第一个数据帧(df1)类似于:
<表类>
日期
名称
tbody><<tr>2022-01-01 2022-01-02 2022-01-03 2022-01-01 B 2022-01-02 B 2022-01-03 B 表类>
使用pd.melt()重塑df2(从宽到长)。为了简化解决方案,我对df2中的列名做了一个小改动。
df1 = pd.DataFrame(
{
"Date": ["2022-01-01", "2022-01-02", "2022-01-03", "2022-01-01", "2022-01-02", "2022-01-03"],
"Name": ["A", "A", "A", "B", "B", "B"]
}
)
df2 = pd.DataFrame(
{
"Date": ["2021-12-31", "2022-01-01", "2022-01-02", "2022-01-03"],
"A": [False, False, False, True],
"B": [True, False, True, False],
"C": [True, True, False, True],
}
)
df2_long = df2.melt(
id_vars=['Date'],
value_vars=['A', 'B', 'C'],
var_name="Name",
value_name="Result"
)
result = df1.merge(df2_long, on=['Date', 'Name'])