如何用不同的值替換多個列名?理想情況下,我想洗掉列名中的某些字符并替換其他字符。
我必須運行我的 jupyter notebook 兩次才能讓這段代碼作業。有誰知道這是什么原因?另外,我將如何簡化此代碼(我知道只是嵌套 .replace(),但這并不能解決我的問題)。下面發布的片段可能不足以關閉;如果需要,請查看以下指向我的筆記本的鏈接:https ://datalore.jetbrains.com/notebook/iBhSV0RbfC66p84tZsnC24/w3Z6tCriPC5v5XwqCDQpWf/
for col in df.columns:
df.rename(columns={col: col.replace('Deaths - ', '').replace(' - Sex: Both - Age: All Ages (Number)', '')}, inplace=True)
df.rename(columns={col: col.replace(' (deaths)', '')}, inplace=True)
df.rename(columns={col: col.replace(' ', '_')}, inplace=True)
for col in df.columns:
df.rename(columns={col: col.lower()}, inplace=True)
uj5u.com熱心網友回復:
由于“點”,我無法發表評論,但首先 - 避免inplace- https://github.com/pandas-dev/pandas/issues/16529#issuecomment-443763553
要替換多個列中的多個值,您可以使用:
df = df.rename(columns = { ... }).rename(columns = lambda x: x.lower())
它將使用給定的字典重命名,并轉換為小寫。
uj5u.com熱心網友回復:
除了替換,正如您在這里所做的那樣,還有其他幾種方法
# create a list of columns and assign to the DF
cols = ['col1','col2','col3','col4']
df.columns=df.columns = cols
或者
# create a dictionary of current values to the new values
# and update using map
d = {'c1' : 'col1', 'c2': 'col2', 'c3':'col3' , 'c4':'col 4'}
df.columns.map(d)
uj5u.com熱心網友回復:
在查看評論后,這是我想出的解決方案。我希望能夠進一步簡化它。但是,我只需要運行一次程式即可保存列值。
for col in df.columns:
df = df.rename(columns={col: col.lower()
.replace('deaths - ', '')
.replace(' - sex: both - age: all ages (number)', '')
.replace(' (deaths)', '')
.replace(' ', '_')
.replace('amnesty_international', '')}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527124.html
