1

Fairly new to this, not sure how to ask the question in a better way but- here's my data (also I don't understand how to type this out in code...)

Date       Sex      Cases
20200103  Female     1
20200103  Female     1
20200103  Female     2
20200103  Male       0
20200103  Male       1
20200104  Female     2
20200104  Female     1
20200104  Male       2
20200104  Male       1

How do I merge the ones with same date AND also by gender (and add the cases together), so it looks something like this:

Date       Sex      Cases
20200103  Female     3
20200103  Male       1
20200104  Female     3
20200104  Male       3
Moon Chan
  • 13
  • 3

1 Answers1

2
df = df.groupby(['Date', 'Sex'], as_index=False).sum()

Output:

>>> df
       Date     Sex  Cases
0  20200103  Female      4
1  20200103    Male      1
2  20200104  Female      3
3  20200104    Male      3
  • Regarding "I don't understand how to type this out in code...", you can simply put the data in excel, save to a comma separated values file, then import the file to pandas. Open Python and run `import pandas as pd` then `df = pd.read_csv('path-to-your-file')`. Then this answer will be correct. To get it back out, just do `df.to_csv('path-to-output-file')`. – D.J. P. Nov 20 '21 at 18:02
  • @D.J.P. Totally understand I could do it that way too but we're supposed to practice on it on python so yeahh :( – Moon Chan Nov 20 '21 at 18:10