将列中的名称改为以大写字母开头

2024-06-28 15:39:12 发布

您现在位置:Python中文网/ 问答频道 /正文

背景

我有一个玩具df

import pandas as pd
df = pd.DataFrame({'Text' : ['Jon J Mmith is Here', 
                                   'Mary Lisa Hder found here', 
                                   'Jane A Doe is also here',
                                'Tom T Tcker is here too'], 

                      'P_ID': [1,2,3,4], 
                      'P_Name' : ['MMITH, JON J', 'HDER, MARY LISA', 'DOE, JANE A', 'TCKER, TOM T'],
                      'N_ID' : ['A1', 'A2', 'A3', 'A4']

                     })

#rearrange columns
df = df[['Text','N_ID', 'P_ID', 'P_Name']]
df

                    Text      N_ID  P_ID    P_Name
0   Jon J Mmith is Here         A1  1   MMITH, JON J
1   Mary Lisa Hder found here   A2  2   HDER, MARY LISA
2   Jane A Doe is also here     A3  3   DOE, JANE A
3   Tom T Tcker is here to     A4   4   TCKER, TOM T

目标

1)将P_Name列从df更改为类似于所需输出的格式;也就是说,将当前格式(例如MMITH, JON J)更改为一种格式(例如Mmith, Jon J),其中名字、姓氏和中间字母都以大写字母开头

2)在新列P_Name_New中创建

所需输出

                Text         N_ID P_ID    P_Name           P_Name_New
0   Jon J Mmith is Here         A1  1   MMITH, JON J     Mmith, Jon J
1   Mary Lisa Hder found here   A2  2   HDER, MARY LISA  Hder, Mary Lisa
2   Jane A Doe is also here     A3  3   DOE, JANE A      Doe, Jane A
3   Tom T Tcker is here too A4  4   TCKER, TOM T    Tcker, Tom T

问题

我如何达到我想要的目标?你知道吗


Tags: textnameiddfhereismarylisa
1条回答
网友
1楼 · 发布于 2024-06-28 15:39:12

只需使用str.title()函数:

In [98]: df['P_Name_New'] = df['P_Name'].str.title()                                                                            

In [99]: df                                                                                                                     
Out[99]: 
                         Text N_ID  P_ID            P_Name        P_Name_New
0         Jon J Smith is Here   A1     1      SMITH, JON J      Smith, Jon J
1  Mary Lisa Rider found here   A2     2  RIDER, MARY LISA  Rider, Mary Lisa
2     Jane A Doe is also here   A3     3       DOE, JANE A       Doe, Jane A
3    Tom T Tucker is here too   A4     4     TUCKER, TOM T     Tucker, Tom T

相关问题 更多 >