简体   繁体   English

将一个 dataframe 的两列与另一个 dataframe 的一列进行比较

[英]Compare two columns of one dataframe to one column of another dataframe

I have one dataframe as below:我有一个 dataframe 如下:

Id1编号1 Id2 ID2
1 1 4 4
2 2 5 5
3 3

The 2nd dataframe is:第2个dataframe是:

ID ID Comment评论
1 1 Pears
2 2 Grapes葡萄
3 3 Orange橙子
4 4 Banana香蕉
5 5 Apple苹果

How can I get the output like:我怎样才能得到 output 像:

Id1编号1 Id2 ID2 Review审查
1 1 4 4 Banana香蕉
2 2 5 5 Apple苹果
3 3 Orange橙子

So, basically I am trying to do a look up for Id2 (from dataframe 1) and get the comment from 2nd dataframe but if the Id2 (in first dataframe) is null then get the Id1 comment from 2nd dataframe. So, basically I am trying to do a look up for Id2 (from dataframe 1) and get the comment from 2nd dataframe but if the Id2 (in first dataframe) is null then get the Id1 comment from 2nd dataframe.

Use Series.fillna for replace missing values in Id2 by Id1 and then mapping column by Series.map by Series created by another DataFrame :使用Series.fillnaId2中的缺失值替换为Id1 ,然后将列映射为Series.map由另一个DataFrame创建的Series

s = df2.set_index('ID')['Comment']

df1['Comment'] = df1['Id2'].fillna(df1['Id1']).map(s)

If there is multiple ID columns is possible forward filling missing values and selected last column, then mapping:如果有多个ID列可能正向填充缺失值并选择最后一列,则映射:

df1['Comment'] = df1.ffill(axis=1).iloc[:, -1].map(s)

Solution with merge is possible with helper column:使用辅助列可以使用merge解决方案:

df1['ID'] = df1['Id2'].fillna(df1['Id1'])
#another idea
#df1['ID'] = df1.ffill(axis=1).iloc[:, -1]
df = df1.merge(df2, on='ID', how='left')

Or:或者:

df = df1.assign(ID = df1['Id2'].fillna(df1['Id1'])).merge(df2, on='ID', how='left')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将一个 dataframe 中的一列与另一个 dataframe pandas 中的许多列进行比较 - Compare a column in one dataframe with many columns in another dataframe pandas 比较一个数据框中的两列的行(如果存在) 蟒蛇 - Compare the rows of two columns in one dataframe if they exist another dataframe | python 将一个 dataframe 中的一列与不同 dataframe 中的其他两列进行比较? - Compare a column in one dataframe with two other columns in a different dataframe? 如何比较两个数据框中的两列(一个包含另一个) - how to compare of two columns in two dataframe( one contains another) 比较另一列 dataframe 中一列的值 dataframe - Compare values of one column of dataframe in another dataframe 比较一个 dataframe 的两列数据和另一个 dataframe 的两列数据,发现不匹配的数据 - Compare data of two columns of one dataframe with two columns of another dataframe and find mismatch data 比较dataframe的两列,新建一列 - Compare the two columns of the dataframe and create a new one 将多列熊猫数据框与一列进行比较 - compare multiple columns of pandas dataframe with one column 比较一个 dataframe 与另一个 dataframe 中的坐标(3 列乘 3 列) - Compare coordinates in one dataframe with another dataframe (3 columns by 3 columns) 我有两个数据框。 我想将一个数据框的标题与另一数据框的一列的内容进行比较 - I have two dataframes. I wanted to compare header of one dataframe with the content of one column in another dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM