w3resource

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


24. Capitalize Boundaries

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.


For more Practice: Solve these Related Problems:

  • Write a Pandas program to convert the first and last characters of each string in a Series to uppercase and reverse the string.
  • Write a Pandas program to capitalize only the first and last letters of each word in a Series and then sort the Series.
  • Write a Pandas program to transform a Series by converting the first and last characters of words to uppercase and adding a prefix.
  • Write a Pandas program to modify a Series of words by capitalizing the first and last letters only if the word length is greater than 3.

Go to:


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.

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.