Python 如何将序列合并到序列索引与某个列值匹配的数据帧中?
我有一个数据帧Python 如何将序列合并到序列索引与某个列值匹配的数据帧中?,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,我有一个数据帧df: date cases country 0 2020-12-14 63 AF 1 2020-12-13 71 AF 2 2020-12-12 110 AF 3 2020-12-11 91 AF ... 501 2020-12-14 14 BE 502 2020-12-13 22 BE 503 2020-1
df
:
date cases country
0 2020-12-14 63 AF
1 2020-12-13 71 AF
2 2020-12-12 110 AF
3 2020-12-11 91 AF
...
501 2020-12-14 14 BE
502 2020-12-13 22 BE
503 2020-12-12 19 BE
504 2020-12-11 35 BE
...
我还有一个系列的casesPerDay
:
date
2019-12-31 0
2020-01-01 0
2020-01-02 46
2020-02-03 58
...
我想将casesPerDay
添加到df
中,以便df
中的date
列与casesPerDay
中的date
索引匹配
例如,如果上面只有两个国家,它将如下所示:
date cases country casePerDay # just the sum of cases
0 2020-12-14 63 AF 77 # 63 + 14
1 2020-12-13 71 AF 93 # 71 + 22
2 2020-12-12 110 AF 129 # 110 + 19
3 2020-12-11 91 AF 126 # 91 + 35
...
501 2020-12-14 14 BE 77 # 63 + 14
502 2020-12-13 22 BE 93 # 71 + 22
503 2020-12-12 19 BE 129 # 110 + 19
504 2020-12-11 35 BE 126 # 91 + 35
...
我们能做的就是
out = df.merge(casesPerDay.to_frame('casePerDay').reset_index())
casesPerDay
dataframe如何在显示的输出中发挥作用?我没有看到任何匹配。。。df中的on date列与casesPerDay中的日期索引匹配casesPerDay
中的日期应与df
中的日期匹配。例如,我为这两个国家添加了案例
,只是为了举例。在实际情况中,我希望根据日期属性添加来自casesPerDay
的值。我添加这两个国家的案例只是为了举例:->不太清楚,因为没有匹配,我们无法复制以获得您显示的输出…:尝试df.merge(casesPerDay,left_on='date',right_index=True)
,请同时阅读