Home > Software design >  Looking for a solution to add numeric and float elements stored in list format in one of the columns
Looking for a solution to add numeric and float elements stored in list format in one of the columns

Time:05-19

| Index    | col1           |
| -------- | -------------- |
| 0        | [0,0]          |
| 2        | [7.9, 11.06]   |  
| 3        | [0.9, 4]       |
| 4        | NAN            |

I have data similar to like this.I want to add elements of the list and store it in other column say total using loop such that output looks like this:

| Index    | col1           |Total    |
| -------- | -------------- | --------|        
| 0        | [0,0]          |0        |
| 2        | [7.9, 11.06]   |18.9     |  
| 3        | [0.9, 4]       |4.9      |
| 4        | NAN            |NAN      |

CodePudding user response:

Using na_action parameter in map should work as well:

df['Total'] = df['col1'].map(sum,na_action='ignore')

CodePudding user response:

Use apply with a lambda to sum the lists or return np.NA if the values are not a list:

df['Total'] = df['col1'].apply(lambda x: sum(x) if isinstance(x, list) else pd.NA)

I tried with df.fillna([]), but lists are not a valid parameters of fillna.

Edit: consider using awkward arrays instead of lists: https://awkward-array.readthedocs.io/en/latest/

  • Related