w3resource

Pandas Data Series: Convert the first and last character of each word to upper case

Pandas: Data Series Exercise-24 with Solution

Write a Pandas program convert the first and last character of each word to upper case in each word of 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: x[0].upper() + x[1:-1] + x[-1].upper())
print("\nFirst and last character of each word to upper case:")
print(result)

Sample Output:

Original Series:
0       php
1    python
2      java
3        c#
dtype: object

First and last character of each word to upper case:
0       PhP
1    PythoN
2      JavA
3        C#
dtype: object

Explanation:

series1 = pd.Series(['php', 'python', 'java', 'c#']): This line creates a Pandas Series object 'series1' containing four strings representing different programming languages.

result = series1.map(lambda x: x[0].upper() + x[1:-1] + x[-1].upper()): This line applies a lambda function to each element of the Pandas Series object 'series1' using the .map() method. The lambda function takes a string x, capitalizes the first and last character of the string using string indexing, and returns the modified string.

Python-Pandas Code Editor:

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

Previous: Write a Pandas program to get the positions of items of a given series in another given series.
Next: Write a Pandas program to calculate the number of characters in each word in 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://w3resource.com/python-exercises/pandas/python-pandas-data-series-exercise-24.php