我有一只熊猫DataFrame df:
+------+---------+
| team | user |
+------+---------+
| A | elmer |
| A | daffy |
| A | bugs |
| B | dawg |
| A | foghorn |
| B | speedy |
| A | goofy |
| A | marvin |
| B | pepe |
| C | petunia |
| C | porky |
+------+---------
我想要查找或编写一个函数来返回一个DataFrame,我将使用以下代码在MySQL中返回该the:
SELECT
team,
GROUP_CONCAT(user)
FROM
df
GROUP BY
team
对于以下结果:
+------+---------------------------------------+
| team | group_concat(user) |
+------+---------------------------------------+
| A | elmer,daffy,bugs,foghorn,goofy,marvin |
| B | dawg,speedy,pepe |
| C | petunia,porky |
+------+---------------------------------------+
我可以想出一些糟糕的方法来做到这一点,方法是迭代行并添加到字典中,但总会有更好的方法。
发布于 2013-08-09 09:16:19
执行以下操作:
df.groupby('team').apply(lambda x: ','.join(x.user))
获取字符串的Series
或
df.groupby('team').apply(lambda x: list(x.user))
以获取字符串的list
%s的Series
。
结果如下所示:
In [33]: df.groupby('team').apply(lambda x: ', '.join(x.user))
Out[33]:
team
a elmer, daffy, bugs, foghorn, goofy, marvin
b dawg, speedy, pepe
c petunia, porky
dtype: object
In [34]: df.groupby('team').apply(lambda x: list(x.user))
Out[34]:
team
a [elmer, daffy, bugs, foghorn, goofy, marvin]
b [dawg, speedy, pepe]
c [petunia, porky]
dtype: object
请注意,通常情况下,对这些类型的Series
的任何进一步操作都将很慢,并且通常不鼓励这样做。如果有另一种方法可以在不将list
放入Series
的情况下进行聚合,那么您应该考虑使用这种方法。
发布于 2015-09-21 04:21:03
如果您想要使用agg
,一个更通用的解决方案
df.groupby('team').agg({'user' : lambda x: ', '.join(x)})
https://stackoverflow.com/questions/18138693
复制相似问题