[英]How to convert each nested dictionary' element to a new pandas column?
我有以下 pandas dataframe 結構。 有兩 (2) 列: id
和info
(對象)
id info
0 14050000893760073 [{'route_id': '1', 'stop_id': '1'}, {'route_id': '2', 'stop_id': '2'}]
我想將此格式轉換為以下格式:
id route_id stop_id
0 14050000893760073 1 1
1 14050000893760073 2 2
有任何想法嗎? 先感謝您!
df2 = df.explode('info', ignore_index=True)
df2
id info
0 14050000893760073 {'route_id': '1', 'stop_id': '1'}
1 14050000893760073 {'route_id': '2', 'stop_id': '2'}
info_df = df2["info"].apply(pd.Series)
info_df
route_id stop_id
0 1 1
1 2 2
result = pd.concat([df2, info_df], axis=1).drop('info', axis=1)
result
id route_id stop_id
0 14050000893760073 1 1
1 14050000893760073 2 2
首先,分解info
列中的列表。 然后,您從該列創建一個數據系列。 最后,連接info_df
和 dataframe 以給出最終結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.