Pandas cumsum separated by comma

Viewed 55

I have a dataframe with a column with data as:

my_column     my_column_two
1,2,3           A
5,6,8           A
9,6,8           B
5,5,8           B

if I do:

data = df.astype(str).groupby('my_column_two').agg(','.join).cumsum()
data.iloc[[0]]['my_column'].apply(print)
data.iloc[[1]]['my_column'].apply(print)

I have:

1,2,3,5,6,8
1,2,3,5,6,89,6,8,5,5,8

how can I have 1,2,3,5,6,8,9,6,8,5,5,8 so the cummulative adds a comma when adding the previous row? (Notice 89 should be 8,9)

1 Answers

Were you after?

df['new']=df.groupby('my_column_two')['my_column'].apply(lambda x: x.str.split(',').cumsum())




 my_column    my_column_two             new
0     1,2,3             A           [1, 2, 3]
1     5,6,8             A  [1, 2, 3, 5, 6, 8]
2     9,6,8             B           [9, 6, 8]
3     5,5,8             B  [9, 6, 8, 5, 5, 8]
Related