【问题标题】:Removing special characters from column headers [duplicate]从列标题中删除特殊字符[重复]
【发布时间】:2021-07-27 09:54:43
【问题描述】:

我使用to_flat_index() 来展平列,并最终得到像('Method', 'sum') 这样的列名。我正在尝试从这些中删除特殊字符。但是当我尝试删除它们时,它会将所有列名更改为nan

函数尝试: df_pred.columns = df_pred.columns.str.replace("[(,),']", '')

预期结果:MethodSum

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您的列似乎是多索引的,因为您使用to_flat_index

    >>> df
            bar                 baz                 foo                 qux
            one       two       one       two       one       two       one       two
    0  0.713825  0.015553  0.036683  0.388443  0.729509  0.699883  0.125998  0.407517
    1  0.820843  0.259039  0.217209  0.021479  0.845530  0.112166  0.219814  0.527205
    2  0.734660  0.931206  0.651559  0.337565  0.422514  0.873403  0.979258  0.269594
    3  0.314323  0.857317  0.222574  0.811631  0.313495  0.315072  0.354784  0.394564
    4  0.672068  0.658103  0.402914  0.430545  0.879331  0.015605  0.086048  0.918678
    

    试试:

    >>> df.columns.to_flat_index().map(''.join)
    Index(['barone', 'bartwo', 'bazone', 'baztwo',
           'fooone', 'footwo', 'quxone', 'quxtwo'],
          dtype='object')
    

    【讨论】:

    • 谢谢你,这很好用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 2020-11-19
    • 2022-07-19
    • 2014-05-14
    • 2012-12-16
    • 1970-01-01
    • 2016-11-30
    相关资源
    最近更新 更多