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



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

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

many thanks, regards

考虑包含以下列的数据框架

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

最新更新