python - 基于每日时间序列数据框创建工作日/周末时间序列数据框

标签 python python-3.x pandas numpy

例如,我创建了一个包含时间序列信息的数据框

Time      daily-bill
2012-01-01   200
2012-01-02  300
2012-01-03   100
2012-01-04    500
….

我想根据上述时间序列创建另一个时间序列数据框。如何在 Pandas 中做到这一点?

Time(weekday-and-weekend)                       total-bill
Monday-Friday
Weekend
Monday-Friday
Weekend
Monday-Friday
Weekend

换句话说,时间步将是weekdayweekend的连续序列。 工作日周一至周五组成;而周末星期六星期日组成。 total-bill 列将存储相应日期发生的账单总和,这些信息来自现有的时间序列。

最佳答案

用途:

print (df)
        Time  daily-bill
0 2012-01-01         200
1 2012-01-02         300
2 2012-01-03         100
3 2012-01-04         500
4 2012-01-05         200
5 2012-01-06         300
6 2012-01-07         100
7 2012-01-08         500
8 2012-01-09         500

arr = np.where(df['Time'].dt.weekday > 4, 'Weekend','Monday-Friday')

s = pd.Series(arr)
s1 = s.ne(s.shift()).cumsum()

df = (df['daily-bill'].groupby([s1,s.rename('Time')])
                     .sum()
                     .reset_index(level=0, drop=True)
                     .reset_index())
print (df)
            Time  daily-bill
0        Weekend         200
1  Monday-Friday        1400
2        Weekend         600
3  Monday-Friday         500

说明:

  1. 首先由 weekday 创建系列numpy.where .
  2. 然后创建另一个由 cumsum 创建的系列移动 s 的次数 shift用于区分连续值
  3. 聚合sum并按 reset_index 删除第一级与 drop=True

详细信息:

print (s)
0          Weekend
1    Monday-Friday
2    Monday-Friday
3    Monday-Friday
4    Monday-Friday
5    Monday-Friday
6          Weekend
7          Weekend
8    Monday-Friday
dtype: object

print (s1)
0    1
1    2
2    2
3    2
4    2
5    2
6    3
7    3
8    4
dtype: int32

编辑:

如果输入DataFrame的第一列是DatetimeIndex:

print (df)
            daily-bill
Time                  
2012-01-01         200
2012-01-02         300
2012-01-03         100
2012-01-04         500
2012-01-05         200
2012-01-06         300
2012-01-07         100
2012-01-08         500
2012-01-09         500

arr = np.where(df.index.weekday > 4, 'Weekend','Monday-Friday')

s = pd.Series(arr, index=df.index)
s1 = s.ne(s.shift()).cumsum()

df = (df['daily-bill'].groupby([s1,s.rename('Time')])
                     .sum()
                     .reset_index(level=0, drop=True)
                     .reset_index())
print (df)
            Time  daily-bill
0        Weekend         200
1  Monday-Friday        1400
2        Weekend         600
3  Monday-Friday         500

关于python - 基于每日时间序列数据框创建工作日/周末时间序列数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51815172/

相关文章:

python - 使用 `gopy` ,如何正确地将 []string 从 Python 传递给 Go?

python - 数据框查找行以返回索引

python - pyinotify 方法未调用

python - PyOpenGL,无法使用两个不同的VBO进行绘制

python - 将 pandas 时间序列从 object dtype 重新索引为 datetime dtype

python - 从 Dataframe 中提取不同的值并将它们插入到具有相同列名称的新 Dataframe 中

python - 使用 py.test 在 Python 中测试正则表达式

image - 在 python 中使用 PIL 模糊图像

python - 为什么无法从 Python 的 apply 函数内部访问其他变量?

python - Pandas :如何更新数据框并附加新条目?