如何比较两个Pandas Dataframes中的值
让我们来讨论一下如何在Pandas数据框中比较数值。下面是比较两个pandas数据框架中的数值的步骤。
第1步 创建数据框架:两个数据集的数据框架可以用以下代码创建。
import pandas as pd
# elements of first dataset
first_Set = {'Prod_1': ['Laptop', 'Mobile Phone',
'Desktop', 'LED'],
'Price_1': [25000, 8000, 20000, 35000]
}
# creation of Dataframe 1
df1 = pd.DataFrame(first_Set, columns=['Prod_1', 'Price_1'])
print(df1)
# elements of second dataset
second_Set = {'Prod_2': ['Laptop', 'Mobile Phone',
'Desktop', 'LED'],
'Price_2': [25000, 10000, 15000, 30000]
}
# creation of Dataframe 2
df2 = pd.DataFrame(second_Set, columns=['Prod_2', 'Price_2'])
print(df2)
输出:

第2步 值的比较:你需要导入numpy来成功执行这一步。下面是执行比较的一般模板。
df1[‘比较结果的新列’] = np.where(condition, ‘value if true’, ‘value if false’)
示例:执行此代码后,在df1下将形成名称为Price_Matching的新列。列的结果将根据以下条件显示。
- 如果Price_1等于Price_2,则赋值为True
- 否则,赋值为False。
import numpy as np
# add the Price2 column from
# df2 to df1
df1['Price_2'] = df2['Price_2']
# create new column in df1 to
# check if prices match
df1['Price_Matching'] = np.where(df1['Price_1'] == df2['Price_2'],
'True', 'False')
df1
输出:

极客教程