【问题标题】:Change names in pandas column to start with uppercase letters将 pandas 列中的名称更改为以大写字母开头
【发布时间】:2019-11-23 13:59:00
【问题描述】:

背景

我有一个玩具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

问题

如何实现我的预期目标?

【问题讨论】:

    标签: python string pandas text apply


    【解决方案1】:

    只需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
    

    【讨论】:

    • 执行apply lambda x: x.title 之类的操作是否有任何性能或其他差异?谢谢!
    • @patrick, %timeit df['P_Name'].str.title() 110 µs ± 1.99 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) -- %timeit df['P_Name'].apply(lambda x: x.title()) 146 µs ± 483 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    相关资源
    最近更新 更多