[英]If values from two columns in two different data frames match then copy values from another column in df2 to column in df1
I have two data frames, and I want to copy values from the column "Result2" in df2 to column "Result1" in df1 and to add the column "Description" from df2 to df1 for values that are in the same row as values from the column "Result2" (that are already copied), if the values from columns "ID" in both data frames match. 我有两个数据帧,我想将df2中的“ Result2”列中的值复制到df1中的“ Result1”列中,并将与df2中的值相同的行中的“描述”列从df2添加至df1中如果两个数据框中的“ ID”列中的值都匹配,则将列“ Result2”(已复制)。
Here are the data frames: 以下是数据帧:
df1 df1
ID Result1
Position1 NaN
MRS1 OK
MRS2 Maybe
MRS3 NOK
Position2 NaN
MRS4 OK
MRS5 OK
Position3 NaN
MRS6 OK
Position4 NaN
MRS7 NOK
MRS8 OK
MRS9 NOK
MRS10 Excellent
df2 df2
ID Result2 Description
text NaN NaN
NaN NaN text
text NaN NaN
MRS1 OK New
MRS2 OK Old
NaN NaN NaN
NaN NaN text
MRS3 OK New
MRS4 OK New
MRS5 OK NaN
MRS6 NOK Very old
NaN text NaN
text text NaN
NaN NaN NaN
MRS7 Excellent Very old
MRS8 Excellent Old
text text text
MRS9 Excellent New
NaN NaN NaN
MRS10 NOK New
I want to get: 我想得到:
ID Result1 Result2
Position1 NaN NaN
MRS1 OK New
MRS2 OK Old
MRS3 OK New
Position2 NaN NaN
MRS4 OK New
MRS5 OK NaN
Position3 NaN NaN
MRS6 NOK Very old
Position4 NaN NaN
MRS7 Excellent Very old
MRS8 Excellent Old
MRS9 Excellent New
MRS10 NOK New
and I put NaN on the places where should be an empty cell. 我将NaN放在应该是一个空单元格的地方。 How to do this in pandas?
如何在熊猫中做到这一点? I tried with the merge, but I have the problem because it is required the same length of comparing columns.
我尝试了合并,但是我遇到了问题,因为它要求比较列的长度相同。 I just want to compare values from the "ID" columns from both data frames, and those columns do not have the same length.
我只想比较两个数据帧的“ ID”列中的值,并且这些列的长度不同。
Use merge
with only column ID
with left join and rename
columns: 使用仅
merge
具有左联接的列ID
rename
列的merge
:
df = (df1[['ID']].merge(df2, on='ID', how='left')
.rename(columns={'Result2':'Result1','Description':'Result2'}))
print (df)
ID Result1 Result2
0 Position1 NaN NaN
1 MRS1 OK New
2 MRS2 OK Old
3 MRS3 OK New
4 Position2 NaN NaN
5 MRS4 OK New
6 MRS5 OK NaN
7 Position3 NaN NaN
8 MRS6 NOK Very old
9 Position4 NaN NaN
10 MRS7 Excellent Very old
11 MRS8 Excellent Old
12 MRS9 Excellent New
13 MRS10 NOK New
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.