Splitting a Pandas Column and Summing the Values

Viewed 129

I have a pandas data frame that looks like this :

Time       Value
10:00       1|2
11:00       10|20|30
12:00       20|32
13:00       3|4|6|8|9

What I want is to have another Column "Results" which will have the sum of integer values on the "Value" column. The result will look like this:

Time       Value         Results
10:00       1|2             3
11:00       10|20|30       60
12:00       20|32          52
13:00       3|4|6|8|9      30

Whats is the easiest way to do this?

1 Answers

Try via pd.eval():

df['Results']=pd.eval(df['Value'].str.replace('|','+',regex=True))
#OR
df['Results']=df['Value'].str.replace('|','+',regex=True).map(pd.eval)

OR

other way without using pd.eval() as suggested by @Jon Clements:

df['Results'] =[sum(int(n) for n in val.split('|')) for val in df['Value']]
Related