この短いガイドでは、2 つの Pandas DataFrame 間の値を比較する方法を説明します。
ステップ
ステップ1: 2つのデータフレームを作成する
まず、以下の2つのDataFrameを作成してください。比較を行う前に、2つのDataFrameの行数が同じである必要があります。
import pandas as pd
# Create the first DataFrame
data_1 = {
"product_1": ["computer", "monitor", "printer", "desk"],
"price_1": [1200, 800, 200, 350],
}
df1 = pd.DataFrame(data_1)
print(df1)
# Create the second DataFrame
data_2 = {
"product_2": ["computer", "monitor", "printer", "desk"],
"price_2": [900, 800, 300, 350],
}
df2 = pd.DataFrame(data_2)
print(df2)
Python でコードを実行すると、次の 2 つの DataFrame が取得されます。

ステップ2: 2つのPandas DataFrameの値を比較する
NumPyパッケージを使用して2つのDataFrameを比較できます。一般的なテンプレートは次のとおりです。
df1["new comparison column"] = np.where(condition, "value if true", "value if false")
たとえば、作成された 2 つの DataFrame 間の価格 (price_1 と price_2) を比較するには、次のようにします。
df1["prices_match"] = np.where(df1["price_1"] == df2["price_2"], "Yes", "No")
完全なコード:
import pandas as pd
import numpy as np
# Create the first DataFrame
data_1 = {
"product_1": ["computer", "monitor", "printer", "desk"],
"price_1": [1200, 800, 200, 350],
}
df1 = pd.DataFrame(data_1)
# Create the second DataFrame
data_2 = {
"product_2": ["computer", "monitor", "printer", "desk"],
"price_2": [900, 800, 300, 350],
}
df2 = pd.DataFrame(data_2)
# Adding the price_2 column to df1 to get a better view when comparing prices
df1["price_2"] = df2["price_2"]
# The new prices_match column to be created in df1
df1["prices_match"] = np.where(df1["price_1"] == df2["price_2"], "Yes", "No")
print(df1)
コードを実行すると、次の価格比較が表示されます。

では、2 つの価格の実際の差を知りたい場合はどうすればよいでしょうか?
(price_1) – (price_2)
その場合は、コードに次の行を追加します。
df1["price_diff"] = np.where(df1["price_1"] == df2["price_2"], 0, df1["price_1"] - df2["price_2"])
したがって、完全な Python コードは次のようになります。
import pandas as pd
import numpy as np
# Create the first DataFrame
data_1 = {
"product_1": ["computer", "monitor", "printer", "desk"],
"price_1": [1200, 800, 200, 350],
}
df1 = pd.DataFrame(data_1)
# Create the second DataFrame
data_2 = {
"product_2": ["computer", "monitor", "printer", "desk"],
"price_2": [900, 800, 300, 350],
}
df2 = pd.DataFrame(data_2)
# Adding the price_2 column to df1 to get a better view when comparing prices
df1["price_2"] = df2["price_2"]
# The new prices_match comparison column to be created in df1
df1["prices_match"] = np.where(df1["price_1"] == df2["price_2"], "Yes", "No")
# The new price_diff comparison column to be created in df1
df1["price_diff"] = np.where(df1["price_1"] == df2["price_2"], 0, df1["price_1"] - df2["price_2"])
print(df1)
コードを実行すると、実際の価格の差がわかります。
