映射到2列 pandas [英] Map on 2 columns pandas

查看:59
本文介绍了映射到2列 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据框:

I have a dataframe that looks like:

        Col1           Col2
0        A              PY
1        B              PA
2        C              PB
3        B              PB

和本系列:

                            Value
   Col1       Col2     
    A          PY             20
    B          PB             30

如果该系列具有一个索引(仅适用于Col1),则我想进行映射:

I would like to do a mapping, if the series has one index(ex Col1 only) its pretty straightforward with:

  df['Value'] = df['Col1'].map(s)

如何基于2个索引/列进行映射?

How can I do mapping based on 2 indexes/columns ?

谢谢!

推荐答案

您可以将它们合并到公共列(具有相同名称的列)中:

you can merge them on the common columns (columns with the same names):

In [28]: d1
Out[28]:
  Col1 Col2
0    A   PY
1    B   PA
2    C   PB
3    B   PB

In [29]: d2
Out[29]:
           Value
Col1 Col2
A    PY       20
B    PB       30

In [30]: d1.merge(d2.reset_index())
Out[30]:
  Col1 Col2  Value
0    A   PY     20
1    B   PB     30

或使用左外部联接:

In [33]: d1.merge(d2.reset_index(), how='left')
Out[33]:
  Col1 Col2  Value
0    A   PY   20.0
1    B   PA    NaN
2    C   PB    NaN
3    B   PB   30.0

相同的解决方案也适用于d2系列:

same solution will work also for d2 as Series:

In [31]: s
Out[31]:
Col1  Col2
A     PY      20
B     PB      30
Name: Value, dtype: int64

In [32]: d1.merge(s.reset_index())
Out[32]:
  Col1 Col2  Value
0    A   PY     20
1    B   PB     30

这篇关于映射到2列 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆