【问题标题】:Converting pandas dataframe to dictionary while modifying column names在修改列名时将熊猫数据框转换为字典
【发布时间】:2022-01-15 20:41:12
【问题描述】:

如何转换数据框,例如如下所示:

id    | column! 1 | column 2?> | column 3
ABC1  | 1234      | text text  | text!
ABC2  | 1234      | text text  | text!

进入字典,但同时转换列名以删除特殊字符和空格。转换可能类似于label_id = re.sub('[^A-Za-z0-9]+', '', str(label_name)),但我不确定如何将其应用于数据框 -> 字典转换。

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    在带有'\W+' 的列上使用str.replace\W 匹配任何非单词字符。

    d = df.rename(columns=dict(zip(df.columns, df.columns.str.replace('\W+', '', regex=True)))).to_dict()
    print(d)
    
    # Output:
    {'id': {0: 'ABC1', 1: 'ABC2'},
     'column1': {0: 1234, 1: 1234},
     'column2': {0: 'text text', 1: 'text text'},
     'column3': {0: 'text!', 1: 'text!'}}
    

    详情:

    >>> dict(zip(df.columns, df.columns.str.replace('\W+', '', regex=True)))
    
    # Output:
    {'id': 'id',
     'column! 1': 'column1',
     'column 2?>': 'column2',
     'column 3': 'column3'}
    

    或更简单的

    df.columns = df.columns.str.replace('\W+', '', regex=True)
    print(df)
    
    # Output:
         id  column1    column2 column3
    0  ABC1     1234  text text   text!
    1  ABC2     1234  text text   text!
    

    【讨论】:

    • 注意\w[^A-Za-z0-9]不等价,\w还包括下划线;)
    • 你的意思是\W
    • 是的,当然是\W(或\w/[A-Za-z0-9]);)
    猜你喜欢
    • 2019-07-18
    • 2017-12-12
    • 2018-11-25
    • 1970-01-01
    • 2018-07-14
    • 2019-05-07
    • 2016-09-06
    • 1970-01-01
    相关资源
    最近更新 更多