Pandas如何为列名添加后缀(附实例)

204 阅读1分钟

你可以使用以下方法为pandas DataFrame中的列名添加后缀:

方法1:为所有列名添加后缀

df = df.add_suffix('_my_suffix')

方法2:为特定列名添加后缀

#specify columns to add suffix to
cols = ['col1', 'col3']

#add suffix to specific columns
df = df.rename(columns={c: c+'_my_suffix' for c in df.columns if c in cols})

下面的例子展示了如何在下面的pandas DataFrame中使用这些方法:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23],
                   'assists': [5, 7, 7, 9, 12, 9],
                   'rebounds': [11, 8, 10, 6, 6, 5],
                   'blocks': [6, 6, 3, 2, 7, 9]})

#view DataFrame
print(df)

   points  assists  rebounds  blocks
0      25        5        11       6
1      12        7         8       6
2      15        7        10       3
3      14        9         6       2
4      19       12         6       7
5      23        9         5       9

方法1:为所有列名添加后缀

下面的代码显示了如何将后缀'_total'添加到所有列名中:

#add '_total' as suffix to each column name
df = df.add_suffix('_total')

#view updated DataFrame
print(df)

   points_total  assists_total  rebounds_total  blocks_total
0            25              5              11             6
1            12              7               8             6
2            15              7              10             3
3            14              9               6             2
4            19             12               6             7
5            23              9               5             9

注意,后缀'_total'已经被添加到所有列名中。

注意:要为列名添加前缀,只需使用add_prefix

方法2:为特定列名添加后缀

下面的代码显示了如何将后缀'_total'只添加到积分助攻列中:

#specify columns to add suffix to
cols = ['points', 'assists']

#add _'total' as suffix to specific columns
df = df.rename(columns={c: c+'_total' for c in df.columns if c in cols})

#view updated DataFrame
print(df)

   points_total  assists_total  rebounds  blocks
0            25              5        11       6
1            12              7         8       6
2            15              7        10       3
3            14              9         6       2
4            19             12         6       7
5            23              9         5       9

请注意,后缀'_total'只被添加到积分助攻列中。

The postPandas: How to Add Suffix to Column Namesappeared first onStatology.