为了账号安全,请及时绑定邮箱和手机立即绑定

pandas:如何返回字符串列的字符串长度计数?

pandas:如何返回字符串列的字符串长度计数?

一只甜甜圈 2022-05-19 18:53:54
说我有一个数据框dfimport pandas as pddf = pd.DataFrame({"id":["a", "b", "aa", "aaa", "bbb", "a"]})在这种情况下,我想计算列 id 的字符串长度计数。在这个例子中id,长度为 1 的字符串有 3 个,长度为 2 的字符串有 1 个,长度为 3 的字符串有 2 个。所以我想要一个反映这些信息的表str_length  count1           32           13           2对数百万行执行此操作的最有效方法是什么?这是我能想到的最好的,但我听说使用apply很慢df_count = df.id.apply(lambda x: len(x)).value_counts()df_count2 = pd.DataFrame({"str_length": df_count.index.tolist(), "count": df_count})df_count2.sort_values("str_length")产生。   str_length  count1           1      32           2      13           3      2
查看完整描述

3 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

干得好


df.id.str.len().value_counts()

1    3

3    2

2    1

Name: id, dtype: int64


查看完整回答
反对 回复 2022-05-19
?
杨魅力

TA贡献1811条经验 获得超6个赞

一个麻木的解决方案:


np.transpose(np.unique(df.id.map(len), return_counts=True))


Out[229]:

array([[1, 3],

       [2, 1],

       [3, 2]], dtype=int64)

创建数据框


pd.DataFrame(np.transpose(np.unique(df.id.map(len), return_counts=True)), 

             columns=['str_length', 'count'])


Out[231]:

   str_length  count

0           1      3

1           2      1

2           3      2


查看完整回答
反对 回复 2022-05-19
?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

使用 groupby 和计数。


(

    df.groupby(by=df.id.apply(len))

    .id.count()

    .to_frame('count')

    .rename_axis(index='str_length')

    .reset_index()

)


    str_length  count

0   1           3

1   2           1

2   3           2


查看完整回答
反对 回复 2022-05-19
  • 3 回答
  • 0 关注
  • 342 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号