PANDAS:如何根据不同的单元格将 Pandas 中的值从数据帧复制到另一个数据帧

时间:2021-07-13 01:38:14

标签: python pandas dataframe

我有 df1

<头>
发货日期 价格
07/15/2014 5
08/19/2015 9
09/20/2016 7

我也有 df2

<头>
发货日期
08/19/2015
07/15/2014
09/20/2016
07/15/2014

我需要 df2 的最终输出

<头>
发货日期 价格
08/19/2015 9
07/15/2014 5
09/20/2016 7
07/15/2014 5

我还为 df2 添加了“价格”列。我需要帮助将“价格”列的每个单元格中的值设置为与 df1 中的日期相对应的价格

2 个答案:

答案 0 :(得分:1)

您可以通过多种方式做到这一点。

合并“Ship_Date”上的 2 个数据帧

new_df = df2.merge(df1, on="Ship_Date", how="left")

print(new_df)
    Ship_Date  Price
0  08/19/2015      9
1  07/15/2014      5
2  07/15/2014      5
3  09/20/2016      7

使用 map 函数创建新列:

date_mappings = df1.set_index("Ship_Date")["Price"]
df2["Price"] = df2["Ship_Date"].map(date_mappings)

print(df2)
    Ship_Date  Price
0  08/19/2015      9
1  07/15/2014      5
2  09/20/2016      7
3  07/15/2014      5

暂时将 df1.index 设置为“Ship_Date”,然后重新索引 df1 使其与 df2 的形状相同:

new_df = df1.set_index("Ship_Date").reindex(df2["Ship_Date"]).reset_index()

print(new_df)
    Ship_Date  Price
0  08/19/2015      9
1  07/15/2014      5
2  09/20/2016      7
3  07/15/2014      5

答案 1 :(得分:0)

您可以对熊猫系列使用ma​​p函数:

将 df2['Ship_Date'] 映射到 df1['Price'] 的值,并将映射的系列存储在 df2 的“价格”列中。 映射参数必须是索引为“Ship_Date”的pandas系列。可以通过将df1索引设置为“Ship_Date”并选择“价格'列。

df2['Price'] = df2['Ship_Date'].map(df1.set_index('Ship_Date')['Price'])