gpt4 book ai didi

python - 如何从 pandas 读取日期时间

转载 作者:太空宇宙 更新时间:2023-11-03 17:10:13 25 4
gpt4 key购买 nike

我将字符串转换为日期并保存 CSV:

df['date'] = pd.to_datetime(df['date'])
df.to_csv('dates.csv')

但是当我尝试读取 CSV 时,它得到的列为 str:

df = pd.read_csv('dates.csv')
type(df['date'].iloc[0])
<type 'str'>

如何将其保存为日期时间并读取为日期时间?

最佳答案

read_csv中有parse_dates参数。

parse_dates : boolean, list of ints or names, list of lists, or dict If True -> try parsing the index. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column. {'foo' : [1, 3]} -> parse columns 1, 3 as date and call result 'foo' A fast-path exists for iso8601-formatted dates.

所以:

df = pd.read_csv(filename, parse_dates=['date_col_1', 'date_col2', etc...])

具体示例:

df = pd.DataFrame({'date': ['2015-1-1', '2015-2-1', '2015-3-1']})
df['date'] = pd.to_datetime(df['date'])
df.to_csv('dates.csv')

df2 = pd.read_csv('dates.csv')

>>> type(df2['date'].iloc[0])
str

df2 = pd.read_csv('dates.csv', parse_dates=['date'])

>>> type(df2['date'].iloc[0])
pandas.tslib.Timestamp

关于python - 如何从 pandas 读取日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34168764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com