For循环,用于从列名中删除字符串模式

时间:2018-08-24 16:06:46

标签: python-3.x pandas

如果(1)列名包含“ eTIV”或“ eTIV1”,我尝试在“ df_merged”数据框中从列名中删除“ _Adj”。

for col in df_merged.columns:
    if 'eTIV1' in col or 'eTIV' in col:
        df_merged.columns.str.replace('_Adj', '')

此代码似乎产生以下错误:

KeyError:“ []在轴上找不到”

1 个答案:

答案 0 :(得分:1)

这里有两个选项:

选项1

df_merged.columns = [col.replace('_Adj','') if 'eTIV' in col else col for col in list(df_merged.columns)]

选项2

df_merged = df_merged.rename(columns={col: col.replace('_Adj','') if 'eTIV' in col else col for col in df_merged.columns})