python - Pandas:获取跨越多年的 Dateranges 的每年计数

标签 python pandas date-arithmetic summarize

我有一个包含多年记录的数据框:

WarName    |     StartDate     |    EndDate
---------------------------------------------
 'fakewar1'    01-01-1990           02-02-1995
 'examplewar'  05-01-1990           03-07-1998
 (...)
 'examplewar2'  05-07-1999           06-09-2002

我正在尝试将此数据框转换为每年总 war 的摘要概述,例如:

  Year  |  Number_of_wars
----------------------------
  1989         0
  1990         2
  1991         2
  1992         3
  1994         2

通常我会使用像 df.groupby('year').count() 这样的东西来按年获得全面 war ,但由于我目前正在使用范围而不是设置日期,这种方法不会工作。

我目前正在编写一个生成年份列表的函数,然后对于列表中的每一年检查数据框中的每一行并运行一个函数来检查年份是否在该行的日期范围内(返回如果是这种情况,则为真)。

years = range(1816, 2006)
year_dict = {}
for year in years:
for index, row in df.iterrows():
    range = year_in_range(year, row)
    if range = True: 
       year_dict[year] = year_dict.get(year, 0) + 1

这行得通,但看起来也非常复杂。所以我想知道,我错过了什么?解决此问题的规范“ Pandas 方式”是什么?

最佳答案

pd.value_counts 使用推导式

pd.value_counts([
    d.year for s, e in zip(df.StartDate, df.EndDate)
    for d in pd.date_range(s, e, freq='Y')
]).sort_index()

1990    2
1991    2
1992    2
1993    2
1994    2
1995    1
1996    1
1997    1
1999    1
2000    1
2001    1
dtype: int64

备用

from functools import reduce

def r(t):
    return pd.date_range(t.StartDate, t.EndDate, freq='Y')

pd.value_counts(reduce(pd.Index.append, map(r, df.itertuples())).year).sort_index()

设置

df = pd.DataFrame(dict(
    WarName=['fakewar1', 'examplewar', 'feuxwar2'],
    StartDate=pd.to_datetime(['01-01-1990', '05-01-1990', '05-07-1999']),
    EndDate=pd.to_datetime(['02-02-1995', '03-07-1998', '06-09-2002'])
), columns=['WarName', 'StartDate', 'EndDate'])

df

      WarName  StartDate    EndDate
0    fakewar1 1990-01-01 1995-02-02
1  examplewar 1990-05-01 1998-03-07
2    feuxwar2 1999-05-07 2002-06-09

关于python - Pandas:获取跨越多年的 Dateranges 的每年计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50440186/

相关文章:

sql - 在oracle中查找一个月中的周数

mysql - 计算MySQL中有多少个月

Python-pandas : the truth value of a series is ambiguous

python - 我如何强制 PyCharm 对未声明的类型发出警告?

python - 连接两个具有相同分区数但不同列数的数据框(dask)

python - 根据 pandas 中的 csv 文件名重命名列

python - 如何使用 Python 将新行数据添加到 CSV 文件?

python - 修改文件文本

python - pandas for 循环导出文件包含所有条件

Oracle 日期计算 trunc(sysdate)