Pandas: Access groubpy dataframe with multiple columns

Viewed 31
#group by team and position and find mean assists
new = df.groupby(['team', 'position']).agg({'assists': ['mean']}).reset_index()

#rename columns 
new.columns = ['team', 'pos', 'mean_assists']

#view DataFrame
print(new)

    team    pos mean_assists
0   A   G   5.0
1   B   F   6.0
2   B   G   7.5
3   M   C   7.5
4   M   F   7.0

Hi, I'm having issues with accessing the first two columns.

I thought

for i in range(5):
   print(new["team"][i])

would be possible

1 Answers

I don't understand what the problem is. Below, you can copy my code (which should work). Hopefully you can find your problem from there.

new = pd.DataFrame([[0, 1], [2, 3], [4, 5]], columns=['a', 'b'])
new.columns = ['c', 'd']

Now you can either do new[['c', 'd']] or with a for-loop such as you did:

for i in range(3):
   print(new.loc[i, ['c', 'd']])
Related