pandas:如何将group by和union一起进行
pandas: how to perform group by and union together
我有以下格式的数据框:
domain c1 c2 c3 c4 c5 c6 c7 c8
--- -- -- -- -- -- -- -- --
0 facebook 0 1 1 0 0 0 1 0
1 facebook 1 0 0 0 0 0 1 1
2 google 1 0 0 1 0 1 0 0
3 google 0 1 0 0 1 0 0 1
4 google 0 0 0 1 1 0 0 1
domain
以外的列只能有 0 或 1 的值。
我想一起执行分组依据(在域上)和联合(在其余列上),以便输出显示组中每一列的值的并集。
在上面给出的示例数据中,我希望输出为:
domain c1 c2 c3 c4 c5 c6 c7 c8
--- -- -- -- -- -- -- -- --
0 facebook 1 1 1 0 0 0 1 1
1 google 1 1 0 1 1 1 0 1
我见过的分组依据示例在一列上应用分组依据,然后在其他列上应用聚合函数(求和、均值、最大值等)。我无法弄清楚如何在其余列上应用并集。
import pandas as pd
from io import StringIO
data = StringIO(u'''domain,c1,c2,c3,c4,c5,c6,c7,c8
facebook,0,1,1,0,0,0,1,0
facebook,1,0,0,0,0,0,1,1
google,1,0,0,1,0,1,0,0
google,0,1,0,0,1,0,0,1
google,0,0,0,1,1,0,0,1''')
df = pd.read_csv(data)
怎么样
df.groupby('domain').agg(any).astype(int)
这会给你
c1 c2 c3 c4 c5 c6 c7 c8
domain
facebook 1 1 1 0 0 0 1 1
google 1 1 0 1 1 1 0 1
我有以下格式的数据框:
domain c1 c2 c3 c4 c5 c6 c7 c8
--- -- -- -- -- -- -- -- --
0 facebook 0 1 1 0 0 0 1 0
1 facebook 1 0 0 0 0 0 1 1
2 google 1 0 0 1 0 1 0 0
3 google 0 1 0 0 1 0 0 1
4 google 0 0 0 1 1 0 0 1
domain
以外的列只能有 0 或 1 的值。
我想一起执行分组依据(在域上)和联合(在其余列上),以便输出显示组中每一列的值的并集。
在上面给出的示例数据中,我希望输出为:
domain c1 c2 c3 c4 c5 c6 c7 c8
--- -- -- -- -- -- -- -- --
0 facebook 1 1 1 0 0 0 1 1
1 google 1 1 0 1 1 1 0 1
我见过的分组依据示例在一列上应用分组依据,然后在其他列上应用聚合函数(求和、均值、最大值等)。我无法弄清楚如何在其余列上应用并集。
import pandas as pd
from io import StringIO
data = StringIO(u'''domain,c1,c2,c3,c4,c5,c6,c7,c8
facebook,0,1,1,0,0,0,1,0
facebook,1,0,0,0,0,0,1,1
google,1,0,0,1,0,1,0,0
google,0,1,0,0,1,0,0,1
google,0,0,0,1,1,0,0,1''')
df = pd.read_csv(data)
怎么样
df.groupby('domain').agg(any).astype(int)
这会给你
c1 c2 c3 c4 c5 c6 c7 c8
domain
facebook 1 1 1 0 0 0 1 1
google 1 1 0 1 1 1 0 1