Skip to main content
 首页 » 编程设计

python之使用多个键在 Pandas 中映射

2025年02月15日8wuhuacong

我有两个 Pandas Datafrmae 作为

df:                         df2: 
   col1 col2  val              col1 col2   s 
0     1    a  1.2           0     1    a  0.90    
1     2    b  3.2           1     3    b  0.70 
2     2    a  4.2           2     1    b  0.02 
3     1    b -1.2           3     2    a  0.10 

我想使用 df2['s'] 并在 df['val'] 中乘以 ['col1', 'col2'] 匹配。如果一行不匹配,我不需要做乘法

我创建一个映射器

mapper = df2.set_index(['col1','col2'])['s'] 

我在哪里

mapper 
col1  col2 
1     a       0.90 
3     b       0.70 
1     b       0.02 
2     a       0.10 
Name: s, dtype: float64 

我想将它与 df[['col1','col2']]

匹配
df[['col1','col2']] 
 
   col1 col2 
0     1    a 
1     2    b 
2     2    a 
3     1    b 

但是当我做映射的时候

mapped_value = df[['col1','col2']].map(mapper) 

出现以下错误

AttributeError: 'DataFrame' object has no attribute 'map'

有什么提示吗?

请您参考如下方法:

我想你需要mul :

df = df2.set_index(['col1','col2'])['s'].mul(df.set_index(['col1','col2'])['val']) 
print (df) 
 
col1  col2 
1     a       1.080 
      b      -0.024 
2     a       0.420 
      b         NaN 
3     b         NaN 
dtype: float64 

如果需要替换NaN:

df = df2.set_index(['col1','col2'])['s'] 
        .mul(df.set_index(['col1','col2'])['val'], fill_value=1) 
print (df) 
col1  col2 
1     a       1.080 
      b      -0.024 
2     a       0.420 
      b       3.200 
3     b       0.700 
dtype: float64