给出pandas DataFrame,如何将后缀“ _old”添加到除两列Id
和Name
之外的所有列中?
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'])
答案 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