您好,我有一個具有以下結構的資料框:
Index A B C D E
3 foo bar 0 1 [{'A': 1, 'B': 'text', 'C': 3}, {'A': 2, 'B': 'other', 'C': 2}]
4 foo bar 0 1 [{'A': 3, 'B': 'foo', 'C': 4}, {'A': 6, 'B': 'bar', 'C': 8}]
使用 loc 我得到索引和 E 列
df2 = df.loc[:, ['E']]
Index E
3 [{'A': 1, 'B': 'text', 'C': 3}, {'A': 2, 'B': 'other', 'C': 2}]
4 [{'A': 3, 'B': 'foo', 'C': 4}, {'A': 6, 'B': 'bar, 'C': 8}]
但我需要的是這個結構
Index A B C
3 1 text 3
3 2 other 2
4 3 foo 4
4 6 bar 8
我認為遍歷行,提取陣列并為每個行創建另一個 df 將起作用,但我希望可以找到更有效的解決方案。
提前致謝。
uj5u.com熱心網友回復:
您可以使用explode展平列然后創建資料框:
out = pd.DataFrame(df['E'].explode().tolist())
print(out)
# Output
A B C
0 1 text 3
1 2 other 2
2 3 foo 4
3 6 bar 8
要保留索引:
out = df['E'].explode()
out = pd.DataFrame(out.tolist(), index=out.index)
print(out)
# Output
A B C
3 1 text 3
3 2 other 2
4 3 foo 4
4 6 bar 8
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/428704.html
