【发布时间】:2018-04-23 07:01:51
【问题描述】:
数据框列的每一行都是一个字典列表。
我想将字典列表转换为一个新数据框,每个字典都作为我数据框中的一个新单元格。字典的键作为列。每个字典有 44 个键,所以我有 44 列。 我需要对数据框列的所有行(列表)执行此操作,并将每个新转换的数据框单元格附加到现有数据框。
我的问题是,并非我列表中的所有字典都转换为新数据框中的单元格。很多字典都漏掉了。
My data frame column df[‘data’] looks like this:
0 [
{ "name": "Tom", "age": 10 },
{ "name": "Mark", "age": 5 },
{ "name": "Pam", "age": 7 },
{ "name": "Dick", "age": 12 }
]
1 [
{ "name": “Ash", "age": 20 },
{ "name": “Jim", "age": 54 },
{ "name": “Sam", "age": 29 },
{ "name": “Poo", "age": 15 }
]
len(df) = 2
输出应该是这样的:df_all
Name Age
Tom 10
Mark 5
Pam 7
Dick 12
Ash 20
Jim 54
Sam 29
Poo 15
len(df_all) =8
我的代码如下:
#Reading all the rows of the column ‘data’ from the df
data = df['data'].iloc[:1500]
len(data) #1500
#Creating an empty data frame
df_append = pd.DataFrame([])
#Iterating over all rows(lists of dictionaries) of a data frame and converting
#each list to a data frame and keep appending to it.
for each_item in data:
df_each_row = pd.DataFrame(each_item)
df_all = df_append.append(df_each_row)
df_all
len(df_all) #501
如果“数据”中的每一行(列表)有 10 个字典,那么最终数据帧中应该有 1500*10(15000) 行。相反,我只得到 501 行。但是,我正确地得到了 44 列。
【问题讨论】:
-
抱歉,您能在问题中在这里发布几行数据吗?如果没有那么多,要可视化您的问题或制定解决方案并不容易。
-
df['data']中是否有可能只有501个索引值,直到索引1500? -
@cᴏʟᴅsᴘᴇᴇᴅ 我已经更新了我的示例输入以及我希望我的输出如何。谢谢。
-
谢谢,推翻了投票。
-
@andrew_reece 是的,可能是这样。那么有什么办法可以解决这个问题呢?请问有什么建议吗?谢谢。
标签: python pandas loops dictionary