Home > database >  if the first column is the same and then append the row value together in pandas
if the first column is the same and then append the row value together in pandas

Time:07-06

The following are the details

Here is the data frame

Name| Filename| delimetier| good delimeter
A     123       48         a
B     123       48         b
C     123       49         c
A     123       48         d
A     123       48         c
B     123       48         d

What I want is

Name| Filename| delimetier| good delimeter
A     123       48         a, c, d
B     123       48         b, d
C     123       49         c

CodePudding user response:

You can use a groupby.apply to achieve this result.

Using this data:

>>> df
  Name  Filename  delimeter good delimeter
0    A       123         48              a
1    B       123         48              b
2    C       123         49              c
3    A       123         48              d
4    A       123         48              c
5    B       123         48              d

Solution

out = (
    df.groupby(['Name', 'Filename', 'delimeter'], as_index=False)
    ['good delimeter'].apply(', '.join)
)

print(out)
  Name  Filename  delimeter good delimeter
0    A       123         48        a, d, c
1    B       123         48           b, d
2    C       123         49              c
  • Related