Home > OS >  the scoring average of every name in a new column
the scoring average of every name in a new column

Time:09-02

data = {'Name' : ["ana","ini","unu"],'ID' : ["1027","1028","1029"],'Score1' : [3,5,2], 'Score2' : [5,5,4],'Score3' : [1,2,5]}

how can i know the scoring average?

data["Average"] = data.mean(axis=1) i tried to use it but didn't work

CodePudding user response:

It tries to take the average over the entire row, including Name and ID.

df = pd.DataFrame(data)
df["Average"] = df[['Score1', 'Score2', 'Score3']].mean(axis=1)

Output:

>>> df
  Name    ID  Score1  Score2  Score3   Average
0  ana  1027       3       5       1  3.000000
1  ini  1028       5       5       2  4.000000
2  unu  1029       2       4       5  3.666667

CodePudding user response:

You need to extract the "Score" keys first and then pass it to np.mean -

np.mean([v for k, v in data.items() if k.startswith('Score')], axis=0)

Output

array([3.        , 4.        , 3.66666667])

CodePudding user response:

Let's try filter to get descired columns

df = pd.DataFrame(data)
df["Average"] = df.filter(like='Score').mean(axis=1)
  • Related