gpt4 book ai didi

pandas - python : How to merge two data frames where the values are not unique

转载 作者:行者123 更新时间:2023-12-05 01:31:42 24 4
gpt4 key购买 nike

我有两个数据框,

import pandas as pd
a = pd.DataFrame( { 'port':[1,1,0,1,0], 'cd':[1,2,3,2,1], 'date':["2014-02-26","2014-02-25","2014-02-26","2014-02-26","2014-02-25"] } )
b = pd.DataFrame( { 'port':[0,1,0,1,0], 'fac':[2,1,2,2,3], 'date': ["2014-02-25","2014-02-25","2014-02-26","2014-02-26","2014-02-27"] } )

我需要做的是获取每个日期端口对,例如端口 0 和日期 2014-02-25,查找 b 中的 fac 值,然后将其填充到 a 中的新列中。因此,输出应该类似于

port cd date         fac 
1 1 "2014-02-26" 2
1 2 "2014-02-25" 1
... (so on) ...

我尝试合并日期和端口上的帧,但出现错误,我认为这是由于数据帧大小不同的事实 - 而且我并不认为它会起作用.

最佳答案

如果您希望合并两个数据帧,您应该使用 merge

import pandas as pd
a = pd.DataFrame( { 'port':[1,1,0,1,0], 'cd':[1,2,3,2,1],
'date':["2014-02-26","2014-02-25","2014-02-26","2014-02-26","2014-02-25"]})

b = pd.DataFrame( { 'port':[0,1,0,1,0], 'fac':[2,1,2,2,3],
'date': ["2014-02-25","2014-02-25","2014-02-26","2014-02-26","2014-02-27"]})

df = a.merge(b)
print (df)

输出:

  port  cd  date       fac
0 1 1 2014-02-26 2
1 1 2 2014-02-26 2
2 1 2 2014-02-25 1
3 0 3 2014-02-26 2
4 0 1 2014-02-25 2

关于pandas - python : How to merge two data frames where the values are not unique,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51801946/

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