Python Pandas 计算特定值的出现次数

新手上路,请多包涵

我试图找出某个值在一列中出现的次数。

我用 data = pd.DataFrame.from_csv('data/DataSet2.csv') 制作了数据框

现在我想找出某物在一列中出现的次数。这是怎么做到的?

我以为是下面,我正在查看教育列并计算 ? 发生的次数。

下面的代码显示我正在尝试查找 9th 出现的次数,并且错误是我在运行代码时得到的

代码

missing2 = df.education.value_counts()['9th']
print(missing2)

错误

KeyError: '9th'

原文由 JJSmith 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 776
2 个回答

您可以根据您的条件创建 subset 数据,然后使用 shapelen

 print df
  col1 education
0    a       9th
1    b       9th
2    c       8th

print df.education == '9th'
0     True
1     True
2    False
Name: education, dtype: bool

print df[df.education == '9th']
  col1 education
0    a       9th
1    b       9th

print df[df.education == '9th'].shape[0]
2
print len(df[df['education'] == '9th'])
2

性能很有趣,最快的解决方案是比较 numpy 数组和 sum

图形

代码

 import perfplot, string
np.random.seed(123)

def shape(df):
    return df[df.education == 'a'].shape[0]

def len_df(df):
    return len(df[df['education'] == 'a'])

def query_count(df):
    return df.query('education == "a"').education.count()

def sum_mask(df):
    return (df.education == 'a').sum()

def sum_mask_numpy(df):
    return (df.education.values == 'a').sum()

def make_df(n):
    L = list(string.ascii_letters)
    df = pd.DataFrame(np.random.choice(L, size=n), columns=['education'])
    return df

perfplot.show(
    setup=make_df,
    kernels=[shape, len_df, query_count, sum_mask, sum_mask_numpy],
    n_range=[2**k for k in range(2, 25)],
    logx=True,
    logy=True,
    equality_check=False,
    xlabel='len(df)')

原文由 jezrael 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 countsum 的几种方法

In [338]: df
Out[338]:
  col1 education
0    a       9th
1    b       9th
2    c       8th

In [335]: df.loc[df.education == '9th', 'education'].count()
Out[335]: 2

In [336]: (df.education == '9th').sum()
Out[336]: 2

In [337]: df.query('education == "9th"').education.count()
Out[337]: 2

原文由 Zero 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题