我有一個熊貓資料框,DF:
| A欄 | B欄 | C欄 |
|---|---|---|
| 蘋果 | 紅色的 | 德克薩斯州 |
| 蘋果 | 紅色的 | 加利福尼亞 |
| 香蕉 | 黃色 | 印第安納州 |
| 香蕉 | 黃色 | 佛羅里達 |
我想以如下形式在字典中獲取它:
{ "Apple red" : ['Texas', 'California'], "Banana yellow" : ['Indiana', 'Florida'] }
其中 Key = A 列和 B 列中字串的串聯(和)
值 = 串列中 C 列(基于 groupby)的所有對應字串。
我不確定如何實作這一目標。
關鍵說明:如果要為字典的鍵分組超過 3 列,它也應該作業
uj5u.com熱心網友回復:
嘗試:
x = dict(
df.groupby(df["Column A"] " " df["Column B"])["Column C"].agg(list)
)
print(x)
印刷:
{'Apple red': ['Texas', 'California'], 'Banana yellow': ['Indiana', 'Florida']}
uj5u.com熱心網友回復:
一個也應該是高性能的選項是使用默認字典:
from collections import defaultdict
out = defaultdict(list)
for a, b, c in zip(df['Column A'], df['Column B'], df['Column C']):
key = a " " b
out[key].append(c)
out
defaultdict(list,
{'Apple red': ['Texas', 'California'],
'Banana yellow': ['Indiana', 'Florida']})
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/519463.html
下一篇:選定列乘以給定向量
