如何为中有重复值的行返回单行

2024-04-24 13:31:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做得很快,不是从一行到另一行,因为这是一个相当大的文件。我在熊猫身上找不到任何东西,尽管桌子看起来很近。。。以下是我所拥有的:

A    B
0    Tree
0    Leaves
0    Buds
1    Ocean
1    Blue

我想要的是:

A    B
0    Tree ; Leaves ; Buds
1    Ocean ; Blue

Tags: 文件treeblueleavesocean桌子buds
2条回答

在Python中,可以通过使用some_delimiter.join(things_you_want_to_join)来连接事物,例如','.join("abc") == 'a,b,c'。我们可以将其应用于在A上分组后的B列:

>>> df.groupby("A")["B"].apply(' ; '.join)
A
0    Tree ; Leaves ; Buds
1            Ocean ; Blue
Name: B, dtype: object

然后将B作为名称返回:

>>> df.groupby("A")["B"].apply(' ; '.join).reset_index()
   A                     B
0  0  Tree ; Leaves ; Buds
1  1          Ocean ; Blue

我们可以在“a”上执行groupby,然后应用一个函数(在本例中是lambda),将所需的分隔符;与B值的列表连接起来。你知道吗

如果要恢复B列,可以调用reset_index()

In [238]:

gp = df.groupby('A')
gp.apply(lambda x: ' ; '.join([t for t in list(x['B'])])).reset_index()
Out[238]:
   A                     0
0  0  Tree ; Leaves ; Buds
1  1          Ocean ; Blue

相关问题 更多 >