'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 e.g. 'JohnDoe2719'. I want to count the amount of numbers in each user name e.g. 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.



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway