Convert list to int and sum all elements in pandas dataframe

Viewed 910

Very new to pandas and I'm trying to sum the elements of a list in a single column for a pandas dataframe, except I can't find a way to do so

The dataframe looks something like this:

index codes 
0     [19, 19]
1     [3, 4]
2     [20, 5, 3]
3     NaN
4     [1]
5     NaN
6     [14, 2]

What I'm trying to get is:

index codes       total 
0     [19, 19]    38
1     [3, 4]      7 
2     [20, 5, 3]  28
3     NaN         0 
4     [1]         1
5     NaN         0
6     [14, 2]     16

However the values in codes were obtained by using str.findall('-(\d+)') from a different column, so they are not a list of ints

Any help would be much appreciated, thanks.

3 Answers

I would use str.extractall() instead of str.findall():

# replace orig_column with the correct column name
df['total'] = (df['orig_column'].str.extractall('-(\d+)')
                 .astype(int).sum(level=0)
                 .reindex(df.index, fill_value=0)
              )

If you really want to use your current codes column:

df['total'] = df['codes'].explode().astype(float).sum(level=0)

Output:

   index       codes  total
0      0    [19, 19]     38
1      1      [3, 4]      7
2      2  [20, 5, 3]     28
3      3         NaN      0
4      4         [1]      1
5      5         NaN      0
6      6     [14, 2]     16

Try df['total'] = df['codes'].apply(lambda x:int(np.nansum(x))) if you want int type output.

Try df['total'] = df['codes'].apply(lambda x:np.nansum(x)) otherwise.

df['total'] = (
    df.codes.apply(lambda x: sum([int(e) for e in x]) if type(x) == list else 0)
)
Related