删除封装在pandas中的字典类型的字符串引号的最快方法

删除封装在pandas中的字典类型的字符串引号的最快方法,pandas,string,dictionary,export-to-csv,re,Pandas,String,Dictionary,Export To Csv,Re,我有一些pd.DataFrame;其中的元素最初是dict类型的dict。但是,我编写了pd.DataFrame来键入csv。我现在遇到的问题是将文件读回pd.DataFrame字典默认读取为typestring。例如,这是输出,我开始阅读csv文件 df.iloc[0,0] "{'maxAge': 1, 'priceHint': {'raw': 2, 'fmt': '2', 'longFmt': '2'}}" 我想要的输出是删除封装字典的字符串引号”,所以它应该是 期望输

我有一些
pd.DataFrame
;其中的元素最初是dict类型的
dict
。但是,我编写了
pd.DataFrame
来键入
csv
。我现在遇到的问题是将文件读回
pd.DataFrame
字典默认读取为type
string
。例如,这是输出,我开始阅读
csv
文件

df.iloc[0,0]
"{'maxAge': 1, 'priceHint': {'raw': 2, 'fmt': '2', 'longFmt': '2'}}"
我想要的输出是删除封装字典的字符串引号
,所以它应该是

期望输出

df.iloc[0,0]
{'maxAge': 1, 'priceHint': {'raw': 2, 'fmt': '2', 'longFmt': '2'}}
我的
pd.DataFrame
相当大(>30000个元素)。实现这一目标的最快方法是什么?很可能没有运行任何循环。我想,在
pd.read\u csv
级别上的一些选项组合可以实现这一点,但我还没有弄清楚它是如何实现的

编辑1.0

这里有一个
pd.DataFrame
,允许复制输入

df = pd.DataFrame({'col_a':["{'maxAge': 1, 'priceHint': {'raw': 2, 'fmt': '2', 'longFmt': '2'}}",\
                   "{'maxAge': 2, 'priceHint': {'raw': 3, 'fmt': '3', 'longFmt': '3'}}",\
                  "{'maxAge': 2, 'priceHint': {'raw': 3, 'fmt': '3', 'longFmt': '3'}}",\
                  "{'maxAge': 1, 'priceHint': {'raw': 2, 'fmt': '2', 'longFmt': '2'}}"]})

由于字典是字典的字符串表示形式,因此需要使用
eval
方法使其再次像字典一样工作(简单地尝试删除引号不会起任何作用)。最简单的方法是使用
ast.literal\u eval
,这是直接调用python的
eval
方法的更安全的替代方法

df = pd.DataFrame({'col_a':["{'maxAge': 1, 'priceHint': {'raw': 2, 'fmt': '2', 'longFmt': '2'}}",\
                   "{'maxAge': 2, 'priceHint': {'raw': 3, 'fmt': '3', 'longFmt': '3'}}",\
                  "{'maxAge': 2, 'priceHint': {'raw': 3, 'fmt': '3', 'longFmt': '3'}}",\
                  "{'maxAge': 1, 'priceHint': {'raw': 2, 'fmt': '2', 'longFmt': '2'}}"]})

df.iloc[0, 0] # Each element of this Series is a string
# "{'maxAge': 1, 'priceHint': {'raw': 2, 'fmt': '2', 'longFmt': '2'}}"
ast.literal\u eval
与Series.apply一起使用

import ast

df["col_a"] = df["col_a"].apply(ast.literal_eval)

df.iloc[0, 0] # Each element of this Series is a dictionary
# {'maxAge': 1, 'priceHint': {'raw': 2, 'fmt': '2', 'longFmt': '2'}}
或者,由于您是从csv中读取此内容,因此可以在通过
pd.read\u csv
读取数据时应用ast.literal\u eval:

df = pd.read_csv("path/to/file.csv", converters={"col_a": ast.literal_eval})

这不会提高性能,但可以稍微简化代码。

eval
,但您可能仍然需要一个循环。