【问题标题】:Pythonic way to fill rows with date range用日期范围填充行的 Pythonic 方法
【发布时间】:2019-05-15 18:09:45
【问题描述】:

我正在处理一个问题陈述,要求我填写缺失日期的行(即 Pandas 数据框列中两个日期之间的日期)。请看下面的例子。我目前的方法是使用 Pandas(如下所述)。

输入数据示例(大约有 25000 行)

A  | B  | C  | Date1    | Date2
a1 | b1 | c1 | 1Jan1990 | 15Aug1990 <- this row should be repeated for all dates between the two dates
.......................
a3 | b3 | c3 | 11May1986 | 11May1986 <- this row should NOT be repeated. Just 1 entry since both dates are same.
.......................
a5 | b5 | c5 | 1Dec1984 | 31Dec2017 <- this row should be repeated for all dates between the two dates
..........................
..........................

预期输出:

A  | B  | C  | Month    | Year
a1 | b1 | c1 | 1        | 1990  <- Since date 1 column for this row was Jan 1990
a1 | b1 | c1 | 2        | 1990    
.......................
.......................
a1 | b1 | c1 | 7        | 1990  
a1 | b1 | c1 | 8        | 1990  <- Since date 2 column for this row was Aug 1990
..........................
a3 | b3 | c3 | 5        | 1986  <- only 1 row since two dates in input dataframe were same for this row.
...........................
a5 | b5 | c5 | 12       | 1984 <- since date 1 column for this row was Dec 1984
a5 | b5 | c5 | 1        | 1985 
..........................
..........................
a5 | b5 | c5 | 11       | 2017 
a5 | b5 | c5 | 12       | 2017 <- Since date 2 column for this row was Dec 2017

我知道实现这一目标的更传统方法(我目前的方法):

  • 遍历每一行。
  • 获取两个日期列之间的天数差。
  • 如果两列中的日期相同,则只需在输出数据框中包含该月份和年份的一行
  • 如果日期不同(diff > 0),则获取每个日期差异行的所有(月、年)组合并附加到新数据框

由于输入数据大约有 25000 行,我相信输出数据会非常大,所以我正在寻找更多 Pythonic 方式 来实现这一点(如果可能比迭代方法更快)!

【问题讨论】:

  • 因此,根据您的预期输出,您希望在日期之间的每个月都有一个新行,对吧?
  • 是的。但包含(不排除)月份(这两列的日期)。我还更新了输入和输出以包含两个日期相同的情况。
  • 我投票决定将此问题作为题外话结束,因为有效但可以改进的代码应该在 codereview.stackexchange.com 上,而不是 stackoverflow.com

标签: python python-3.x pandas date dataframe


【解决方案1】:

在我看来,这里使用的最佳工具是PeriodIndex(生成日期之间的月份和年份)。

但是,PeriodIndex 一次只能对一行进行操作。所以,如果我们要去 要使用 PeriodIndex,必须单独处理每一行。那 不幸的是,意味着循环遍历 数据框:

import pandas as pd
df = pd.DataFrame([('a1','b1','c1','1Jan1990','15Aug1990'),
                   ('a3','b3','c3','11May1986','11May1986'),
                   ('a5','b5','c5','1Dec1984','31Dec2017')],
                  columns=['A','B','C','Date1','Date2'])

result = [] 
for tup in df.itertuples():
    index = pd.PeriodIndex(start=tup.Date1, end=tup.Date2, freq='M')
    new_df = pd.DataFrame([(tup.A, tup.B, tup.C)], index=index)
    new_df['Month'] = new_df.index.month
    new_df['Year'] = new_df.index.year
    result.append(new_df)
result = pd.concat(result, axis=0)
print(result)

产量

          0   1   2  Month  Year
1990-01  a1  b1  c1      1  1990    <--- Beginning of row 1
1990-02  a1  b1  c1      2  1990
1990-03  a1  b1  c1      3  1990
1990-04  a1  b1  c1      4  1990
1990-05  a1  b1  c1      5  1990
1990-06  a1  b1  c1      6  1990
1990-07  a1  b1  c1      7  1990
1990-08  a1  b1  c1      8  1990    <--- End of row 1
1986-05  a3  b3  c3      5  1986    <--- Beginning and End of row 2
1984-12  a5  b5  c5     12  1984    <--- Beginning row 3
1985-01  a5  b5  c5      1  1985
1985-02  a5  b5  c5      2  1985
1985-03  a5  b5  c5      3  1985
1985-04  a5  b5  c5      4  1985
...      ..  ..  ..    ...   ...
2017-09  a5  b5  c5      9  2017
2017-10  a5  b5  c5     10  2017
2017-11  a5  b5  c5     11  2017
2017-12  a5  b5  c5     12  2017    <--- End of row 3

[406 rows x 5 columns]

请注意,您可能真的不需要定义 MonthYear

new_df['Month'] = new_df.index.month
new_df['Year'] = new_df.index.year

因为您已经有了一个 PeriodIndex ,这使得计算月份和年份变得非常容易。

【讨论】:

  • 虽然必须使用您的示例遍历每一行,但它的工作原理就像魅力一样(并且显然比我目前的方法更快)。谢谢!
【解决方案2】:

给定样本数据

df = pd.DataFrame({'Date1': ["1Jan1990", "11May1986", "1Dec1984"],
                   'Date2': ["5Jul1990", "11May1986", "7Apr1985"],
                   'A': ['a1', 'a3', 'a5'],
                   'B': ['b1', 'b3', 'b5'],
                   'C': ['c1', 'c3', 'c5'],})  

这是一个没有显式迭代的解决方案

# Convert to pandas datetime
df['Date1'] = pd.to_datetime(df['Date1'])
df['Date2'] = pd.to_datetime(df['Date2'])

# Split and stack by dates
df = pd.concat([df.drop('Date2', 1).rename(columns={'Date1': 'Date'}),
                df.drop('Date1', 1).rename(columns={'Date2': 'Date'})])
df = df.drop_duplicates().set_index('Date')

# Break down by dates
df = (df.groupby(['A', 'B', 'C'], as_index=False)
      .resample('M') # with end of month interval
      .ffill() # propagating everything else forward
      .reset_index(level=0, drop=True)) # getting rid of auxiliary index

# Get the year and a month
df['Year'] = df.index.year
df['Month'] = df.index.month

导致

             A   B   C  Year  Month
Date                               
1990-01-31  a1  b1  c1  1990      1
1990-02-28  a1  b1  c1  1990      2
1990-03-31  a1  b1  c1  1990      3
1990-04-30  a1  b1  c1  1990      4
1990-05-31  a1  b1  c1  1990      5
1990-06-30  a1  b1  c1  1990      6
1990-07-31  a1  b1  c1  1990      7
1986-05-31  a3  b3  c3  1986      5
1984-12-31  a5  b5  c5  1984     12
1985-01-31  a5  b5  c5  1985      1
1985-02-28  a5  b5  c5  1985      2
1985-03-31  a5  b5  c5  1985      3
1985-04-30  a5  b5  c5  1985      4

【讨论】:

    【解决方案3】:

    这是使用 2 个辅助理解和 numpy.repeat 的另一种方法

    import numpy as np
    import pandas as pd
    
    repeats = (pd.to_datetime(df['Date2']) - pd.to_datetime(df['Date1'])) // np.timedelta64(1, 'M') + 1
    periods = np.concatenate([pd.period_range(start=pd.to_datetime(d), periods=r, freq='M')
                              for d, r in zip(df['Date1'], repeats)])
    
    new_df = (pd.DataFrame(
                np.repeat(df.values, repeats, 0),
                columns=df.columns,
                index=periods)
              .assign(month = [x.month for x in periods],
                      year = [x.year for x in periods])
              .drop(['Date1', 'Date2'], axis=1))
    
    print(new_df)
    
    [out]
              A   B   C  month  year
    1990-01  a1  b1  c1      1  1990
    1990-02  a1  b1  c1      2  1990
    1990-03  a1  b1  c1      3  1990
    1990-04  a1  b1  c1      4  1990
    1990-05  a1  b1  c1      5  1990
    1990-06  a1  b1  c1      6  1990
    1990-07  a1  b1  c1      7  1990
    1990-08  a1  b1  c1      8  1990
    1986-05  a3  b3  c3      5  1986
    1984-12  a5  b5  c5     12  1984
    1985-01  a5  b5  c5      1  1985
    1985-02  a5  b5  c5      2  1985
    1985-03  a5  b5  c5      3  1985
    1985-04  a5  b5  c5      4  1985
    1985-05  a5  b5  c5      5  1985
    1985-06  a5  b5  c5      6  1985
    1985-07  a5  b5  c5      7  1985
    1985-08  a5  b5  c5      8  1985
    1985-09  a5  b5  c5      9  1985
    1985-10  a5  b5  c5     10  1985
    1985-11  a5  b5  c5     11  1985
    1985-12  a5  b5  c5     12  1985
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 2011-04-02
      • 2020-12-06
      相关资源
      最近更新 更多