简体   繁体   中英

Python- Compute the sum of numerical characters of every string in a dataframe

so I have a dataframe with a column "dname". It contains many rows of 2LD domain names. ie [123ask , example92 , what3ver] .

I want to find the number of digits for every string in every row.

So, to create a new column in the dataframe with values ie [3 , 2 , 1] .

I have:

df['numeric']= sum (x.isdigit() for b in df['dname'] for x in b)

And all i get is 6 6 6 instead of 3 2 1

Any help ? Thanks in advance!

You almost had it.

df = {'dname':["123ask", "example92" , "what3ver"]}
df['numeric'] = [sum (x.isdigit()  for x in b) for b in df['dname']]
print df['numeric']
#>>> [3, 2, 1]
    df['numeric']= df['dname'].apply(lambda v : sum(x.isdigit() for x in v))

这会将所需的操作应用于所有行,并且速度更快

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