【问题标题】:pandas/python: combining replace and loc for replacing part of column names within a rangepandas/python:结合 replace 和 loc 用于替换范围内的部分列名
【发布时间】:2021-10-28 00:38:16
【问题描述】:

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

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

非常感谢,问候

【问题讨论】:

    标签: python pandas dataframe replace pandas-loc


    【解决方案1】:

    考虑具有以下列的数据框

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-18
      • 2021-03-31
      • 2013-10-20
      • 1970-01-01
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 2021-10-24
      相关资源
      最近更新 更多