Pandas Delete Part of String

后端 未结 1 474
借酒劲吻你
借酒劲吻你 2021-01-26 10:10
>>> df
                       Time
    5/10/2017 (135) 01:05:03
    5/11/2017 (136) 04:05:06

Given an input date such as this in a DataFrame,

相关标签:
1条回答
  • 2021-01-26 10:34

    You can use replace by regex:

    First need escape () by \ because special chars in regex, then match all ints by \d+ and last match zero or more whitespaces after ) by \s*.


    df['Time'] = df['Time'].str.replace("\(\d+\)\s*", '')
    print (df)
                     Time
    0  5/10/2017 01:05:03
    1  5/11/2017 04:05:06
    

    And if need convert to datetime:

    df['Time'] = pd.to_datetime(df['Time'].str.replace("\(\d+\)\s*", ''))
    print (df)
                     Time
    0 2017-05-10 01:05:03
    1 2017-05-11 04:05:06
    

    EDIT:

    In your sample are mising escaping chars \ and is possible use instead \d+ [0-9]+:

    df['Time'].replace('\([0-9]+\)\s*','', regex=True, inplace=True)
    print (df)
                     Time
    0  5/10/2017 01:05:03
    1  5/11/2017 04:05:06
    
    0 讨论(0)
提交回复
热议问题