[英]Pandas DataFrame to dictionary of lists of lists
我有包含四列的 CSV 文件:product_price、country_of_origin、product_quantity 和 brand_id。 這就是 csv 的樣子我想創建一個字典,其中鍵是brand_id,值是包含其他列的元組/列表列表。 類似的東西:
some_dict = {
1:
[(country_of_origin, product_quantity, product_price),
(country_of_origin, product_quantity, product_price),
(country_of_origin, product_quantity, product_price)],
2:
[(country_of_origin, product_quantity, product_price),
(country_of_origin, product_quantity, product_price)],
3:
[(country_of_origin, product_quantity, product_price),
(country_of_origin, product_quantity, product_price)]
}
有可能用熊貓創建這樣的結構嗎? 我試過在 df.itertuples(index=False)} 中使用 {x[3]: x[0:] for x 但它每個brand_id 只返回一個值:
{1: (200, 'Kenya', 19), 3: (40, 'South Africa', 40), 2: (350, 'Turkey', 64)}
您可以將dict comprehension
與groupby
brand_id
和DataFrame.iterrows
:
some_dict = {k: [(co, pq, pp) for _, (pp, co, pq, _) in x.iterrows()]
for k, x in df.groupby('brand_id')}
[出去]
{1: [('Kenya', 19, 200), ('Turkey', 25, 35), ('Jordan', 53, 16)],
2: [('Turkey', 64, 350), ('Jordan', 24, 80)],
3: [('South Africa', 5, 40), ('Oman', 8, 63)]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.