Pandas - Data frame - Changing values ​​in a data frame

I am new to Pandas and have a command frame data frame in two separate columns. This is what I have.

Game_ID Teams   Score

1    Team A  95
1    Team B  85
2    Team C  90
2    Team D  72

Here I would like to get there, and then perfect.

1   Team A  95 Team B  94
2   Team C  90 Team B  72 
+4
source share
2 answers

Knowing that games always include exactly 2 teams, we can manipulate the basic numpy array.

pd.DataFrame(df.values[:, 1:].reshape(-1, 4),
             pd.Index(df.values[::2, 0], name='Game_ID'),
             ['Team', 'Score'] * 2)

enter image description here

0
source

You can try something as follows: Create row_idinside each group with Game_ID, and then format row_id, which converts your data to a wide format:

import pandas as pd
df['row_id'] = df.groupby('Game_ID').Game_ID.transform(lambda g: pd.Series(range(g.size)))
df.set_index(['row_id', 'Game_ID']).unstack(level=0).sortlevel(level = 1, axis = 1)

enter image description here

Update:

If it's preferable to drop row_id, you can remove the level from the columns:

df1 = df.set_index(['row_id', 'Game_ID']).unstack(level=0).sortlevel(level = 1, axis = 1)   
df1.columns = df1.columns.droplevel(level = 1)
df1

enter image description here

+4

Source: https://habr.com/ru/post/1657941/


All Articles