我有以下系列:
df产
Date
2001-01-03 True
2002-07-24 True
2002-07-29 True
2008-09-30 True
2008-10-13 True
2008-10-28 True
2008-11-13 True
2008-11-21 True
2008-11-24 True
2008-12-16 True
2009-03-10 True
2009-03-23 True
Name: pct_day, dtype: bool我怎样才能知道值之间有多少天是真实的,不包括周末?
发布于 2019-12-17 22:29:49
你可以这样做:
(例如,创建示例DataFrame )
>>> import pandas.util.testing as tm
>>> df = tm.makeTimeDataFrame(freq='M', nper=5)
>>> print(df)
A B C D
2000-01-31 1.051346 1.722165 -0.659687 1.026716
2000-02-29 0.352166 1.699898 1.469741 -0.138593
2000-03-31 -0.202217 -0.470095 0.169060 -0.241817
2000-04-30 0.446261 1.518129 2.263510 1.800027
2000-05-31 -0.088365 1.923264 1.763859 0.348480diff方法将计算这两个日期之间的datetime.timedelta,当然,零索引是NaT,因为它之前没有任何数据。
>>> df['time_delta'] = df.index.to_series().diff()
>>> print(df)
A B C D time_delta
2000-01-31 1.051346 1.722165 -0.659687 1.026716 NaT
2000-02-29 0.352166 1.699898 1.469741 -0.138593 29 days
2000-03-31 -0.202217 -0.470095 0.169060 -0.241817 31 days
2000-04-30 0.446261 1.518129 2.263510 1.800027 30 days
2000-05-31 -0.088365 1.923264 1.763859 0.348480 31 days然后,如果希望以浮点数而不是datetime对象的形式获取天数,则可以使用Series.dt访问器:
>>> days = df.time_delta.dt.days
>>> print(days)
2000-01-31 NaN
2000-02-29 29.0
2000-03-31 31.0
2000-04-30 30.0
2000-05-31 31.0
Freq: M, dtype: float64发布于 2019-12-17 22:24:20
这似乎是可行的:
import pandas as pd
df = pd.DataFrame({'Date' : pd.date_range(start='2/1/2018', end='2/08/2018', freq='D'),
'Label': 'True'})
df['DayOfWeek'] = df['Date'].dt.day_name()
df = df[(df.DayOfWeek != 'Saturday') & (df.DayOfWeek != 'Sunday') & (df.Label == 'True')]
df['Diff'] = df['Date'].diff()发布于 2019-12-17 22:32:56
可以使用索引上的to_frame()方法将索引转换为列,然后在该列上调用diff()。
df2 = df.index.to_frame()
df2['diff'] = df2[df.0 == True]https://stackoverflow.com/questions/59382468
复制相似问题