考虑具有以下列的数据框
>>> df.columns
Index(['foo', 'bar', 'baz', 'twobaz', 'threebaz'], dtype='object', name='col')
现在,假设您希望仅在最后两列中将字符串 baz 替换为字符串 BAZ,为此,一种可能的方法是选择最后两列,然后替换其中的字符串列并将它们与其余列组合在一起
df.columns = [*df.columns[:3], *df.columns[3:].str.replace('baz', 'BAZ', regex=True)]
>>> df.columns
Index(['foo', 'bar', 'baz', 'twoBAZ', 'threeBAZ'], dtype='object')
另一种可能的方法是使用数据帧的rename 方法,使用rename 方法的好处是它保留了索引名称(如果有)
c = df.columns[3:]
df = df.rename(columns=dict(zip(c, c.str.replace('baz', 'BAZ', regex=True))))
>>> df.columns
Index(['foo', 'bar', 'baz', 'twoBAZ', 'threeBAZ'], dtype='object', name='col')