簡體   English   中英

如何將每個嵌套字典的元素轉換為新的 pandas 列?

[英]How to convert each nested dictionary' element to a new pandas column?

我有以下 pandas dataframe 結構。 有兩 (2) 列: idinfo (對象)

                    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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM