You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 11:07:48