[英]Pandas returning empty groups in groupby
我有一個 Pandas DataFrame 有 3 列, target
, pred
和conf_bin
。 如果我運行groupby(by='conf_bin').apply(...)
我的 apply function 將被調用,空的DataFrame
s 沒有出現在conf_bin
列中的值。 這怎么可能?
細節
DataFrame 看起來像這樣:
target pred conf_bin
0 5 6 0.50
1 4 4 0.60
2 4 4 0.50
3 4 3 0.50
4 4 5 0.50
5 5 5 0.55
6 5 5 0.55
7 5 5 0.55
顯然conf_bin
是一個數值 bin,其值在np.arange(0, 1, 0.05)
范圍內。 但是,並非所有值都存在於數據中:
In [224]: grp = tp.groupby(by='conf_bin')
In [225]: grp.groups.keys()
Out[225]: dict_keys([0.5, 0.60000000000000009, 0.35000000000000003, 0.75, 0.85000000000000009, 0.65000000000000002, 0.55000000000000004, 0.80000000000000004, 0.20000000000000001, 0.45000000000000001, 0.40000000000000002, 0.30000000000000004, 0.70000000000000007, 0.25])
因此,例如,值0
和0.05
不會出現。 但是,當我在組上運行apply
程序時,我的 function 確實會被要求提供這些值:
In [226]: grp.apply(lambda x: x.shape)
Out[226]:
conf_bin
0.00 (0, 3)
0.05 (0, 3)
0.10 (0, 3)
0.15 (0, 3)
0.20 (22, 3)
0.25 (75, 3)
0.30 (95, 3)
0.35 (870, 3)
0.40 (8505, 3)
0.45 (40068, 3)
0.50 (51238, 3)
0.55 (54305, 3)
0.60 (47191, 3)
0.65 (38977, 3)
0.70 (34444, 3)
0.75 (20435, 3)
0.80 (3352, 3)
0.85 (4, 3)
0.90 (0, 3)
dtype: object
問題:
DataFrame
中?DataFrame
對象調用我的 apply function 以獲取未出現在grp.groups
中的值?我也遇到了這個問題,當我嘗試為我的數據框中的每個類別創建子圖時,這個問題就出現了。
我想出了以下解決方法(基於此 SO 帖子),將非空組拉到列表中。
groups = df.groupby('conf_bin')
group_list = [(index, group) for index, group in groups if len(group) > 0]
它確實打破了“你在熊貓中糾纏你的數據”的隱含契約,並且可能會管理不善,但它確實有效。
現在,您可以使用與 groupby 對象相同的界面遍歷 groupby 列表,例如
fig, axes = plt.subplots(nrows=len(group_list), ncols=1)
for (index, group), ax in zip(group_list, axes.flatten()):
group['target'].plot(ax=ax, title=index)
使用分類數據類型的主要優點是:
缺點是:
您可以從這篇文章中獲得更深入的信息: https://medium.com/gitconnected/pandas-category-type-pros-and-cons-1bcac1bdea71
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.