Reputation: 10021
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
Upvotes: 1
Views: 1253
Reputation: 28332
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
Upvotes: 6
Reputation: 10021
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
Upvotes: 0