2017-02-01 1 views
2

팬더에서 value_counts() 메소드를 사용하여 통계를 얻는 경우가 있습니다.팬더의 해당 색인 value_counts() 메소드

예를 들어 아래와 같이 value_counts() 결과를 얻을 수 있습니다.

male  7825 
female 6764 

두 레이블 (남성 및 여성)에 해당하는 데이터 프레임의 인덱스를 가져 오는 기본 제공 함수가 있습니까?

예상 결과 : male_indices = [1,3,5,6,7, ..., 14589] 렌 (male_indices) = 7825

+1

을 고려 – EdChum

답변

1

이것은 무엇입니까 groupby 않습니다. 방금 .index` [섹스 '] =='남성 '[DF']`안양을 할 수있는 예를 들어 dataframe df

np.random.seed([3,1415]) 
df = pd.DataFrame(dict(sex=np.random.choice(('male', 'female'), 10))) 
print(df) 

     sex 
0 male 
1 female 
2 male 
3 female 
4 male 
5 male 
6 female 
7 male 
8 female 
9 female 

사용 groupby.groups

df.groupby('sex').groups 

{'female': Int64Index([1, 3, 6, 8, 9], dtype='int64'), 
'male': Int64Index([0, 2, 4, 5, 7], dtype='int64')} 
0

여기 DataFrame 주어진 칼럼 내의 특정 그룹에 대응하는 인덱스를 반환 최소한 약간 견고한 함수의 중 :

# create some data 
d = pd.DataFrame({'sex': ['male', 'male', 'female', 'male', 'female', 'female', 'male'], 'age': [23, 24, 20, 32, 45, 43, 32]}) 

# returns a dictionary with group names as keys and indices corresponding 
# to those groups as values (can just use `list` or `set` to avoid pandas indexes 
def get_indices(df, col): 
    return {group: df[df[col] == group].index for group in set(df[col])} 

# test it out 
get_indices(d, 'sex') 
Out[178]: 
{'female': Int64Index([2, 4, 5], dtype='int64'), 
'male': Int64Index([0, 1, 3, 6], dtype='int64')} 
관련 문제