![](/img/trans.png)
[英]python pandas dataFrame create single json column of multiple columns value
[英]Python how to create a dictionary using the values in multiple pandas dataframe columns as tuple keys and a single column as value
我想創建一個字典,使用 pandas 數據框中的多列值作為元組鍵,單列值作為值。 如果特定元組對沒有值,我想分配一個通用值,比如 99999。這后一部分被證明是一個挑戰,我希望從這個論壇尋求幫助,了解如何完成這項任務。 謝謝你。
示例提取數據:
期間(天) | 工廠 | 倉庫 | 銷售網點 | 產品 | 遠程事實倉庫 | |
---|---|---|---|---|---|---|
0 | 1個 | 柏林 | 泰爾托 | 馬格德堡 | 馬拉庫哈 | 19.6 |
1個 | 2個 | 漢堡 | 維斯馬 | 呂貝克 | 辛貝爾 | 126.2 |
2個 | 3個 | 柏林 | 小機器 | 哈雷 | 馬拉加 | 26.9 |
3個 | 4個 | 漢堡 | 維斯馬 | 呂貝克 | 瓦爾德邁斯特 | 126.2 |
4個 | 5個 | 柏林 | 小機器 | 萊比錫 | 核桃 | 26.9 |
基於上面的數據集,下面的代碼是我如何從數據框中創建我的字典對象:
F = df.Factory.drop_duplicates().to_list()
W = df.Warehouse.drop_duplicates().to_list()
dist1 = {};
for i in df.index:
key = (df.at[i, 'Factory'], df.at[i, 'Warehouse'])
value = df.at[i, 'Dist Fact-Whse']
dicT = {key : value}
dist1.update(dicT)
for f in F:
for w in W:
if (f, w) not in dist1:
dist1[(f, w)] = 9999
我得到了我想要或預期的結果: {('Berlin', 'Teltow'): 19.6, ('Hamburg', 'Wismar'): 126.2, ('Berlin', 'Kleinmachnow'): 26.9, ('Berlin', 'Wismar'): 9999, ('Hamburg', 'Teltow'): 9999, ('Hamburg', 'Kleinmachnow'): 9999},
但這過於繁瑣、耗時且效率不高,因為我有一個類似於“dist1”的其他參數要在我的整個代碼中創建。
我誠摯地歡迎一個更優雅、更聰明的解決方案來解決這個問題。
這是來自itertools的pandas.DataFrame.groupby
和itertools.product
的命題。
d = df.groupby(["Factory","Warehouse"])["Dist Fact-Whse"].first().to_dict()
combs = list(product(df["Factory"].unique(), df["Warehouse"].unique()))
dist1 = {k:v for v,k in zip([d.get(c, 99999) for c in combs], combs)}
這看起來更短(也許更漂亮)但不確定它是否更快。 我會讓你自己試一試!
Output:
print(dist1)
{('Berlin', 'Teltow'): 19.6,
('Berlin', 'Wismar'): 99999,
('Berlin', 'Kleinmachnow'): 26.9,
('Hamburg', 'Teltow'): 99999,
('Hamburg', 'Wismar'): 126.2,
('Hamburg', 'Kleinmachnow'): 99999}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.