python - 将 panda 列中的 json 字符串值提取到第一级具有动态键的新列中

标签 python json pandas dataframe

您好,我在 csv 文件中有一个非常大的数据集,我将其读入 Pandas 数据框。一列有我想将值提取到新列中的 json 字符串。下图显示了我的 csv 文件中的几行。

this is example of my csv datafile.

第四列(数据)是需要提取的列。第一级中的 key (605,254,834,265 等)始终在变化,但数字始终与最后一列('reg')中的数字相同。我想提取“价格”、“状态”和“#result”的值并将它们放入新列中。

我使用的代码是

import pandas as pd
import numpy as np
import json
from pandas import DataFrame
df = pd.read_csv('sample.csv')
df["result"]=np.nan #create empty column
df["price"]=np.nan
df["status"]=np.nan
for i in range (0,len(df['data'])):
      df['result'].iloc[i]=json.loads(df['data'].iloc[i])[str(df['reg'].iloc[i])]['#result']
      df['price'].iloc[i]=json.loads(df['data'].iloc[i])[str(df['reg'].iloc[i])]['price']
      df['status'].iloc[i]=json.loads(df['data'].iloc[i])[str(df['reg'].iloc[i])]['status']

print(df)

所以我得到了包含新列(结果、价格和状态)的数据框,如下所示:

enter image description here

代码给出了我想要的输出。但是,由于我使用的是“for 循环”,因此运行大数据帧需要很长时间。我认为必须有更聪明的方法来做到这一点。而且我知道如果第一级 key 不变,则有不同的方法。谁能有更好的主意在 Pandas 框架中提取这种类型的 json 字符串。 干杯!

最佳答案

在您的示例中,您多次解析相同的 JSON。只解析一次就足够了。例如:

import pandas as pd

d1 = '{"605":{"price":"570", "address":"946", "status": "done", "#result":"good" }}'
d2 = '{"254":{"price":"670", "address":"300", "status": "done", "classification_id": "102312321", "#result":"good" }}'

df = pd.DataFrame({'num': [1771, 905],
                  'item': ['orange', 'mango'],
                  'id': [190384, 2500003],
                  'data':[d1, d2],
                  'reg': [605, 254]
    })


import json
df = df.join( pd.DataFrame(list(json.loads(d).values())[0] for d in df.pop('data')) )

# drop columns we don't want
del df['address']
del df['classification_id']

print(df)

打印:

    num    item       id  reg price status #result
0  1771  orange   190384  605   570   done    good
1   905   mango  2500003  254   670   done    good

关于python - 将 panda 列中的 json 字符串值提取到第一级具有动态键的新列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59423816/

相关文章:

Python/ Pandas : Bug with element-wise division resulting in NaN?

JavaScript 对象文字 - 数据操作

python - 合并具有相同标题的列没有重复的列

python - Matplotlib 绘图和颜色条问题

ios - 使用 Alamofire 在 Swift 中解析 JSON

python - 每当超过某个 cumsum 阈值时如何对 pandas 行进行分组(为每个新组重新启动 cumsum)

python - 如何根据列的值和该列中的下一个值过滤数据帧的行

python - 使用 NaN 获取 pandas 系列模式的最快方法

python - Zapier 频繁超时 10.01 秒

json - 在 Angular 2 中使用 JSON 正文发出 POST 请求