我有以下字典:
{'instance_1': {'race': {'asian': 0,
'black': 99,
'white': 9},
'dominant_race': 'black',
'region': {'x': 0, 'y': 0, 'w': 100, 'h': 100}},
'instance_2': {'race': {'asian': 0,
'black': 0,
'white': 89},
'dominant_race': 'white',
'region': {'x': 6, 'y': 12, 'w': 79, 'h': 79}}}
并希望將其轉換為 Pandas 資料框,以便每個專案中的每個元素都是它自己的列,例如
| 物品 | 亞洲人 | 黑色的 | 白色的 | 優勢種族 | X | 是 | 瓦 | H |
|---|---|---|---|---|---|---|---|---|
| 實體_1 | 0 | 99 | 9 | 黑色的 | 0 | 0 | 100 | 100 |
| 實體_2 | 0 | 0 | 89 | 白色的 | 6 | 12 | 79 | 79 |
使用pd.DataFrame.to_dict()與東方=索引產生以下結果
pd.DataFrame.from_dict(predictions, orient='index')
race dominant_race \
instance_1 {'asian': 0, 'black': 99.... black
instance_2 {'asian': 0, 'black': 0..... white
region
instance_1 {'x': 0, 'y': 0, 'w': 100, 'h': 100}
instance_2 {'x': 6, 'y': 12, 'w': 79, 'h': 79}
如何轉換字典,以便“race”和“region”中的每個元素都是自己的列?
uj5u.com熱心網友回復:
.apply(pd.Series) 會將單元格中的字典分解為不同的列。
假設上面的示例很好地表示了您的真實資料,您可以先使用pd.DataFrame().T,然后使用concat來組合來自 region 和 Race 的新形成的列:
df = pd.DataFrame(d).T # d being your sample dictionary
res = pd.concat([df['race'].apply(pd.Series),
df['dominant_race'],
df['region'].apply(pd.Series)], axis=1)
這將列印:
res
Out[262]:
asian black white dominant_race x y w h
instance_1 0 99 9 black 0 0 100 100
instance_2 0 0 89 white 6 12 79 79
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/350564.html
