Combine consecutive rows with identical column values

I have something like this. How can I go from this:

    0             d
0   The         DT
1   Skoll       ORGANIZATION
2   Foundation  ORGANIZATION
3   ,           ,
4   based       VBN
5   in          IN
6   Silicon     LOCATION
7   Valley      LOCATION

:

    0                       d
0   The                     DT
1   Skoll Foundation        ORGANIZATION
3   ,                       ,
4   based                   VBN
5   in                      IN
6   Silicon Valley          LOCATION
+4
source share
2 answers

The @rfan answer, of course, works, as an alternative, the approach using pandas groupby is used here .

.groupby()groups data by column "b" - for sort=Falseyou need to keep order. .apply()applies a function to each group of b data, in this case, the union of the string together is separated by spaces.

In [67]: df.groupby('b', sort=False)['a'].apply(' '.join)
Out[67]: 

b
DT                       The
Org         Skoll Foundation
,                          ,
VBN                    based
IN                        in
Location      Silicon Valley
Name: a, dtype: object

EDIT:

( ) - -, , , :

df['key'] = (df['b'] != df['b'].shift(1)).astype(int).cumsum()

, . , :

df = DataFrame({'a': ['The', 'Skoll', 'Foundation', ',', 
                      'based', 'in', 'Silicon', 'Valley', 'A', 'Foundation'], 
                'b': ['DT', 'Org', 'Org', ',', 'VBN', 'IN', 
                      'Location', 'Location', 'Org', 'Org']})

groupby:

In [897]: df.groupby(['key', 'b'])['a'].apply(' '.join)
Out[897]: 
key  b       
1    DT                       The
2    Org         Skoll Foundation
3    ,                          ,
4    VBN                    based
5    IN                        in
6    Location      Silicon Valley
7    Org             A Foundation
Name: a, dtype: object
+7

, groupby @chrisb , groupby , . .


, , , pandas. groupby, , , , .

, , :

df = DataFrame({'a': ['The', 'Skoll', 'Foundation', ',', 
                      'based', 'in', 'Silicon', 'Valley'], 
                'b': ['DT', 'Org', 'Org', ',', 'VBN', 'IN', 
                      'Location', 'Location']})

# Initialize result lists with the first row of df
result1 = [df['a'][0]]  
result2 = [df['b'][0]]

# Use zip() to iterate over the two columns of df simultaneously,
# making sure to skip the first row which is already added
for a, b in zip(df['a'][1:], df['b'][1:]):
    if b == result2[-1]:        # If b matches the last value in result2,
        result1[-1] += " " + a  # add a to the last value of result1
    else:  # Otherwise add a new row with the values
        result1.append(a)
        result2.append(b)

# Create a new dataframe using these result lists
df = DataFrame({'a': result1, 'b': result2})
+2

All Articles