简体   繁体   English

计算字符串中的位数,然后在 Pandas 数据框中创建具有计数的新列

[英]Count number of digits in a string, then create new column with counts in Pandas dataframe

I have a pandas dataframe with a column that contains strings of Twitter screennames eg 'JohnDoe2719'.我有一个 pandas 数据框,其中有一列包含 Twitter 屏幕名称字符串,例如“JohnDoe2719”。 I want to count the amount of numbers in each user name eg 4, and then create a new column in my pandas dataframe with the counts for each screenname.我想计算每个用户名中的数字数量,例如 4,然后在我的 pandas 数据框中创建一个新列,其中包含每个用户名的计数。

Some help in this would be much appreciated.在这方面的一些帮助将不胜感激。

You can use str.count with '\d' as regex:您可以使用带有'\d' str.count作为正则表达式:

df = pd.DataFrame({'name': ['JohnDoe2719', 'JohnDoe123', 'JohnDoe']})

df['count'] = df['name'].str.count(r'\d')

output:输出:

          name  count
0  JohnDoe2719      4
1   JohnDoe123      3
2      JohnDoe      0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM