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

标签 python pandas dataframe

我有两个 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

关于python - 使用多个键在 Pandas 中映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42645886/

相关文章:

python - 使用字典作为字典中的键

python - IP 地址 - 从 30 秒列表中找到下一个可用的 30 网络?

python - 编写基于 XML 的大型日志文件时性能不佳

python - 在 Pandas 数据框中将单个列向前移动几个日期

python - 是否可以使用部分列名来 reshape pandas DataFrame?

python - 使用列表加一些字符串从数据框中选择列

python - 一个 python 代码,用于将数字从任何基数转换为 10 的基数,给出错误。这段代码有什么问题?

python - 将带有项目列表的字典转换为 Pandas 数据框

python - Pandas:将所有列从字符串转换为数字,除了两个?

Python 计算特定列的相同值