简体   繁体   English

数据帧转换和字符串连接

[英]Dataframe transformation and string concatenate

I have a pandas dataframe that looks like this: 我有一个像这样的pandas数据框:

index, a, b
0, i, this
1, belong, is 
2, here, right
0, only, one
0, two, another
1, items, example

And I am trying to get the output so that running indexes get folded up and concatenates the strings: 我试图获取输出,以便运行索引折叠起来并连接字符串:

index, a, b
0, i belong here, this is right
1, only, one
2, two items, another example

Any idea how to do this in a clean way? 知道如何以干净的方式做到这一点?

You need create groups starting with 0 in index and cumulative sum, then aggregate join : 您需要在index和累积总和中创建以0开头的组,然后聚合join

#if index is column
df = df.groupby(df['index'].eq(0).cumsum(), as_index=False).agg(' '.join)
#if index is not column
#df = df.groupby((df.index == 0).cumsum(), as_index=False).agg(' '.join)
print (df)
               a                b
0  i belong here   this is  right
1           only              one
2      two items  another example

Details : 细节

print (df['index'].eq(0).cumsum())
0    1
1    1
2    1
3    2
4    3
5    3
Name: index, dtype: int32

#print ((df.index == 0).cumsum())
#[1 1 1 2 3 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM