【问题标题】:How to remove numbers from all column names / headers in a dataframe如何从数据框中的所有列名/标题中删除数字
【发布时间】:2019-10-24 23:51:24
【问题描述】:

嗨,我有一个列名以“2018”结尾的数据框

我需要从这些列名中删除年份,但遇到了一些麻烦。我还需要从这些列名中去除前导和尾随空格。

我已经尝试过以下方法:

df.columns.str.replace('\d+',"") #to try and remove the numbers from the column names

df.columns = df.columns.str.strip('') #to try and get rid of the spaces

这些对数据框没有任何作用。

我希望列名从“Stock 2018”变为“Stock”

但这并没有发生。感谢您的帮助!

【问题讨论】:

    标签: python pandas iteration renaming


    【解决方案1】:

    您也可以尝试使用正则表达式..

    示例数据框:

    >>> df = pd.DataFrame.from_dict({'Name04': ['Chris', 'Joe', 'Karn', 'Alina'], 'Age04': [14, 16, 18, 21], 'Weight04': [15, 21, 37, 45]})                                 
    
    >>> df
       Age04 Name04  Weight04
    0     14  Chris        15
    1     16    Joe        21
    2     18   Karn        37
    3     21  Alina        45
    

    结果使用regex:

    >>> df.columns = df.columns.str.replace(r'\d+', '')
    >>> df
       Age   Name  Weight
    0   14  Chris      15
    1   16    Joe      21
    2   18   Karn      37
    3   21  Alina      45
    

    【讨论】:

      【解决方案2】:

      您只需分配给df.columns 即可删除数字,也不要将任何内容传递给str.strip() 以删除前导/尾随空白字符。

      df.columns=df.columns.str.replace('\d+','').str.strip()
      

      【讨论】:

        【解决方案3】:

        您没有使用正确的方式重命名 pandas 中的列:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html

        从文档看来,您可以简单地执行以下操作:

        df = df.rename(str.replace('\d+',""), axis='columns')
        

        让我知道这是否适合你。

        【讨论】:

        • 嗨!我得到一个 TypeError “replace() 至少需要 2 个参数(1 个给定)
        • 你给出的 TypeError 是什么,如果更容易的话,你可以用 pastebin 回复
        猜你喜欢
        • 2021-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-07
        • 2016-08-09
        • 2022-11-18
        • 2019-06-26
        • 1970-01-01
        相关资源
        最近更新 更多