简体   繁体   English

Pandas dataframe 条件列更新基于另一个 dataframe

[英]Pandas dataframe conditional column update based on another dataframe

I have two dataframes with two columns each - 'MeetingId' and 'TAB'.我有两个数据框,每个数据框有两列 - 'MeetingId' 和 'TAB'。 The first dataframe is the full table, but it has some errors in the 'TAB' column.第一个 dataframe 是完整的表格,但它在“TAB”列中有一些错误。 The second dataframe has the solutions to the errors.第二个dataframe有错误的解决方法。 I would like to replace the 'TAB' column of the first dataframe with the 'TAB' column of the second datafrmae if the 'MeetingId's match up.如果“MeetingId”匹配,我想用第二个 datafrmae 的“TAB”列替换第一个 dataframe 的“TAB”列。

Example of table:表格示例:

MeetingId    TAB
123          TRUE
124          FALSE

Code:代码:

df1 = meetingdf1
df1.set_index("MeetingId")
df2 = meetingdf2
df2.set_index("MeetingId")
df1.update(df2)
print(df1)
df['TAB'] = df.apply(lambda x: df2[df2['MeetingId'] == x['MeetingId']]['TAB'].values[0], axis=1)

OR要么

df.loc[df['MeetingId'].isin(df2['MeetingId']), 'TAB'] = df2['TAB']

Example:例子:

> df

   MeetingId    TAB
0        123   True
1        124  False

> df2

   MeetingId    TAB
0        123  False
1        124   True
2        125  False

Output after running code above:运行上面的代码后 Output:

> df

   MeetingId    TAB
0        123  False
1        124   True

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM