简体   繁体   English

根据条件从另一个数据帧的值替换一个数据帧的值

[英]substitue values of one dataframe from values of another dataframe based on condition

I have a df which looks like我有一个 df 看起来像

floor id p1 p2 p3
L1     1  5  6  7
L1     2  5  8  3
L2     1  4  2  1
L2     2  4  5  4

and df2和 df2

floor id p1 p2 p4
L1     1  6  6  5
L1     2  9  8  5 
L2     1  5  5  5
L2     2  4  5  5

How do I replace the values of p1 and p2 in my df for particular floor and id with the values the respective values from df2?如何将特定楼层和 id 的 df 中 p1 和 p2 的值替换为 df2 中相应值的值?

We can also use DataFrame.merge我们也可以使用DataFrame.merge

df1 = (df1[df1.columns.difference(['p1','p2'])].merge(df2,
                                                      on =['floor','id'],
                                                      how ='left')
                                               .fillna(df1)[df1.columns])
print(df1)
  floor  id  p1  p2  p3
0    L1   1   6   6   7
1    L1   2   9   8   3
2    L2   1   5   5   1
3    L2   2   4   5   4

Merge can be used for this particular problem: Merge 可用于此特定问题:

# left join
df = (df.merge(df2, left_on=['floor', 'id'], how='left', right_on=['floor', 'id'])
# fill missing values with corresponding original df values
df['p1_y'] = df['p1_y'].fillna(df['p1_x']).astype(int)
df['p2_y'] = df['p2_y'].fillna(df['p2_x']).astype(int)

# drop unnecessary columns
df.drop(['p1_x', 'p2_x', 'p4'], axis=1, inplace=True)
df.rename(columns={'p1_y': 'p1', 'p2_y': 'p2'}, inplace=True)

暂无
暂无

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

相关问题 Pandas:根据条件将值从一个 dataframe 合并到另一个 - Pandas: Merge values from one dataframe to another based on condition 根据条件将一个 dataframe 列的值分配给另一个 dataframe 列 - assign values of one dataframe column to another dataframe column based on condition 根据条件从另一个数据帧的值向数据帧添加新列 - Adding a new column to a dataframe from the values of another dataframe based on a condition 根据另一个 dataframe 和条件将值输入 dataframe - Imputing values into a dataframe based on another dataframe and a condition (运行的干净代码)根据来自另一个 dataframe 的日期间隔和字符串条件获取一个 dataframe 中的值的平均值 - (Clean code that runs) Getting the mean of values in one dataframe based on date interval and string condition from another dataframe 根据条件从另一个 dataframe 值替换列的值 - Python - Replace values of a column from another dataframe values based on a condition - Python 根据条件用一个python pandas dataframe列的值替换为另一个python pandas dataframe列的值 - Substitute the values of one python pandas dataframe column by values from another based on a condition 使用条件映射来自另一个数据帧的数据帧值 - Mapping dataframe values from another dataframe with condition 根据对另一个 dataframe 的条件检查,过滤来自一个 dataframe 的值 - Filter values from one dataframe based on conditional checks on another dataframe 根据两者的索引将一个数据帧中的值填充到另一个数据帧中 - Fill values from one dataframe into another dataframe based on index of the two
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM