【问题标题】:Count Number of Rows within Time Interval in Pandas Dataframe在 Pandas Dataframe 中计算时间间隔内的行数
【发布时间】:2020-08-13 13:31:32
【问题描述】:

假设我们有这些数据:

list1, list2, list3 = [1,2,3,4], [1990, 1990, 1990, 1991], [2009, 2009, 2009, 2009]
df = pd.DataFrame(list(zip(list1, list2, 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())

但结果看起来不对。

感谢任何帮助。

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    你可以这样做:

    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
    

    【讨论】:

      【解决方案2】:

      以下内容应该可以完成您的工作:

      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'])
      

      【讨论】:

        猜你喜欢
        • 2017-09-02
        • 1970-01-01
        • 2021-04-16
        • 1970-01-01
        • 2014-02-26
        • 2016-03-13
        • 2020-08-25
        • 2021-07-26
        • 1970-01-01
        相关资源
        最近更新 更多