Skip to content
Advertisement

How do you cumulatively aggregate string in pandas?

I have a column that contains strings.

                 Rm
0                Rwws,xxALd
1                Ras,yySAw
2                Bdbbd1dd

I want to cumulatively aggregate the string through the y-axis.

This is the desired output.

                 Rm
0                Rwws,xxALd
1                Rwws,xxALdRas,yySAw
2                Rwws,xxALdRas,yySAwBdbbd1dd

Something like this can be achieved using the expanding or cumsum() function, however it appears to work for numeric attributes only.

Advertisement

Answer

    col1
0   I
1   am
2   cool

a quick idea

df.apply(lambda x: x+',').cumsum().str.strip(',')

output:

0            I
1         I,am
2    I,am,cool

or just:

df.cumsum()

output:

0          I
1        Iam
2    Iamcool
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement