获取python中GROUPBY两列上剩余的聚合列作为列表
我总共有5列,我想对两列进行分组,并希望得到列表中的其他列。我正在使用python熊猫。 我在这里举一个例子获取python中GROUPBY两列上剩余的聚合列作为列表,python,python-2.7,pandas,Python,Python 2.7,Pandas,我总共有5列,我想对两列进行分组,并希望得到列表中的其他列。我正在使用python熊猫。 我在这里举一个例子 BN PN tempC tempF humidity 0 7363311 1 28 82 73 1 7363311 2 27 81 73 2 7363311 3 27 81 73 3 736331
BN PN tempC tempF humidity
0 7363311 1 28 82 73
1 7363311 2 27 81 73
2 7363311 3 27 81 73
3 7363311 4 27 81 73
4 7363311 4 27 81 73
5 7363311 5 27 81 73
8 7363311 7 27 81 73
9 7363311 7 27 81 74
输出应该如下所示
BN PN tempC tempF humidity
7363311 1 28 82 73
2 27 81 73
3 27 81 73
4 [27,27] [81,81] [73,73]
5 27 81 73
7 [27,27] [81,81] [73,74]
我用下面的代码来分组
df.groupby(['BN','PN'])
首先需要聚合
元组
,然后转换为列表
s:
df = df.groupby(['BN','PN']).agg(tuple).applymap(list)
print (df)
tempC tempF humidity
BN PN
7363311 1 [28] [82] [73]
2 [27] [81] [73]
3 [27] [81] [73]
4 [27, 27] [81, 81] [73, 73]
5 [27] [81] [73]
7 [27, 27] [81, 81] [73, 74]
如果要将列表
s与标量
s组合,请添加If-else
语句:
df = df.groupby(['BN','PN']).agg(tuple).applymap(lambda x: x[0] if len(x) == 1 else list(x))
print (df)
tempC tempF humidity
BN PN
7363311 1 28 82 73
2 27 81 73
3 27 81 73
4 [27, 27] [81, 81] [73, 73]
5 27 81 73
7 [27, 27] [81, 81] [73, 74]
正在获取错误。。。ValueError:没有要连接的对象OK我知道了。。。正确的解决方案是df.groupby(['BN','PN']).aggregate(lambda x:tuple(x)).applymap(list)