我希望使用第一列标题作为前缀来更新熊猫 df 中的最后一列。以下面为例,我想更新 col Z 以包含 col X 作为X_Z。
import pandas as pd
df = pd.DataFrame({
'X' : [1,2,3],
'Y' : [1,2,3],
'Z' : [1,2,3],
})
# Update all cols to include a consistent suffix
df.columns.values[-1:] = [str(col) + '_Col' for col in df.columns[-1:]]
# Update last col to include hard coded string
df.columns = [str(col) + '_Col' for col in df.columns]
请注意:我不想使用以下功能手动更新。列标题会有所不同,所以我不想回去检查第一列是什么并添加它。我希望处理所有案件。
df.rename(columns={'Z': 'X_Z'}, inplace=True)
预期输出:
X Y X_Z
0 1 1 1
1 2 2 2
2 3 3 3
我们可以使用列表索引和f-strings
来做到这一点:
cols = df.columns
df = df.rename(columns={cols[-1]:f'{cols[0]}_{cols[-1]}'})
X Y X_Z
0 1 1 1
1 2 2 2
2 3 3 3
或者我们可以按索引调整我们的列列表,然后将这个调整后的列表传回:
cols = df.columns.tolist()
cols[-1] = f'{cols[0]}_{cols[-1]}'
df.columns = cols
X Y X_Z
0 1 1 1
1 2 2 2
2 3 3 3
奖励:奇怪的开箱即用列表理解:
[df.columns[0] + '_' + col if idx+1 == df.shape[1] else col for idx, col in enumerate(df.columns)]
# Out
['X', 'Y', 'X_Z']