如何将一个数据映射到具有较少行数、索引在给定间隔内的行的求和值的另一个df中?
例如
给定df:
Survived
Age
20 1
22 1
23 3
24 2
30 2
33 1
40 8
42 7期望df
(间隔为5):
Survived
Age
20 7
25 0
30 3
35 0
40 15(间隔为10):
Survived
Age
20 7
30 3
40 15发布于 2016-07-11 08:13:52
您可以为groupby参数使用一个函数:
In [6]: df.groupby(lambda x: x//10 * 10).sum()
Out[6]:
Survived
20 7
30 3
40 15注意,这也适用于5,但它不像你想要的那样与空组一起工作,也就是说,它不填充零!
In [12]: df.groupby(lambda x: x//5 *5).sum()
Out[12]:
Survived
20 7
30 3
40 15但是,如果数据在5间隔中包含这些组的值,则可以看到它正在工作。
In [18]: df
Out[18]:
Survived
Age
20 1
22 1
23 3
24 2
26 99
30 2
33 1
40 8
42 7
47 99
In [19]: df.groupby(lambda x: x//5 *5).sum()
Out[19]:
Survived
20 7
25 99
30 3
40 15
45 99发布于 2016-07-11 08:13:10
首先将int索引转换为TimedeltaIndex,然后将resample转换为
df.index = pd.TimedeltaIndex(df.index.to_series(), unit='s')
print (df)
Survived
00:00:20 1
00:00:22 1
00:00:23 3
00:00:24 2
00:00:30 2
00:00:33 1
00:00:40 8
00:00:42 7
df1 = df.resample('5S').sum().fillna(0)
df1.index = df1.index.seconds
print (df1)
Survived
20 7.0
25 0.0
30 3.0
35 0.0
40 15.0
df2 = df.resample('10S').sum().fillna(0)
df2.index = df2.index.seconds
print (df2)
Survived
20 7
30 3
40 15编辑:
如果Age > 60,效果也很好:
print (df)
Survived
Age
20 1
22 1
23 3
24 2
30 2
33 1
40 8
42 7
60 8
62 7
70 8
72 7df.index = pd.TimedeltaIndex(df.index.to_series(), unit='s')
df1 = df.resample('5S').sum().fillna(0)
df1.index = df1.index.seconds
print (df1)
Survived
20 7.0
25 0.0
30 3.0
35 0.0
40 15.0
45 0.0
50 0.0
55 0.0
60 15.0
65 0.0
70 15.0
df2 = df.resample('10S').sum().fillna(0)
df2.index = df2.index.seconds
print (df2)
Survived
20 7.0
30 3.0
40 15.0
50 0.0
60 15.0
70 15.0发布于 2016-07-11 08:11:05
您可以从列Age创建一个新列,然后使用groupby:
为了创建新列,需要从索引中删除Age:
df.reset_index(inplace = True)
def cat_age(age):
return 10*int(age/10.)
df['category_age'] = df.Age.apply(lambda x: cat_age(x))
df.groupby('category_age',as_index = False).agg({'Survived':sum})输出:
category_age Survived
0 20 7
1 30 3
2 40 15当然,如果要更改类别,可以在cat_age中传递间隔。
def cat_age(age,interval)
return interval*int(1.*age/interval)https://stackoverflow.com/questions/38301806
复制相似问题