我有一個資料框并做了一些特征工程,現在想更改列名。如果我做一個新的任務,我知道如何改變它們,但我想用方法鏈來做。我嘗試了下面的(rename行)但它不起作用。我怎么寫才能讓它起作用?
df = pd.DataFrame({'ID':[1,2,2,3,3,3], 'date': ['2021-10-12','2021-10-16','2021-10-15','2021-10-10','2021-10-19','2021-10-01'],
'location':['up','up','down','up','up','down'],
'code':[False, False, False, True, False, False]})
df = (df
.assign(date = lambda x: pd.to_datetime(x.date))
.assign(entries_per_ID = lambda x: x.groupby('ID').ID.transform('size'))
.pivot_table(values=['entries_per_ID'], index=['ID','date','code'],
columns=['location'], aggfunc=np.max)
.reset_index()
#.rename(columns=lambda x: dict(zip(x.columns, ['_'.join(col).strip() if col[1]!='' else col[0] for col in x.columns.values])))
)
這在這里有效,但這不是我想要的寫法。
df.columns = ['_'.join(col).strip() if col[1]!='' else col[0] for col in df.columns.values ]
uj5u.com熱心網友回復:
要df.columns在鏈中設定,請使用set_axis(..., axis=1):
df.set_axis(['_'.join(col).strip() if col[1] else col[0] for col in df.columns], axis=1)
在這種情況下,set_axis需要管道的結果,所以pipe它:
df = (df
.assign(date = lambda x: pd.to_datetime(x.date))
.assign(entries_per_ID = lambda x: x.groupby('ID').ID.transform('size'))
.pivot_table(values=['entries_per_ID'], index=['ID','date','code'],
columns=['location'], aggfunc=np.max)
.reset_index()
.pipe(lambda x: x.set_axis(['_'.join(col).strip() if col[1] else col[0] for col in x.columns], axis=1))
)
# ID date code entries_per_ID_down entries_per_ID_up
# 0 1 2021-10-12 False NaN 1.0
# 1 2 2021-10-15 False 2.0 NaN
# 2 2 2021-10-16 False NaN 2.0
# 3 3 2021-10-01 False 3.0 NaN
# 4 3 2021-10-10 True NaN 3.0
# 5 3 2021-10-19 False NaN 3.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/331177.html
