w3resource

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

Pandas: Data Series Exercise-25 with Solution

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.

Python-Pandas Code Editor:

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

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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/pandas/python-pandas-data-series-exercise-25.php