Python 熊猫时间戳系列到字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44741587/
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-08-20 00:25:03  来源:igfitidea点击:

pandas timestamp series to string?

pythonarrayspandasvector

提问by StatsStudent

I am new to python (coming from R), and I am trying to understand how I can convert a timestamp series in a pandas dataframe (in my case this is called df['timestamp']) into what I would call a string vector in R. is this possible? How would this be done?

我是 python 的新手(来自 R),我试图了解如何将 Pandas 数据帧中的时间戳系列(在我的情况下称为df['timestamp'])转换为我在 R 中称为字符串向量的内容。这可能吗? ? 这将如何完成?

I tried df['timestamp'].apply('str'), but this seems to simply put the entire column df['timestamp']into one long string. I'm looking to convert each element into a string and preserve the structure, so that it's still a vector (or maybe this a called an array?)

我试过了df['timestamp'].apply('str'),但这似乎只是将整个列df['timestamp']放入一个长字符串中。我希望将每个元素转换为字符串并保留结构,以便它仍然是一个向量(或者这可能是一个称为数组?)

回答by piRSquared

Consider the dataframe df

考虑数据框 df

df = pd.DataFrame(dict(timestamp=pd.to_datetime(['2000-01-01'])))

df

   timestamp
0 2000-01-01

Use the datetime accessor dtto access the strftimemethod. You can pass a format string to strftimeand it will return a formatted string. When used with the dtaccessor you will get a series of strings.

使用 datetimedt访问器访问该strftime方法。您可以将格式字符串传递给strftime它,它会返回一个格式化的字符串。与dt访问器一起使用时,您将获得一系列字符串。

df.timestamp.dt.strftime('%Y-%m-%d')

0    2000-01-01
Name: timestamp, dtype: object

Visit strftime.orgfor a handy set of format strings.

访问strftime.org一组方便的格式字符串。

回答by VinceP

Use astype

astype

>>> import pandas as pd
>>> df = pd.to_datetime(pd.Series(['Jul 31, 2009', '2010-01-10', None])) 
>>> df.astype(str)
0    2009-07-31
1    2010-01-10
2           NaT
dtype: object

returns an array of strings

返回一个字符串数组

回答by MarMat

Following on from VinceP's answer, to convert a datetime Series in-place do the following:

继 VinceP 的回答之后,要就地转换日期时间系列,请执行以下操作:

df['Column_name']=df['Column_name'].astype(str)

df['Column_name']=df['Column_name'].astype(str)