Pandas - Convert the first and last character of each word to upper case in a series

Pandas - Convert the first and last character of each word to upper case in a series

To convert the first and last character of each word in a Pandas Series to upper case, you can use a combination of Python's string manipulation functions and the apply method in Pandas. Here's a step-by-step guide to achieving this:

Step 1: Create a Pandas Series

First, create a Pandas Series that contains the strings you want to modify. If you already have a Series, you can skip this step.

import pandas as pd data = ["hello", "world", "pandas", "python"] series = pd.Series(data) 

Step 2: Define a Function to Modify the Strings

You need a function that takes a string and returns a new string with the first and last character in uppercase.

def first_last_upper(word): if len(word) > 1: return word[0].upper() + word[1:-1] + word[-1].upper() else: # For single character strings or empty strings return word.upper() 

Step 3: Apply the Function to the Series

Use the apply method to apply the function to each element in the Series.

modified_series = series.apply(first_last_upper) 

Example

Putting it all together:

import pandas as pd # Sample data data = ["hello", "world", "pandas", "python"] series = pd.Series(data) # Function to convert first and last character to upper case def first_last_upper(word): if len(word) > 1: return word[0].upper() + word[1:-1] + word[-1].upper() else: return word.upper() # Apply the function modified_series = series.apply(first_last_upper) print(modified_series) 

Output

This will output a series where each word has its first and last character converted to upper case:

0 HellO 1 WorlD 2 PandaS 3 PythoN dtype: object 

This method efficiently handles each word in the series, taking care of edge cases like single-character strings or empty strings.


More Tags

soap backslash contenteditable kerberos bmp wkhtmltoimage wikipedia-api dinktopdf intentfilter oh-my-zsh

More Programming Guides

Other Guides

More Programming Examples