gpt4 book ai didi

python - 通过比较值而不是列名称来合并两个数据框

转载 作者:行者123 更新时间:2023-12-02 02:27:43 25 4
gpt4 key购买 nike

DataFrame 1 - 按日期列出的水果价格(索引是日期)

fruits_price = {'Apple': [9,5,14],
'Orange': [10,12,10],
'Kiwi': [5,4,20],
'Watermelon': [4.4,5.4,6.4]}
df1 = pd.DataFrame(fruits_price,
columns = ['Apple','Orange','Kiwi','Watermelon'],
index=['2020-01-01','2020-01-02','2020-01-10'])

date Apple Oranges Kiwi Watermelon ... Fruit_100
2020-01-01 9 10 5 4.4
2002-01-02 5 12 4 5.4
...
2002-12-10 14 10 20 6.4

数据框 2(排名靠前的水果)(索引是日期)

top_fruits = {'Fruit_1': ['Apple','Apple','Apple'],
'Fruit_2': ['Kiwi','Orange','Kiwi'],
'Fruit_3': ['Orange','Watermelon','Watermelon'],
'Fruit_4': ['Watermelon','Kiwi','Orange']}

df2 = pd.DataFrame(top_fruits,
columns = ['Fruit_1','Fruit_2','Fruit_3','Fruit_4'],
index=['2020-01-01','2020-01-02','2020-01-10'])

date Fruit_1 Fruit_2 Fruit_3 Fruit_4 ... Fruit_100
2020-01-01 Apple Kiwi Oranges Watermelon Pineapple
2002-01-02 Apple Oranges Watermelon Kiwi Pineapple
...
2002-12-10 Apple Kiwi Watermelon Oranges Pineapple

我想要 DataFrame 3(给定日期顶级水果的价格)它实际上告诉我给定日期顶级水果的价格

    date        Price_1    Price_2   Price_3     Price_4 ..... Price_100 
2020-01-01 9 5 10 4.4
2002-01-02 5 12 5.4 4
...
2002-12-10 14 20 6.4 10

花了将近 1 个晚上的时间,尝试迭代 Dataframe 2,然后在 DataFrame 1 上进行内循环,并向 DataFrame 3 添加值。我通过 iterrow 、iteritems 尝试了几乎 6-7 种不同的方法,然后通过 iloc 直接将输出存储到df3。这些都不起作用。

只是想知道有没有更简单的方法来做到这一点。稍后我会将其乘以同一数据帧格式中的水果销量。

最佳答案

只需使用带有 axis=1 的 apply 函数,它的作用是逐行,每行是一个系列,其名称是日期,将值替换为 df1 中相应行的值。

df2.apply(lambda x: x.replace(df1.to_dict('index')[x.name]), axis=1)

关于python - 通过比较值而不是列名称来合并两个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65402127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com