如何在某些列之外的列名中添加后缀?

时间:2018-11-19 18:04:07

标签: python pandas

给出pandas DataFrame,如何将后缀“ _old”添加到除两列IdName之外的所有列中?

import pandas as pd
data = [[1,'Alex',22,'single'],[2,'Bob',32,'married'],[3,'Clarke',23,'single']]
df = pd.DataFrame(data,columns=['Id','Name','Age','Status'])

3 个答案:

答案 0 :(得分:3)

您可以重新分配数据框的列:

>>> df
   Id    Name  Age   Status
0   1    Alex   22   single
1   2     Bob   32  married
2   3  Clarke   23   single
>>> 
>>> keep_same = {'Id', 'Name'}
>>> df.columns = ['{}{}'.format(c, '' if c in keep_same else '_old')
...:               for c in df.columns]
>>>
>>> df
   Id    Name  Age_old Status_old
0   1    Alex       22     single
1   2     Bob       32    married
2   3  Clarke       23     single

答案 1 :(得分:3)

您可以使用 rename 方法获取 {column:new_name} 的字典:

df = df.rename(columns={col: col+'_old' 
                        for col in df.columns if col not in ['Id', 'Name']})

答案 2 :(得分:1)

使用map

df.columns=df.columns.map(lambda x : x+'_old' if x !='Id' and x!='Name' else x)
df
Out[181]: 
   Id    Name  Age_old Status_old
0   1    Alex       22     single
1   2     Bob       32    married
2   3  Clarke       23     single