简体   繁体   中英

Python pandas - Replace string of Zeros in series

I have a pandas dataframe with a date variable with dates formatted like this "2011-01-11 01:11:11.111111+00." However, some dates with 0 for the timestamp are formatted like this ""2011-01-11 00:00:00.+00."

I have written a simple function to strip the last 10 digits leaving only the date and time with no decimals. But before stripping, I need to standardize the dates with 0 for time to have the same number of characters as all other dates.

So far I tried this code, but no change occurred. No error message was given.

df['time'] = df['time'].replace({"00:00:00+00":"00:00:00.000000+00"}, regex=True). 

I also tried it with regex=False and tried using str.replace instead.

PS here's my function to strip digits:

def strip_n_chars(df, col, n): 
    values = df[col]
    df[col]= values.str[:-n]
    

Does anyone now how I can replace the 0 timestamps? Or know of another way to strip all dates to end up like "2011-01-11 00:00:00"?

The first step should probably to get the df['time'] column into a Timestamp if that's not already done, by using pd.to_datetime .
Then you can use the dt accessor to output the format you like using the strftime method .
For example:

df['timestamp'] = pd.to_datetime(df['time'])
df['nice_date'] = df['timestamp'].dt.strftime('%x %X') #2011-01-11 00:00:00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM