Home > Software engineering >  Pandas cumsum separated by comma
Pandas cumsum separated by comma

Time:01-17

I have a dataframe with a column with data as:

my_column
[1,2,3]
[5,6,8]
[9,6,8]
[5,5,8]

if I do:

data = df.cumsum().apply(print)
data.iloc[[0]]['my_column'].apply(print)
data.iloc[[1]]['my_column'].apply(print)

I have:

1,2,3
1,2,35,6,8

how can I have 1,2,3,5,6,8 so the cummulative adds a comma when adding the previous row?

CodePudding user response:

Were you after?

df.apply(lambda x: (pd.Series([str(y) for y in x]).cumsum()).str.replace(r'\]\[',',',regex=True))

      

     my_column
0                    [1,2,3]
1              [1,2,3,5,6,8]
2        [1,2,3,5,6,8,9,6,8]
3  [1,2,3,5,6,8,9,6,8,5,5,8]

CodePudding user response:

You can just try cumsum

df.col.cumsum()
0                               [1, 2, 3]
1                      [1, 2, 3, 5, 6, 8]
2             [1, 2, 3, 5, 6, 8, 9, 6, 8]
3    [1, 2, 3, 5, 6, 8, 9, 6, 8, 5, 5, 8]
Name: col, dtype: object
  •  Tags:  
  • Related