简体   繁体   English

将不包含任何值的字典列表转换为多个 Dataframe 列

[英]Convert list of dictionaries that contain none values into multiple Dataframe columns

I have a Dataframe with 10k rows of different user input text responses.我有一个包含 10k 行不同用户输入文本响应的数据框。 And for each of the responses, several other columns in the Dataframe contain list of dictionaries as below:对于每个响应,Dataframe 中的其他几列包含字典列表,如下所示:

top row of column[0]:列 [0] 的顶行:

{'action': 'CLICK', 'docid': 'url_1', 'position': 1 } {'动作':'点击','docid':'url_1','位置':1}

top row of column[1]:列 [1] 的顶行:

{'action': 'NoAction', 'docid': 'url_2', 'position': 2 }` {'action': 'NoAction', 'docid': 'url_2', 'position': 2 }`

I need to convert this into multiple Dataframe columns and concatenate back to the original file.我需要将其转换为多个 Dataframe 列并连接回原始文件。

I tried to do the following on column[0], it works fine:我尝试在列 [0] 上执行以下操作,效果很好:

top1_list = df[df.columns[0]].tolist()
df_result1 = pd.DataFrame.from_dict(top1_list)
df_result1.columns = ['action_1', 'docid_1', 'position_1']
data1 = pd.concat([df_result1, df], axis=1)

When I tried the same approach on column[1], since for some user input responses, the column[1] is empty.当我在列 [1] 上尝试相同的方法时,因为对于某些用户输入响应,列 [1] 为空。 I got an error of 'NoneType' object has no attribute 'keys' .我收到了'NoneType' object has no attribute 'keys' But if I remove the none value when I convert column[1] to list, then I lost the original index position and can't concatenate back to the original file correctly.但是,如果我在将 column[1] 转换为 list 时删除了 none 值,那么我丢失了原始索引位置并且无法正确连接回原始文件。

So what would be the solution to convert list of dictionaries (that contain none values) into multiple Dataframe columns while keep them at the right index position?那么将字典列表(不包含任何值)转换为多个 Dataframe 列同时将它们保持在正确的索引位置的解决方案是什么?

Thank you!谢谢!

solve the question using使用解决问题

df['result2'].apply(pd.Series) df['result2'].apply(pd.Series)

Thanks.谢谢。

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

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