根据条件用不同的替换字典替换熊猫数据框列中的值

Fre*_*son 6 python pandas

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

   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
Run Code Online (Sandbox Code Playgroud)

我有一本看起来像这样的字典:

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}}
Run Code Online (Sandbox Code Playgroud)

我希望映射逻辑根据日期而不同。

在这个例子中,预期的输出是:

   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
Run Code Online (Sandbox Code Playgroud)

我有一个庞大的数据帧(100M+ 行),所以我真的想尽可能避免任何循环解决方案。

我试图想办法使用 map 或 replace 但没有成功

jez*_*ael 7

使用DataFrame.joinMultiIndex Series通过创建DataFramecosntructor和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
Run Code Online (Sandbox Code Playgroud)

  • 事实上,使用“df = pd.concat([df for _ in range(100000)])”扩展数据帧会导致 47.6 ms ± 1.56 ms,而 @oskros 解决方案会导致每个循环 3.01 s ± 102 ms。很棒的解决方案! (2认同)