是否可以使用loc和replace函数来替换一定范围内的列的部分列名?我已经尝试在几个变体中组合了replace和loc函数,但是没有成功。或者,是否有任何替代方案可以更改列范围中的部分列名。
df.columns = df.columns.str.replace('j','rep',regex=True)
df.loc[:, 10:]非常感谢,致以问候
发布于 2021-08-28 12:42:17
考虑包含以下列的数据帧
>>> 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')https://stackoverflow.com/questions/68964135
复制相似问题