简体   繁体   English

如何将列表解析为 pandas dataframe 中的列

[英]How can I parse a list to columns in a pandas dataframe

I've pulled some JSON data, but I have a list within a list I want to explode out.我已经提取了一些 JSON 数据,但是我想在列表中列出一个列表。 I have one list ORDERS and then a list within that called ITEMS.我有一个列表 ORDERS,然后是一个名为 ITEMS 的列表。

I have converted to a data frame so that I have the information I need eg我已转换为数据框,以便获得所需的信息,例如

Order Number    items
999999999       {'orderItemId': 1111111, 'sku': 'AAA-BBB'}
888888888       {'orderItemId': 2222222, 'sku': 'AAA-CCC'}
777777777       {'orderItemId': 3333333, 'sku': 'BBB-CCC'}

Both data types are now Objects - how can I parse/demlimit what is in the items column so I have this as as one dataframe eg两种数据类型现在都是对象 - 我如何解析/分解项目列中的内容,所以我将其作为一个 dataframe 例如

Order Number     orderItemId         sku
999999999       11111111            AAA-BBB
888888888       22222222            AAA-CCC
777777777       33333333            BBB-CCC

Right now, this is what I have to pull the data from the request, parse the ORDER data and then just select the orderNumber column from this order data and the items list现在,这就是我必须从请求中提取数据,解析 ORDER 数据,然后只是 select 这个订单数据和项目列表中的 orderNumber 列

Any suggestions how this can be done cleaner appreciated任何建议如何做到这一点更清洁表示赞赏

df = response.json()
df = (df["orders"])
df = pd.DataFrame.from_dict(df)
df = df[['orderNumber', 'items']]
df = df.explode('items')

Here is what you need to do to deal with the items column:以下是您需要执行的处理items列的操作:

df['items'] = df["items"].apply(lambda x : dict(eval(x)))
df2 = df["items"].apply(pd.Series)

which return哪个返回

   orderItemId      sku
0      1111111  AAA-BBB
1      2222222  AAA-CCC
2      3333333  BBB-CCC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM