[英]Compare two dataframes to get comparison value in in another dataframe
I have two dataframes, df1
and df2
, each in the following format with the same index and different values: 我有两个数据
df1
和df2
,每个数据df2
都采用以下格式,具有相同的索引和不同的值:
Value
Date
01-01 60
01-02 70
01-03 -80
I need to compare the two dataframes where values of df1 < df2
and get only those values for which the comparison stands true with their respective indices in a third dataframe df_new
. 我需要比较
df1 < df2
值的两个数据帧,并仅获取比较正确的值以及它们在第三个数据帧df_new
的相应索引。
I would suggest that you merge your two data frames based on the index so that you can compare the values between each columns. 我建议您根据索引合并两个数据框,以便可以比较各列之间的值。
Try this: 尝试这个:
import pandas
df1 = pandas.DataFrame(
data=[60, 70, -80],
index=['01-01', '01-02', '01-03'],
columns=['Value'])
df2 = pandas.DataFrame(
data=[59, 69, -79],
index=['01-01', '01-02', '01-03'],
columns=['Value'])
df3 = df1.merge(df2, how='outer', left_index=True, right_index=True, suffixes=('_1', '_2'))
df3['Delta'] = df3['Value_2'] - df3['Value_1']
It will return you the following dataframe: 它将返回以下数据框:
Value_1 Value_2 Delta
01-01 60 59 -1
01-02 70 69 -1
01-03 -80 -79 1
Here is the link to the merge method: pandas.DataFrame.merge 这是合并方法的链接: pandas.DataFrame.merge
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.