w3resource

Pandas: Calculate the number of characters in each word in a given series


25. Word Character Count

Write a Pandas program to calculate the number of characters in each word in a given series.

Sample Solution :

Python Code :

import pandas as pd
series1 = pd.Series(['Php', 'Python', 'Java', 'C#'])
print("Original Series:")
print(series1)
result = series1.map(lambda x: len(x))
print("\nNumber of characters in each word in the said series:")
print(result)

Sample Output:

Original Series:
0       Php
1    Python
2      Java
3        C#
dtype: object

Number of characters in each word in the said series:
0    3
1    6
2    4
3    2
dtype: int64

Explanation:

In the above exercise -

series1 = pd.Series(['Php', 'Python', 'Java', 'C#']): This code creates a Pandas Series object 'series1' containing four strings representing different programming languages.

result = series1.map(lambda x: len(x)): This code applies a lambda function to each element of the Pandas Series object 'series1' using the .map() method. The lambda function takes a string x and returns the length of the string using the len() function.


For more Practice: Solve these Related Problems:

  • Write a Pandas program to calculate the number of vowels in each word in a Series.
  • Write a Pandas program to compute the number of characters in each word and then normalize these counts.
  • Write a Pandas program to count the number of alphabetic characters in each word of a Series, ignoring punctuation.
  • Write a Pandas program to calculate the character count for each word and filter out words with less than 4 characters.

Go to:


Previous: Write a Pandas program convert the first and last character of each word to upper case.
Next: Write a Pandas program to compute difference of differences between consecutive numbers of a given series.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.