简体   繁体   中英

Summing based on IDs across multiple columns in Pandas

I have the following problem:

There are four teams, which have each been assigned an ID number (1 to 4). They play each other just once and earn points. The results from the games is in a Pandas DataFrame as below:

+----------------+----------------+-------------+-------------+
| Home Player ID | Away Player ID | Home Points | Away Points |
+----------------+----------------+-------------+-------------+
|              1 |              2 |           3 |           0 |
|              3 |              4 |           1 |           1 |
|              2 |              3 |           3 |           0 |
|              4 |              1 |           3 |           0 |
|              2 |              4 |           1 |           1 |
|              3 |              1 |           1 |           1 |
+----------------+----------------+-------------+-------------+

The aim is to sum each player's points, based on their ID's, regardless of whether they played home or away.

I have achieved this is in a very scrappy way by creating two new DataFrames firstly for the Home, and then for the Away, renaming column names so they are uniform, and then using pd.concat to combine them into two columns: Player ID and Player Points.

However, this seems a very inefficient way of doing this and I am hoping to find a far more efficient method!

The end result would look like this:

| Player ID | Total Points |
+-----------+--------------+
|         1 |            4 |
|         2 |            4 |
|         3 |            2 |
|         4 |            5 |
+-----------+--------------+

I would really appreciate any help/advice, and if anything is explained badly, please let me know!

Firat create MultiIndex from columns by first whitespace by split , then reshape by stack and last aggregate sum :

df.columns = df.columns.str.split(n=1, expand=True)
df = df.stack(0).groupby('Player ID', as_index=False)['Points'].sum()
print (df)
   Player ID  Points
0          1       4
1          2       4
2          3       2
3          4       5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM