我经常在pandas中使用value_counts()方法来获取统计信息。
例如,我可以得到如下所示的value_counts()结果。
male 7825
female 6764
是否有任何内置函数可以获取数据框的索引,对应两个标签(男性和女性)。
预期结果:male_indices = [1,3,5,6,7, ..., 14589]
,其中len(male_indices)= 7825
答案 0 :(得分:1)
这是 groupby
的功能。考虑示例数据框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')}
答案 1 :(得分: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')}