繁体   English   中英

如何在 pandas dataframe 中执行 groupby、排序和连接字符串

[英]how to perform a groupby, sort, and concatenate strings in a pandas dataframe

我有这个 pandas 框架:

PK  Line    Text    Source
1   1       The     A
1   2       quick   A
1   3       brown   A
2   1       fox     A
2   2       jumped  A
3   1       over    A
3   2       the     A
3   3       lazy    A
4   1       yellow  A
5   1       dogs    A
5   2       sam     A

我需要去:

PK  Text              Source
1   The quick brown   A
2   fox jumped        A
3   over the lazy     A
4   yellow            A
5   dogs sam          A

我试过了:

record.groupby('PK').apply(Lambda x: (' '.join(x)).sort_values('LINE', ascending))

但它接缝我错过了一些东西。 我怎样才能做到这一点?

谢谢!

看起来像groupby()和聚合:

df.groupby(['PK', 'Source'], as_index=False).Text.agg(' '.join)

您可以添加sort_values('Line')以确保行是有序的,例如

(df.sort_values('Line')
        .groupby(['PK', 'Source'], as_index=False)
        .Text.agg(' '.join)
)

Output:

   PK Source             Text
0   1      A  The quick brown
1   2      A       fox jumped
2   3      A    over the lazy
3   4      A           yellow
4   5      A         dogs sam

暂无
暂无

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

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