pandas.groupby

时间:2019-03-06 14:09:35

标签: python pandas pandas-groupby

我觉得这对我来说是一个非常明显的错误,但是由于某种原因,解决方案现在正在逃避我。

因此,首先,创建以下数据框

import pandas as pd
A = {'device': 1, 'component': 100, 'value': 10}
B = {'device': 1, 'component': 100, 'value': 20}
C = {'device': 1, 'component': 101, 'value': 20}
D = {'device': 2, 'component': 100, 'value': 30}
E = {'device': 2, 'component': 100, 'value': 31}
F = pd.DataFrame([A, B, C, D, E])

现在,我想将一种方法应用于“设备”和“组件”的唯一组。为简单起见,假设我只是想获得数据框的形状

def simple(df):
  print(df.shape)

现在,将其应用于每个分组

F.groupby(['device', 'component']).apply(simple)

输出为

(2, 3)
(2, 3)
(1, 3)
(2, 3)

您所期望的是什么,但是现在让我们进行更改

A = {'device': 1, 'component': 100, 'value': 10}
B = {'device': 1, 'component': 100, 'value': 20}
C = {'device': 1, 'component': 100, 'value': 20}
F_new = pd.DataFrame([A, B, C])
F_new.groupby(['device', 'component']).apply(simple)

这给

(3, 3)
(3, 3)

为什么它一次不给我(3,3)只有一次

0 个答案:

没有答案