'pandas groupby ignoring column
Below is my groupby function and dataset before the operation. However, the statement as written produces no change. I want this to be a single row containing sums for each category.
ichiro_df.groupby('playerID')['AB', 'HBP', 'SF'].sum()
playerID AB HBP SF
81816 suzukic01 692 8.0 4.0
83144 suzukic01 647 5.0 5.0
84474 suzukic01 679 6.0 1.0
85829 suzukic01 704 4.0 3.0
87152 suzukic01 679 4.0 6.0
88529 suzukic01 695 5.0 2.0
89915 suzukic01 678 3.0 2.0
Solution 1:[1]
You need to enclose your list by []:
# HERE ---v-------------------v
out = ichiro_df.groupby('playerID')[['AB', 'HBP', 'SF']].sum()
print(out)
# Output
AB HBP SF
playerID
suzukic01 4774 35.0 23.0
Solution 2:[2]
Try:
ichiro_df.agg({'AB':sum,'HBP':sum,'SF':sum})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Corralien |
| Solution 2 | Tyler H |
