gpt4 book ai didi

python - 根据条件用不同的替换字典替换 Pandas 数据框列中的值

转载 作者:行者123 更新时间:2023-12-03 15:47:57 25 4
gpt4 key购买 nike

我有一个数据框,我想在其中替换列中的值,但描述替换的字典基于另一列中的值。示例数据框如下所示:

   Map me strings        date
0 1 test1 2020-01-01
1 2 test2 2020-02-10
2 3 test3 2020-01-01
3 4 test2 2020-03-15
我有一本看起来像这样的字典:
map_dict = {'2020-01-01': {1: 4, 2: 3, 3: 1, 4: 2},
'2020-02-10': {1: 3, 2: 4, 3: 1, 4: 2},
'2020-03-15': {1: 3, 2: 2, 3: 1, 4: 4}}
我希望映射逻辑根据日期而不同。
在这个例子中,预期的输出是:
   Map me strings        date
0 4 test1 2020-01-01
1 4 test2 2020-02-10
2 1 test3 2020-01-01
3 4 test2 2020-03-15
我有一个庞大的数据帧(100M+ 行),所以我真的想尽可能避免任何循环解决方案。
我试图想办法使用 map 或 replace 但没有成功

最佳答案

使用 DataFrame.join MultiIndex Series创建者 DataFrame构造函数和 DataFrame.stack :

df = df.join(pd.DataFrame(map_dict).stack().rename('new'), on=['Map me','date'])
print (df)
Map me strings date new
0 1 test1 2020-01-01 4
1 2 test2 2020-02-10 4
2 3 test3 2020-01-01 1
3 4 test2 2020-03-15 4

关于python - 根据条件用不同的替换字典替换 Pandas 数据框列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64908770/

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