繁体   English   中英

比较两个不同DataFrame中不同长度的两列的值,如果匹配条件则执行数学运算

[英]Compare the values of two columns of different length in two different DataFrames and perform a math operation if matches a condition

我有两个不同长度的不同数据框,但有两列共同。

在此处输入图像描述

在此处输入图像描述

如果条件与相同的 ID 和 Z9BD81329FEBF6EFE22788E0 匹配,我需要执行一个数学运算,假设将第一个 dataframe 的 VALUE 列中的浮点值与第二个 dataframe 的 NUMBER 列中的值相乘

例如:

In 1st dataframe if ID is 103 and Class is A, then the value 2.301308 must be multiplied with the value 0.15 in 2nd dataframe whose ID is 103 and Class is A. Likewise for each ID and Class of two dataframes matches the value in VALUE column应乘以 NUMBER 列中的值。

我试过 df.assign function

df1.assign(VALUE = df1['VALUE']*(df2.NUMBER.loc[(df2.ID == df1.ID) & (df2.Class == df1.Class)]))

得到错误

ValueError:只能比较标签相同的系列对象

出了什么问题或任何其他解决方案?

提前致谢!

使用MultiIndex

df11 = df1.set_index(['ID','Class'])
df11['VALUE'] = df11['VALUE'].mul(df2.set_index(['ID','Class'])['NUMBER'])
df = df11.reset_index()

或者:

df = df1.merge(df2, on=['ID','Class'], how='left')
df['VALUE'] *= df.pop('NUMBER')

暂无
暂无

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

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