我有這樣的 Excel 資料
Category Item
old apple
new mango
old grape
new ginger
我需要使用字典格式的熊貓在 python 中獲取該資料,例如 -
{'old': ['apple', 'grape'], 'new': ['mango', ginger']}
從堆疊溢位的參考之一他們提供這樣的代碼
import pandas as pd
df = pd.read_excel("Skills.xlsx", index_col=0)
df = df.where(pd.notnull(df), None)
print(df.to_dict())
我越來越喜歡輸出
{'Skills': {'old': 'grape', 'new': 'ginger'}}
但我需要這樣的輸出
{'Skills': {'old': ['apple', 'grape'], 'new': ['mango', ginger']}}
uj5u.com熱心網友回復:
之后可以使用apply函式groupby。
df
Category Item
0 old apple
1 new mango
2 old grape
3 new ginger
df.groupby('Category')['Item'].apply(list).to_dict()
{'new': ['mango', 'ginger'], 'old': ['apple', 'grape']}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/521236.html
