给定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'])

最佳答案

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

>>> 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

关于python - 如何在某些列之外的列名中添加后缀?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53380310/

10-14 18:19