【问题标题】:Converting an excel columns with each cell like a dictionary to multiple pandas columns [duplicate]将每个单元格的excel列(如字典)转换为多个pandas列[重复]
【发布时间】:2020-11-28 08:04:57
【问题描述】:
# test.csv
co11,col2
a,"{'Country':'USA', 'Gender':'Male'}"
b,"{'Country':'China', 'Gender':'Female'}"

df = pd.read_csv('test.csv')
  • 我在 csv 文件中有一个列,每个单元格都包含一个类似于 python 字典的数据结构。
  • 我应该如何使用 Python 将 csv 中的这个单元格转换为名为 Country 和 Gender 的两列?

【问题讨论】:

    标签: python csv dictionary json-normalize


    【解决方案1】:

    test.csv

    • 我在 csv 文件中有一个列
    co11,col2
    a,"{'Country':'USA', 'Gender':'Male'}"
    b,"{'Country':'China', 'Gender':'Female'}"
    

    代码

    import pandas as pd
    from ast import literal_eval
    
    # read the csv and convert string to dict
    df = pd.read_csv('test.csv', converters={'col2': literal_eval})
    
    # display(df)
      co11                                      col2
    0    a      {'Country': 'USA', 'Gender': 'Male'}
    1    b  {'Country': 'China', 'Gender': 'Female'}
    
    # unpack the dictionaries in col2 and join then as separate columns to df
    df = df.join(pd.json_normalize(df.col2))
    
    # drop col2
    df.drop(columns=['col2'], inplace=True)
    
    # df
      co11 Country  Gender
    0    a     USA    Male
    1    b   China  Female
    

    【讨论】:

      【解决方案2】:

      读取 CSV 文件:
      需要 ast.literal_eval 否则 pd.read_csv 会将字典读取为字符串

      import ast
      
      df = pd.read_csv('/data_with_dict.csv', converters={'dict_col': ast.literal_eval})
      

      处理包含字典的数据帧:

      # Example dataframe
      df = pd.DataFrame({'unk_col' : ['foo','bar'], 
                         'dict_col': [{'Country':'USA',   'Gender':'Male'}, 
                                      {'Country':'China', 'Gender':'Female'}]})
      
      # Convert dictionary to columns
      df = pd.concat([df.drop(columns=['dict_col']), df['dict_col'].apply(pd.Series)], axis=1)
      
      # Write to file
      df.to_csv(''/data_no_dict.csv'', index=False)
      
      print(df)
      

      输出:

        unk_col Country  Gender
      0     foo     USA    Male
      1     bar   China  Female
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-27
        • 2021-11-08
        • 2021-05-05
        • 2017-12-04
        • 2017-02-20
        • 1970-01-01
        • 2022-01-19
        • 1970-01-01
        相关资源
        最近更新 更多