I have a dataframe column with numerical values separated by commas(,). I am trying to find the sum of the values in each cell of that column and create a new column.
Input: df:
id Scores
1 10,12
2 11
3 1,2,3
Output required:
id Scores Sum
1 10,12 22
2 11 11
3 1,2,3 6
Code: I have tried writing a custom function, so that I can make use of apply function in python
def sum_of_number(listx):
a=[]
n=0
if len(listx)==1:
a=listx
n=a
else:
a=str(listx).split(',')
for i in range(0,len(a)):
n=n+int(a[i])
return n
df['Sum']=df.Scores.apply(sum_of_number)
But I am not able to get the intended result.
Edit: Thanks to DeepSpace for providing the solution
df['Sum'] = df['Scores'].apply(lambda x: sum(map(float, x.split(','))))
Can the same be applied to get median
id Scores Median
1 10,12 11
2 11 11
3 1,2,3 2