Pandas计算两个日期列

时间:2017-07-20 07:40:00

标签: python pandas dataframe

我需要计算各行之间的行date_from和date_to,例如:

我有这个DataFrame: date_from date_to

0    2017-07-01  2017-07-03
1    2017-07-01  2017-07-05
2    2017-07-02  2017-07-04
3    2017-07-03  2017-07-04

我需要计算列date_from和date_to之间的行数,例如:

              count
date
2017-07-01    2
2017-07-02    3
2017-07-03    3
2017-07-04    1

我尝试过:

df.groupby(['date_from','date_to']).size()

但是熊猫计算一次

修改

我需要计算两个日期之间有多少行, 只有一行的数据框:

    date_from     date_to
0 2017-07-01    2017-07-03

有这个输出: 2017-07-01 1 2017-07-02 1

1 个答案:

答案 0 :(得分:1)

我认为你需要:

df['date_to'] = df['date_to'] - pd.to_timedelta(1, unit='d')
df = df.stack().rename_axis(('a','b')).reset_index(name='c').set_index('c')
df = df.groupby('a').resample('d').ffill().groupby('c').size().reset_index(name='a')
print (df)
           c  a
0 2017-07-01  2
1 2017-07-02  3
2 2017-07-03  3
3 2017-07-04  1

类似的解决方案:

df['date_to'] = df['date_to'] - pd.to_timedelta(1, unit='d')
df = df.stack().rename_axis(('a','b')).reset_index(name='c').set_index('c')
df = df.groupby('a').resample('d')['b'].size().reset_index()
#
df = df['c'].value_counts().sort_index().rename_axis('a').reset_index()
print (df)
           a  c
0 2017-07-01  2
1 2017-07-02  3
2 2017-07-03  3
3 2017-07-04  1

另一个itertuples的解决方案:

df['date_to'] = df['date_to'] - pd.to_timedelta(1, unit='d')

df=pd.concat([pd.Series(r.Index,
                        pd.date_range(r.date_from, r.date_to)) for r in df.itertuples()])
      .reset_index()

df = df['index'].value_counts().sort_index().rename_axis('a').reset_index(name='c')
print (df)
           a  c
0 2017-07-01  2
1 2017-07-02  3
2 2017-07-03  3
3 2017-07-04  1
相关问题