Home > Back-end >  I want to iterate over columns in python and get the column names & values at the same time
I want to iterate over columns in python and get the column names & values at the same time

Time:10-15

I have a data frame that is about the class grades. Each column is the grade of each homework. The column names are: HW1, HW2, HW3... HW8. I need to get the average value of each column, which means the average mean of each homework of the whole class. Also, I need to print the result.

The codes that I use are the following:

for column in dats:
    print(dats[column].mean())

I want to print the result like this:

HW1:50
HW2:40
...
HW8:90

I am struggling with the iteration of the column names. Could you please help me with that?

Thank you!!

CodePudding user response:

Try this

import numpy as np
import pandas as ps

df = pd.DataFrame(np.random.randint(0,100,size=(15, 4)), columns=['HW1', 'HW2', 'HW3', 'HW4'])
[print(f'{i}: {k}') for k, i in zip(df.mean(), df.mean().index)];

CodePudding user response:

The mean function takes a list as a parameter, try using

for column in dats:
    print(mean(dats[column]))
  • Related