gpt4 book ai didi

pandas - 将 Pandas 数据帧转换为具有多个键的字典

转载 作者:行者123 更新时间:2023-12-04 17:15:14 25 4
gpt4 key购买 nike

我正在尝试将数据框转换为具有四个键的字典,这些键都来自列。我还有多个列,我想使用从这四列构建的键返回值。我研究了一种循环方式,但最终出现了内存错误。我很好奇有没有更有效的方法?

数据框如下所示:

    Service Bill Weight Zone    Resi    UPS FedEx   USPS    DHL
1DEA 1 2 N 33.02 9999 9999 9999
1DEA 2 2 N 33.02 9999 9999 9999
1DEA 3 2 N 33.02 9999 9999 9999

我想为每个运营商提供一个 key ,如下所示:
    price[('1DEA', '1', '2', 'N', 'UPS')]=33.02
price[('1DEA', '1', '2', 'N', 'FedEx')]=9999

我试过这个:
    price = {}
carriers = ['UPS', 'FedEx', 'USPS','DHL']
for carrier in carriers:
for row in rate_keys.to_dict('records'):
key = (row['Service'], row['Bill Weight'], row['Zone'],
row['Resi'], carrier)
rate_keys[key] = row[carrier]

最佳答案

将索引设置为除载体列之外的所有列,然后堆叠。

df.set_index(['Service', 'Bill Weight', 'Zone', 'Resi']).stack().to_dict()

{('1DEA', 1, 2, 'N', 'DHL'): 9999.0,
('1DEA', 1, 2, 'N', 'FedEx'): 9999.0,
('1DEA', 1, 2, 'N', 'UPS'): 33.02,
('1DEA', 1, 2, 'N', 'USPS'): 9999.0,
('1DEA', 2, 2, 'N', 'DHL'): 9999.0,
('1DEA', 2, 2, 'N', 'FedEx'): 9999.0,
('1DEA', 2, 2, 'N', 'UPS'): 33.02,
('1DEA', 2, 2, 'N', 'USPS'): 9999.0,
('1DEA', 3, 2, 'N', 'DHL'): 9999.0,
('1DEA', 3, 2, 'N', 'FedEx'): 9999.0,
('1DEA', 3, 2, 'N', 'UPS'): 33.02,
('1DEA', 3, 2, 'N', 'USPS'): 9999.0}

理解
{(*r[:4], c): v for r in df.values for c, v in zip(df.columns[4:], r[4:])}

{('1DEA', 1, 2, 'N', 'DHL'): 9999,
('1DEA', 1, 2, 'N', 'FedEx'): 9999,
('1DEA', 1, 2, 'N', 'UPS'): 33.02,
('1DEA', 1, 2, 'N', 'USPS'): 9999,
('1DEA', 2, 2, 'N', 'DHL'): 9999,
('1DEA', 2, 2, 'N', 'FedEx'): 9999,
('1DEA', 2, 2, 'N', 'UPS'): 33.02,
('1DEA', 2, 2, 'N', 'USPS'): 9999,
('1DEA', 3, 2, 'N', 'DHL'): 9999,
('1DEA', 3, 2, 'N', 'FedEx'): 9999,
('1DEA', 3, 2, 'N', 'UPS'): 33.02,
('1DEA', 3, 2, 'N', 'USPS'): 9999}

关于pandas - 将 Pandas 数据帧转换为具有多个键的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52192177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com