计算熊猫数据帧中时间间隔内的行数

问题描述

说我们有以下数据:

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())

但是结果看起来不正确。

感谢任何帮助。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)