简体   繁体   中英

Count numbers of chinese characters for each row of one column in Python

Given a dataframe as follows:

   id            name
0   1             个体户
1   2              个人
2   3  利他润己企业管理有限公司
3   4    博通国际投资有限公司
4   5      西潼·科技有限公司
5   6      度咪科技有限公司

How could I count the numbers of chinese characters for each row of name column?

The expected result will be like this:

   id            name           count
0   1             个体户            3
1   2              个人             2
2   3    利他润己企业管理有限公司    12
3   4      博通国际投资有限公司      10
4   5        西潼科技有限公司        8
5   6        度咪科技有限公司        8

You can use str.count to do this together with a regex pattern:

df['count'] = df['name'].str.count(pat='[\u4e00-\u9fff]')

Result:

   id                    name   count
0   1                   个体户      3
1   2                    个人       2
2   3  利他润己企业管理有限公司      12
3   4      博通国际投资有限公司      10
4   5        西潼·科技有限公司       8
5   6         度咪科技有限公司       8

The following code works, but it will be appreciated if you could share other possible solutions.

def hans_count(str):
    hans_total = 0
    for s in str:
        if '\u4e00' <= s <= '\u9fef':
            hans_total += 1
    return hans_total

df['count'] = df['name'].apply(hans_count)
df

Out:

   id            name  count
0   1             个体户      3
1   2              个人      2
2   3    利他润己企业管理有限公司     12
3   4      博通国际投资有限公司     10
4   5        西潼科技有限公司     8
5   6        度咪科技有限公司     8

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