如何解决计算熊猫数据帧中时间间隔内的行数
说我们有以下数据:
list1,list2,list3 = [1,2,3,4],[1990,1990,1991],[2009,2009,2009]
df = pd.DataFrame(list(zip(list1,list3)),columns = ['Index','Y0','Y1'])
> df
Index Y0 Y1
1 1990 2009
2 1990 2009
3 1990 2009
4 1991 2009
我想每年计算一下一年内有多少行(“索引”),但不包括Y0。
假设我们从1990年的第一个可用年份开始
我们计算多少行? 0。
1991:
- 三个(第1、2、3行)
1992年:
- 四个(第1、2、3、4行)
...
2009:
- 四个(第1、2、3、4行)
所以我想得到一个数据框,上面写着:
Count Year
0 1990
3 1991
4. 1992
... ...
4 2009
我的尝试:
df['Y0'] = pd.to_datetime(df['Y0'],format='%Y')
df['Y1'] = pd.to_datetime(df['Y1'],format='%Y')
# Group by the interval between Y0 and Y1
df = d.groupby([d['Y0'].dt.year,d['Y1'].dt.year]).agg({'count'})
df.columns = ['count','Y0 count','Y1 count']
# sum the total
df_sum = pd.DataFrame(df.groupby(df.index)['count'].sum())
但是结果看起来不正确。
感谢任何帮助。
解决方法
您可以这样做:
min_year = df[['Y0','Y1']].values.min()
max_year = df[['Y0','Y1']].values.max()
year_range = np.arange(min_year,max_year+1)
counts = ((df[['Y0']].values < year_range) & (year_range<= df[['Y1']].values)).sum(axis=0)
o = pd.DataFrame({"counts": counts,'year': year_range})
counts year
0 0 1990
1 3 1991
2 4 1992
3 4 1993
4 4 1994
5 4 1995
6 4 1996
7 4 1997
8 4 1998
9 4 1999
10 4 2000
11 4 2001
12 4 2002
13 4 2003
14 4 2004
15 4 2005
16 4 2006
17 4 2007
18 4 2008
19 4 2009
,
以下应能完成您的工作:
counts=[]
years=[]
def count_in_interval(year):
n=0
for i in range(len(df)):
if df['Y0'][i]<year<=df['Y1'][i]:
n+=1
return n
for i in range(1990,2010):
counts.append(count_in_interval(i))
years.append(i)
result=pd.DataFrame(zip(counts,years),columns=['Count','Year'])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。