2015-10-17 102 views
0

我想通過年齡組低於20分割的數據幀,20至24,25至30和上述30.我能夠用數組來做到這一點的範圍迭代器,但我想知道是否有更好的方法來做到這一點。蟒&大熊貓:如何分割數據幀分成組

gates = [0,20,25,30,50] 
total = df.agepreg.isnull().sum() 
print("INAPPLICABLE {0}".format(total)) 
for i in range(0, 4): 
    t = df.agepreg[(df.agepreg>=gates[i]) & (df.agepreg<gates[i+1])].value_counts().sum() 
    print("{0} to {1} {2}".format(gates[i], gates[i+1], t)) 
    total += t 
print("Total {0}".format(total)) 

結果是這樣的

INAPPLICABLE 352 
0 to 20 3182 
20 to 25 4246 
25 to 30 3178 
30 to 50 2635 
Total 13593 

該數據來自nsfg。免費書籍thinkstats2github上有配套代碼和數據。

從'code'目錄中,您可以運行以下行來加載數據框。

import nsfg 
df = nsfg.ReadFemPreg() 
df 
+1

你能發表您的樣本數據? – Zero

回答

0

你可以groupbypd.cut(df['agrpreg'], [20,24,25,30,pd.np.inf], right=False)

創建20和35

In [643]: df = pd.DataFrame(pd.np.random.randint(20, 35, 100), columns=['agrpreg']) 

In [644]: df_cuts = (df 
        .groupby(pd.cut(df['agrpreg'], [20,24,25,30,pd.np.inf], right=False)) 
        .sum()) 

In [645]: df_cuts 
Out[645]: 
      agrpreg 
agrpreg 
[20, 24)  532 
[24, 25)  192 
[25, 30)  878 
[30, inf)  1093 

之間有100行的數據框與值檢查兩個總和匹配。

In [646]: df_cuts.sum() == df['agrpreg'].sum() 
Out[646]: 
agrpreg True 
dtype: bool 

瞭解pd.cut的作用 - 將每個值分組爲桶。

In [647]: df[:5] 
Out[647]: 
    agrpreg 
0  29 
1  25 
2  22 
3  28 
4  23 

In [648]: pd.cut(df['agrpreg'], [20,24,25,30,pd.np.inf], right=False)[:5] 
Out[648]: 
0 [25, 30) 
1 [25, 30) 
2 [20, 24) 
3 [25, 30) 
4 [20, 24) 
Name: agrpreg, dtype: category 
Categories (4, object): [[20, 24) < [24, 25) < [25, 30) < [30, inf)] 
+0

你可以總結一下嗎?我想知道懷孕對於每個年齡段的數量。 –

+1

而不是總數嘗試計數? – Zero