1
# 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 的两列?
4

2 回答 2

0

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
于 2020-08-08T02:14:27.483 回答
0

读取 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
于 2020-08-08T02:19:26.740 回答