【发布时间】:2016-12-22 13:57:19
【问题描述】:
我先创建一些数据:
df = pd.DataFrame(data = {"A":np.random.random_integers(1,10,10), "B":np.arange(1,11,1)})
df.A.ix[3,4] = np.nan
然后我得到了一个带有 Nans 的 pd 数据框
A B
0 7 1
1 1 2
2 3 3
3 NaN 4
4 NaN 5
5 9 6
6 2 7
7 10 8
8 6 9
9 6 10
我尝试使用 pd.cut 函数对 A 列进行分组,并在每个组上添加使用聚合函数
bin_S = pd.cut(df.A, [-math.inf, 3,5,8,9, math.inf],right= False)
df.groupby(bin_S).agg("count")
但是 Nan 值没有分组(没有 Nan 类别)
A B
A
[-inf, 3) 2 2
[3, 5) 1 1
[5, 8) 3 3
[8, 9) 0 0
[9, inf) 2 2
然后我尝试通过以下方式添加一个名为“Missing”的新类别:
bin_S.cat.add_categories("Missing", inplace = True)
bin_S.fillna(value = "Missing", inplace = True
分箱系列看起来不错。但是,groupby 聚合并不是我所期望的。
df.groupby(bin_S).agg("count")
结果是,
A B
A
[-inf, 3) 2 2
[3, 5) 1 1
[5, 8) 3 3
[8, 9) 0 0
[9, inf) 2 2
Missing 0 2
我希望 A 列和 B 列完全相同。为什么它们在“缺失”行上有所不同?真正的问题涉及对每个组进行更复杂的操作。这个问题真的很困扰我,因为对 Nan 值进行分组可能不可靠。
【问题讨论】: