我有一个带有
列的数据框Name Date Date_x Date_y A A_x A_y..
,我需要将_z添加到尚未具有_x或_y的列(“名称”列除外)中。因此,我希望输出类似于
Name Date_z Date_x Date_y A_z A_x A_y...
我尝试过
df.iloc[:,~df.columns.str.contains('x|y|Name')]=df.iloc[:,~df.columns.str.contains('x|y|Name')].add_suffix("_z")
# doesn't add suffixes and replaces columns with all nans
df.columns=df.columns.map(lambda x : x+'_z' if "x" not in x or "y" not in x else x)
#many variations of this but seems to add _z to all of the column names
答案 0 :(得分:4)
怎么样:
df.columns = [x if x=='Name' or '_' in x else x+'_z' for x in df.columns]
答案 1 :(得分:1)
您也可以尝试:
df.rename(columns = lambda x: x if x=='Name' or '_' in x else x+'_z')
从Quang Hoang偷了一点;)
答案 2 :(得分:0)
在列存根重复且没有后缀的地方添加“ _z”。
m = (df.columns.str.split('_').str[0].duplicated(keep=False)
& ~df.columns.str.contains('_'))
df.columns = df.columns.where(~m, df.columns+'_z')
答案 3 :(得分:0)
我将按以下方式使用index.putmask
:
m = (df.columns == 'Name') | df.columns.str[-2:].isin(['_x','_y'])
df.columns = df.columns.putmask(~m, df.columns+'_z')
In [739]: df.columns
Out[739]: Index(['Name', 'Date_z', 'Date_x', 'Date_y', 'A_z', 'A_x', 'A_y'], dty
pe='object')