-1

I have a 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-12-12     19       BE
504  2020-12-11     35       BE
...

I also have a Series casesPerDay:

date
2019-12-31    0
2020-01-01    0
2020-01-02   46
2020-02-03   58
...

I want to add casesPerDay to df so that the date column in df matches the date index in casesPerDay.

For example if there were only the 2 countries above it would look like this:

           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
...
anInputName
  • 439
  • 2
  • 12
  • How does `casesPerDay` dataframe play a part in your shown output? I dont see any matches... on *date column in df matches the date index in casesPerDay* – anky Mar 17 '21 at 19:00
  • The date in `casesPerDay` should match the date in `df`. For the example, I added the `cases` for the two countries just for examples sake. In the real thing I am looking to just append the values from `casesPerDay` based on the date attribute. – anInputName Mar 17 '21 at 19:03
  • 1
    *I added the cases for the two countries just for examples sake* :- > not quite clear since none match and we can't reproduce to get the output you show... : try `df.merge(casesPerDay,left_on='date',right_index=True)`, please also read [how to create a readable and reproducible pandas example](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – anky Mar 17 '21 at 19:09

1 Answers1

2

What we can do is

out = df.merge(casesPerDay.to_frame('casePerDay').reset_index())
BENY
  • 317,841
  • 20
  • 164
  • 234