반응형
예
s=pd.Series([5,4,3,2,1], index=[1,2,3,4,5])
print s
1 5
2 4
3 3
4 2
5 1
시리즈를 만드는 효율적인 방법이 있습니까? 예 : 각 행에 지연된 값 포함 (이 예에서는 지연 2까지)
3 [3, 4, 5]
4 [2, 3, 4]
5 [1, 2, 3]
이는 s = pd.Series ([[3,4,5], [2,3,4], [1,2,3]], index = [3,4,5]) 에 해당합니다. em>
매우 긴 시계열이 많은 데이터 프레임에 대해 어떻게 효율적으로 수행 할 수 있습니까?
감사
답변을 본 후 수정 됨
좋아, 결국이 기능을 구현했습니다.
def buildLaggedFeatures(s,lag=2,dropna=True):
'''
Builds a new DataFrame to facilitate regressing over all possible lagged features
'''
if type(s) is pd.DataFrame:
new_dict={}
for col_name in s:
new_dict[col_name]=s[col_name]
# create lagged Series
for l in range(1,lag+1):
new_dict['%s_lag%d' %(col_name,l)]=s[col_name].shift(l)
res=pd.DataFrame(new_dict,index=s.index)
elif type(s) is pd.Series:
the_range=range(lag+1)
res=pd.concat([s.shift(i) for i in the_range],axis=1)
res.columns=['lag_%d' %i for i in the_range]
else:
print 'Only works for DataFrame or Series'
return None
if dropna:
return res.dropna()
else:
return res
원하는 출력을 생성하고 결과 DataFrame에서 열 이름 지정을 관리합니다.
입력으로 시리즈의 경우 :
s=pd.Series([5,4,3,2,1], index=[1,2,3,4,5])
res=buildLaggedFeatures(s,lag=2,dropna=False)
lag_0 lag_1 lag_2
1 5 NaN NaN
2 4 5 NaN
3 3 4 5
4 2 3 4
5 1 2 3
입력으로 DataFrame의 경우 :
s2=s=pd.DataFrame({'a':[5,4,3,2,1], 'b':[50,40,30,20,10]},index=[1,2,3,4,5])
res2=buildLaggedFeatures(s2,lag=2,dropna=True)
a a_lag1 a_lag2 b b_lag1 b_lag2
3 3 4 5 30 40 50
4 2 3 4 20 30 40
5 1 2 3 10 20 30
해결 방법
In [11]: pd.concat([s, s.shift(), s.shift(2)], axis=1)
Out[11]:
0 1 2
1 5 NaN NaN
2 4 5 NaN
3 3 4 5
4 2 3 4
5 1 2 3
In [12]: pd.concat([s, s.shift(), s.shift(2)], axis=1).dropna()
Out[12]:
0 1 2
3 3 4 5
4 2 3 4
5 1 2 3
이 작업을 수행하면 목록에있는 것보다 더 효율적입니다 ...
참조 페이지 https://stackoverflow.com/questions/20410312
반응형
'파이썬' 카테고리의 다른 글
파이썬 NoneType이 작동하지 않는 Python 검사 (0) | 2020.12.28 |
---|---|
파이썬 Python에서 전역 변수를 변경하는 방법 (0) | 2020.12.28 |
파이썬 virtualenv를 사용하는 flask라는 모듈이 없습니다. (0) | 2020.12.28 |
파이썬 그리드를 유지하면서 x 축 눈금 제거 (matplotlib) (0) | 2020.12.28 |
파이썬 변수를 사용하여 네트워크 공유에서 로컬 디스크로 파일을 복사하는 방법은 무엇입니까? (0) | 2020.12.28 |
댓글