pandas 从数据框中的字符串中删除字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46544351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:34:41  来源:igfitidea点击:

Removing character from string in dataframe

pythonpandas

提问by Adrian Y

I have a dataframe, one column of which is filled with entries like this:

我有一个数据框,其中一列充满了这样的条目:

2017-03-01T09:30:00.436
2017-03-01T09:30:00.444
...

Is there a way to convert the entire column into datetime format?

有没有办法将整个列转换为日期时间格式?

So far I have tried using

到目前为止,我已经尝试使用

str.replace('T',' ') over iterrows()

as well as slicing methods but neither seems to work. Any help will be greatly appreciated. Thanks!

以及切片方法,但似乎都不起作用。任何帮助将不胜感激。谢谢!

回答by jezrael

Use regex=Truefor replacesubstrings:

使用regex=Truereplace字符串:

df['col'] = df['col'].replace('T', ' ', regex=True)

But maybe need only to_datetime:

但也许只需要to_datetime

df = pd.DataFrame({'col':['2017-03-01T09:30:00.436','2017-03-01T09:30:00.444']})

df['col'] = pd.to_datetime(df['col'])
print (df['col'])
0   2017-03-01 09:30:00.436
1   2017-03-01 09:30:00.444
Name: col, dtype: datetime64[ns]

回答by jgummersall

to_datetime()should work in converting it to datetime format

to_datetime()应该可以将其转换为日期时间格式