大 pandas :计算下排的字符串条件 [英] pandas: count string criteria across down rows

查看:52
本文介绍了大 pandas :计算下排的字符串条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据框:

I have a dataframe that looks like:

  col_1
0  A
1  A:C:D
2  A:B:C:D:E
3  B:D

我试图计算每个':'得出:

I'm trying to count each ':' to get to:

  col_1        count
0  A             0
1  A:C:D         2
2  A:B:C:D:E     4
3  B:D           1

我尝试将一个函数应用到无济于事:

I've tried applying a function to no avail:

def count_fx(df):
    return df.str.contains(':').sum()
df['count'] = df['col_1'].apply(count_fx)

df['count'] = df['col_1'].apply(lambda x: (x.str.contains(':')).sum(), axis=1)

推荐答案

此处使用apply()的方式将导致传入每个元素.即,DataFrame是 not 传入的内容.因此,您只需要将功能更改为

The way you use apply() here causes each element to be passed in. I.e., the DataFrame is not what is passed in. So you just need to change your function to

def count_fx(s):
    return s.count(':')

然后,您可以使用自己拥有的东西:

Then you can use what you had:

In [11]: df['count'] = df['col_1'].apply(count_fx)

In [12]: df
Out[12]:
       col_1  count
0          A      0
1      A:C:D      2
2  A:B:C:D:E      4
3        B:D      1

这篇关于大 pandas :计算下排的字符串条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆