如何在Pandas中转换姓名格式:交换首尾并提取名字首字母
Solution for Pandas Name Formatting
Got it, let's tackle this name formatting problem in Pandas. Here's a straightforward solution that matches exactly what you're looking for:
First, let's define a helper function to transform each name string according to your rules:
import pandas as pd def format_name(name): # Remove leading/trailing whitespace first cleaned_name = name.strip() # Split into individual parts name_parts = cleaned_name.split() # First part is the given name, rest are the full surname (including middle surname parts) given_name = name_parts[0] surname = ' '.join(name_parts[1:]) # Return formatted string: Full surname + given initial with dot return f"{surname} {given_name[0]}."
Then apply this function to both columns in your DataFrame:
# Your original DataFrame df = pd.DataFrame({ 'Player1':['Roger Federer ', 'Alex De Minaur'], 'Player2':['Bernabe Zapata Miralles','Andy Roddick'] }) # Apply the formatting function to each column df['Player1'] = df['Player1'].apply(format_name) df['Player2'] = df['Player2'].apply(format_name) print(df)
Output:
Player1 Player2 0 Federer R. Zapata Miralles B. 1 De Minaur A. Roddick A.
How this works:
strip(): Cleans up any extra leading/trailing spaces in the name strings (like the trailing space in "Roger Federer ").split(): Breaks the name into a list of individual words.- We separate the first word as the given name and all remaining words as the full surname (this handles cases where surnames have multiple parts like "De Minaur" or "Zapata Miralles").
- Finally, we format the string to place the full surname first, followed by the initial of the given name with a dot.
内容的提问来源于stack exchange,提问作者Herwini
相关产品推荐
相关产品推荐

