使用相同的列值组合连续行

use*_*418 6 python pandas

我有一些看起来像这样的东西.我该怎么做:

    0             d
0   The         DT
1   Skoll       ORGANIZATION
2   Foundation  ORGANIZATION
3   ,           ,
4   based       VBN
5   in          IN
6   Silicon     LOCATION
7   Valley      LOCATION
Run Code Online (Sandbox Code Playgroud)

对此:

    0                       d
0   The                     DT
1   Skoll Foundation        ORGANIZATION
3   ,                       ,
4   based                   VBN
5   in                      IN
6   Silicon Valley          LOCATION
Run Code Online (Sandbox Code Playgroud)

chr*_*isb 9

@ rfan的答案当然有效,作为替代方案,这是一种使用pandas groupby的方法.

.groupby()基团通过"B"列中的数据-的sort=False是需要保持顺序不变.将.apply()函数应用于每组b数据,在这种情况下将字符串连接在一起,用空格分隔.

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
Run Code Online (Sandbox Code Playgroud)

编辑:

为了处理更一般的情况(重复的非连续值) - 一种方法是首先添加一个跟踪列,该列跟踪每行适用的连续数据组,如下所示:

df['key'] = (df['b'] != df['b'].shift(1)).astype(int).cumsum()
Run Code Online (Sandbox Code Playgroud)

然后将密钥添加到groupby中,即使重复值也应该有效.例如,使用带有重复的虚拟数据:

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

应用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
Run Code Online (Sandbox Code Playgroud)


Rog*_*Fan 2

我实际上认为 @chrisb 的 groupby 解决方案更好,但是您需要创建另一个 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})
Run Code Online (Sandbox Code Playgroud)