pandas/python:结合replace和loc用于替换范围内的部分列名

pandas/python: combining replace and loc for replacing part of column names within a range

是否可以使用 loc 和 replace 函数来替换一系列列的部分列名?我已经尝试将 replace 和 loc 函数组合成几个变体,但是没有成功。或者是否有任何替代方法可以更改一系列列中的部分列名。

df.columns = df.columns.str.replace('j','rep',regex=True)
df.loc[:, 10:]

非常感谢,问候

考虑具有以下列的数据框

>>> df.columns
Index(['foo', 'bar', 'baz', 'twobaz', 'threebaz'], dtype='object', name='col')

现在,假设您希望仅在最后两列中将字符串 baz 替换为字符串 BAZ,为此,一种可能的方法是 select最后两列然后替换这些列中的字符串并将它们与其余列组合回去

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