저는 다양한 칼럼을 가진 데이터 프레임을 가지고 있으며, 각 그룹에 최소 유효 회원 수가 있다는 조건 하에서 그룹의 평균값을 계산하고 싶습니다. groupby, filter 및 mean을 사용하여 다음을 시도했습니다. 그것은 작동하는 것,하지만 나는 더 효율적인 솔루션이 있는지 궁금해?pandas groupby : 효율적인 조건부 집계?
import pandas as pd
import numpy as np
df = pd.DataFrame({'id' : ['one', 'one', 'two', 'three', 'two',
'two', 'two', 'one', 'three', 'one'],
'idprop' : [1., 1., 2., 3., 2., # property corresponding to id
2., 2., 1., 3., 1.],
'x' : np.random.randn(10),
'y' : np.random.randn(10)})
# set a couple of x values to nan
s = df['x'].values
s[s < -0.6] = np.nan
df['x'] = s
g = df.groupby('id', sort=False)
# filter out small group(s) with less than 3 valid values in x
# result is a new dataframe
dff = g.filter(lambda d: d['x'].count() >= 3)
# this means we must group again to obtain the mean value of each filtered group
result = dff.groupby('id').mean()
print result
print type(result)
how to get multiple conditional operations after a Pandas groupby?에 관련된 문제가되는, 그러나, 기 요소의 수에 의해 행 값들만 "필터". 이것은 내 코드로 변환 될 것입니다 : 측면의 질문으로
res2 = g.agg({'x': lambda d: df.loc[d.index, 'x'][d >= -0.6].sum()})
: 아래 또는 NaN이에 주어진 임계 값을 초과 값을 설정하는보다 효율적인 방법이? 내가 loc를 사용하여 이것을 시도 할 때 내 두뇌가 뒤 틀렸다.
'df.loc [df [ 'x'] <-0.6, 'x'] = np.nan' – IanS
나는'df.filter (...) .groupby ('id'). mean()'은 원하는 것을 얻는 가장 효율적인 방법입니다. – jonchar