Skip to content

Instantly share code, notes, and snippets.

@kyoro1
Last active June 20, 2018 12:00
Show Gist options
  • Save kyoro1/d4297c4d567d1177a2afc039f73c6c23 to your computer and use it in GitHub Desktop.
Save kyoro1/d4297c4d567d1177a2afc039f73c6c23 to your computer and use it in GitHub Desktop.
pandasでWindow関数的な集計 ref: https://qiita.com/kyoro1/items/ffe2a11986131857e6ef
import pandas as pd
import numpy as np
from numpy.random import *
from pandas import rolling_mean, rolling_apply
### Randomに0-1のデータを10個生成(numpy array形式)
tmp = rand(10) #
tmp
#array([0.05049257, 0.19130526, 0.38653303, 0.01820196, 0.28877423,
# 0.57416531, 0.85929624, 0.92731291, 0.27886026, 0.51936736])
df = pd.DataFrame(tmp)
df.columns = ['values']
## `ma`列に、直近3の幅の移動平均を計算した値を入れます
df['ma'] = pd.rolling_mean(df['values'], 3)
def count_threshold(x):
return np.sum(x>0.3)
df['count_threshold'] = pd.rolling_apply(df['values'], 3, count_threshold)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment