简体   繁体   中英

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'. 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.

Some help in this would be much appreciated.

You can use str.count with '\d' as regex:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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