I have a list number data frame and I want to calculate the average using Python language enter image description here
-
Does this answer your question? Pandas mean of list within dataframebluevulture– bluevulture2021-12-21 12:20:34 +00:00Commented Dec 21, 2021 at 12:20
-
You want to calculate the average within each semester, I suppose?Niqua– Niqua2021-12-21 12:24:44 +00:00Commented Dec 21, 2021 at 12:24
-
Please provide enough code so others can better understand or reproduce the problem.Community– Community Bot2021-12-29 23:20:44 +00:00Commented Dec 29, 2021 at 23:20
Add a comment
|
1 Answer
You can use .apply here with a lambda function.
df["Course Final Score"] = df["Course Final Score"].apply(lambda x: sum(x)/len(x))
Essentially your applying the function sum(x)/len(x) to every x in your column "Course Final Score", i.e replacing the list with the sum of that list divided by the length of that list which will give you the mean.
EDIT
If your list contains a string of a list, you can use json to decode it as follows:
import json
df["Score"].apply(lambda x: sum(json.loads(x))/len(json.loads(x)))
7 Comments
hana
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Sam
Does your list of Scores contain strings at any point?
Sam
I've edited a solution for if your scores are string values.
hana
ValueError: could not convert string to float: '['
hana
ValueError: could not convert string to float: '['
|