2024-04-24 13:31:06 发布
网友
我想做得很快,不是从一行到另一行,因为这是一个相当大的文件。我在熊猫身上找不到任何东西,尽管桌子看起来很近。。。以下是我所拥有的:
A B 0 Tree 0 Leaves 0 Buds 1 Ocean 1 Blue
我想要的是:
A B 0 Tree ; Leaves ; Buds 1 Ocean ; Blue
在Python中,可以通过使用some_delimiter.join(things_you_want_to_join)来连接事物,例如','.join("abc") == 'a,b,c'。我们可以将其应用于在A上分组后的B列:
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():
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
在Python中,可以通过使用
some_delimiter.join(things_you_want_to_join)
来连接事物,例如','.join("abc") == 'a,b,c'
。我们可以将其应用于在A
上分组后的B
列:然后将
B
作为名称返回:我们可以在“a”上执行groupby,然后应用一个函数(在本例中是lambda),将所需的分隔符
;
与B值的列表连接起来。你知道吗如果要恢复B列,可以调用
reset_index()
:相关问题 更多 >
编程相关推荐