gpt4 book ai didi

python - 将 Json/Dict 响应保存到数据帧 - 它们在导出时转换为字符串。如何避免这种情况?

转载 作者:行者123 更新时间:2023-12-01 07:22:34 25 4
gpt4 key购买 nike

我正在运行 API 并将响应保存为字典 response.to_dict()到一个新列以供稍后引用。

示例数据框:

dict1 = {'thing': 200,
'other thing': 18,
'available_data': {'premium': {'emails': 1}},
'query': {'names': [{'first': 'John','last': 'Smith'}]}}

dict2 = {'thing': 123,
'other thing': 13,
'available_data': {'premium': {'emails': 1}},
'query': {'names': [{'first': 'Foo','last': 'Bar'}]}}


dict_frame = pd.DataFrame({'customers':['John','Foo'],
'api_response':[dict1,dict2]})

print(dict_frame)

customers api_response
0 John {'thing': 200, 'other thing': 18, 'available_d...
1 Foo {'thing': 123, 'other thing': 13, 'available_d...

我们可以看到数据仍然是dict类型:

type(dict_frame.loc[1,'api_response'])

dict

但是,如果我将其保存到文件并重新加载它,数据现在是一个字符串。

# save to file
dict_frame.to_csv('mydicts.csv')

# reload dataframe
dict_frame = pd.read_csv('mydicts.csv')

# check type
type(dict_frame.loc[1,'api_response'])

#it's a string
str

通过一些谷歌搜索,我看到有一个包可以将其转换回字典:

from ast import literal_eval

python_dict = literal_eval(first_dict)

它有效,但我有一种感觉,首先有一种方法可以避免这种情况。有什么建议吗?

我试过dtype={'api_response': dict}在读取 csv 时,但是 TypeError: dtype '<class 'dict'>' not understood

最佳答案

这是 CSV 文件类型的限制:所有内容都会转换为文本。 pandas 在读回文本时必须猜测数据类型。您可以指定一个转换器:

from ast import literal_eval
dict_frame_csv = pd.read_csv('mydicts.csv', converters={'api_response': literal_eval})

关于python - 将 Json/Dict 响应保存到数据帧 - 它们在导出时转换为字符串。如何避免这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57629224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com