[英]How do I assign a group # to a set of rows in a pandas data frame?
數據框具有一個時間列,該列的int值從零開始。 我想將數據幀分為100組(例如),其中步驟為ts = df['time'].max()/100
。 一種簡單的方法是測試'time'列的每個值是否大於t
and
小於t+ts
,其中t
是一個np.linspace
向量,該向量從0
開始並在df['time'].max()
。
我的數據框如下所示:
df.head()
0 1 2 3 time
0 1 1 1 1130165891 59559371
1 2 1 1 1158784502 88177982
2 2 1 1 1158838664 88232144
3 2 1 1 1158838931 88232411
4 2 1 1 1158839132 88232612
您可以使用pd.cut
生成組:
df.groupby(pd.cut(df['time'], 2)).mean()
Out:
0 1 2 3 time
time
(59530697.759, 73895991.5] 1 1 1 1130165891 59559371
(73895991.5, 88232612] 2 1 1 1158825307 88218787
由於數據集非常小,因此只有2個組,並且最少開始。 您可以更改組數。 除了傳遞組數外,您還可以傳遞斷點(使用不帶np.linspace的傳遞點)。
df.groupby(pd.cut(df['time'], [0, 6*10**7, np.inf], include_lowest=True)).mean()
Out:
0 1 2 3 time
time
[0, 60000000] 1 1 1 1130165891 59559371
(60000000, inf] 2 1 1 1158825307 88218787
在兩個示例中,我均采用了均值的方法來向您展示其工作原理。 您可以對groupby對象使用其他方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.