简体   繁体   English

Python pandas - 串联替换零串

[英]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."我有一个 pandas dataframe 的日期变量,其日期格式如下“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."但是,某些时间戳为 0 的日期的格式类似于“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.我写了一个简单的 function 来去除最后 10 位数字,只留下没有小数的日期和时间。 But before stripping, I need to standardize the dates with 0 for time to have the same number of characters as all other dates.但在剥离之前,我需要将日期标准化为 0,以便与所有其他日期具有相同数量的字符。

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.我还尝试使用 regex=False 并尝试使用 str.replace 代替。

PS here's my function to strip digits: PS这里是我的 function 去除数字:

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?现在有谁可以替换 0 时间戳? Or know of another way to strip all dates to end up like "2011-01-11 00:00:00"?或者知道另一种方法来删除所有日期以结束“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 .如果尚未完成,第一步可能应该使用pd.to_datetimedf['time']列放入 Timestamp 中。
Then you can use the dt accessor to output the format you like using the strftime method .然后您可以使用dt 访问器使用strftime 方法访问您喜欢的格式 output 。
For example:例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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