如何将pandas系列json字符串平面化为datafram

2024-04-26 14:33:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有熊猫数据帧

            date_hour                                            content
0 2016-10-17 00:00:00  [{"81": 0.0, "82": 0.0, "83": 0.0}]
1 2016-10-17 01:00:00  [{"81": 0.0, "82": 0.0, "83": 0.0}]

我想把数据框内容像这样的数据帧

^{pr2}$

我怎样才能做到这一点?在

我试过了:

# work for one item, though I can concat them, but it's slow(I have each json of 7k k/v pairs), took 2.5s for each
pd.read_json(df.head(1).content.item(), orient='records')

Tags: 数据json内容fordatecontentitemone
2条回答

使用str[0]获取第一个元素

pd.DataFrame(df.content.str[0].tolist()).set_index(df.date_hour)

                      81   82   83
date_hour                         
2016-10-17 00:00:00  0.0  0.0  0.0
2016-10-17 01:00:00  0.0  0.0  0.0

你可以用pd系列在apply函数中,将Series对象中的字典转换为列,然后使用pd.concat方法将date_hour列与展开的数据帧绑定:

import pandas as pd
pd.concat([df.date_hour, df.content.apply(lambda x: pd.Series(x[0]))], axis=1)

#             date_hour  81  82  83
#0  2016-10-17 00:00:00 0.0 0.0 0.0
#1  2016-10-17 01:00:00 0.0 0.0 0.0

相关问题 更多 >