pandas 根据另一个数据框中的匹配列填充新的数据框列 [英] Pandas populate new dataframe column based on matching columns in another dataframe

查看:102
本文介绍了 pandas 根据另一个数据框中的匹配列填充新的数据框列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个df,其中包含我的主要数据,其中有100万个rows.我的主要数据也有30 columns.现在,我想在我的df中添加另一列称为category. categorydf2中的column,其中包含约700个rows和另外两个columns,它们将与df中的两个columns匹配.

I have a df which contains my main data which has one million rows. My main data also has 30 columns. Now I want to add another column to my df called category. The category is a column in df2 which contains around 700 rows and two other columns that will match with two columns in df.

我首先在df2df中设置一个index,它们将在帧之间匹配,但是df2中的某些indexdf中不存在.

I begin with setting an index in df2 and df that will match between the frames, however some of the index in df2 doesn't exist in df.

df2中的其余列称为AUTHOR_NAMECATEGORY.

df中的相关列称为AUTHOR_NAME.

df中的某些AUTHOR_NAMEdf2中不存在,反之亦然.

Some of the AUTHOR_NAME in df doesn't exist in df2 and vice versa.

我想要的指令是:当df中的indexdf2中的index匹配并且df中的titledf2中的title匹配时,将category添加到df,否则在category中添加NaN.

The instruction I want is: when index in df matches with index in df2 and title in df matches with title in df2, add category to df, else add NaN in category.

示例数据:

df2
           AUTHOR_NAME              CATEGORY
Index       
Pub1        author1                 main
Pub2        author1                 main
Pub3        author1                 main
Pub1        author2                 sub
Pub3        author2                 sub
Pub2        author4                 sub


df
            AUTHOR_NAME     ...n amount of other columns        
Index       
Pub1        author1                 
Pub2        author1     
Pub1        author2 
Pub1        author3
Pub2        author4 

expected_result
            AUTHOR_NAME             CATEGORY   ...n amount of other columns
Index
Pub1        author1                 main
Pub2        author1                 main
Pub1        author2                 sub
Pub1        author3                 NaN
Pub2        author4                 sub

如果我使用df2.merge(df,left_index=True,right_index=True,how='left', on=['AUTHOR_NAME']),则我的df会比预期的大三倍.

If I use df2.merge(df,left_index=True,right_index=True,how='left', on=['AUTHOR_NAME']) my df becomes three times bigger than it is supposed to be.

所以我认为合并可能是错误的解决方法.我真正想做的是使用df2作为查找表,然后根据是否满足某些条件,将type值返回到df.

So I thought maybe merging was the wrong way to go about this. What I am really trying to do is use df2 as a lookup table and then return type values to df depending on if certain conditions are met.

def calculate_category(df2, d):
    category_row = df2[(df2["Index"] == d["Index"]) & (df2["AUTHOR_NAME"] == d["AUTHOR_NAME"])]
    return str(category_row['CATEGORY'].iat[0])

df.apply(lambda d: calculate_category(df2, d), axis=1)

但是,这引发了一个错误:

However, this throws me an error:

IndexError: ('index out of bounds', u'occurred at index 7614')

推荐答案

请考虑以下数据框dfdf2

df = pd.DataFrame(dict(
        AUTHOR_NAME=list('AAABBCCCCDEEFGG'),
        title=      list('zyxwvutsrqponml')
    ))

df2 = pd.DataFrame(dict(
        AUTHOR_NAME=list('AABCCEGG'),
        title      =list('zwvtrpml'),
        CATEGORY   =list('11223344')
    ))

选项1
merge

option 1
merge

df.merge(df2, how='left')

选项2
join

option 2
join

cols = ['AUTHOR_NAME', 'title']
df.join(df2.set_index(cols), on=cols)


两个选项均产生收益


both options yield

这篇关于 pandas 根据另一个数据框中的匹配列填充新的数据框列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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