我有一个数据框,我想在其中替换列中的值,但描述替换的字典基于另一列中的值。示例数据框如下所示:
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 但没有成功
使用DataFrame.join
与MultiIndex Series
通过创建DataFrame
cosntructor和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)