Python Pandas匹配两个索引和列的值 [英] Python Pandas match two indexes and value of column

查看:1478
本文介绍了Python Pandas匹配两个索引和列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在两个不同df中的行索引之间进行匹配,如果索引相同,我想转到第二个df,遍历它的列,并且如果列的值为'V',转到第一个df,然后将df的名称添加到列的值中.

I want to match between indexes of rows in two different dfs, and if the indexes are the same, I want to go to the second df, iterate through it's columns, and if the value of a column is 'V', go to the first df, and add the name of the df to the value of a column.

例如:

主DF:

names    col1   col2   col3   total
 bbb      V      V      X      2
 ccc      V      X      X      1

DF2:

names    col1   col2   col3   total
 bbb      V      V      X      2
 zzz      X      X      V      1

因此在主DF 之后将是:

names    col1   col2   col3   total   totla_col1   total_col2   total_col3
 bbb      V      V      X      2          DF2          DF2         NULL
 ccc      V      X      X      1          NULL         NULL        NULL

推荐答案

您可以先通过names列创建索引/pandas.DataFrame.set_index.html"rel =" nofollow noreferrer> set_index

You can first create index from names column by set_index, replace values by dict and add_prefix.

然后 join 它还原为原始图片:

Then join it to original:

cols = ['col1','col2','col3']
DF2 = DF2.set_index('names')[cols].replace({'V':'DF2', 'X':np.nan}).add_prefix('total_')
print (DF2) 
      total_col1 total_col2 total_col3
names                                 
bbb          DF2        DF2        NaN
zzz          NaN        NaN        DF2

df = df.join(DF2, on='names')
print (df)
  names col1 col2 col3  total total_col1 total_col2 total_col3
0   bbb    V    V    X      2        DF2        DF2        NaN
1   ccc    V    X    X      1        NaN        NaN        NaN

这篇关于Python Pandas匹配两个索引和列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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