如何在不转换为字符串的情况下改变日期时间格式

2024-10-01 04:48:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框,我正在尝试使用seaborn创建一个tsplot,在将DateTime从string转换为DateTime对象之后,我遇到的第一个问题是日期已经被自动添加。你知道吗

原始数据帧如下所示:

zillowvisualtop5.head()
Out[161]: 
        City_State     Year     Price
0     New York, NY  1996-04  169300.0
1  Los Angeles, CA  1996-04  157700.0
2      Houston, TX  1996-04   86500.0
3      Chicago, IL  1996-04  114000.0
6      Phoenix, AZ  1996-04   88100.0

(注意日期是年-月格式) 在我把它转换成DateTime对象以便我可以使用seaborn绘制它之后,我得到了在月份之后添加日期的问题。你知道吗

zillowvisualtop5['Year'] = pd.to_datetime(zillowvisualtop5['Year'], format= '%Y-%m')
zillowvisualtop5.head()
Out[165]: 
        City_State       Year     Price
0     New York, NY 1996-04-01  169300.0
1  Los Angeles, CA 1996-04-01  157700.0
2      Houston, TX 1996-04-01   86500.0
3      Chicago, IL 1996-04-01  114000.0
6      Phoenix, AZ 1996-04-01   88100.0

我找到的解决方案似乎建议转换为strftime,但是我需要我的时间是DateTime格式,这样我就可以使用seaborn来绘制它。你知道吗


Tags: 对象citynewdatetimeseabornoutyearprice
1条回答
网友
1楼 · 发布于 2024-10-01 04:48:12

您遇到的问题是,DateTime对象总是包含date对象和time对象的所有组件。不能让DateTime对象只包含年份和月份信息(源:here)。你知道吗

但是,可以像这样使用matplotlib转换器:

import pandas as pd
from pandas.plotting import register_matplotlib_converters
import seaborn as sns

cols = ['City', 'Price', 'Month']
data = [['New York', 125, '1996-04'],
        ['New York', 79, '1996-05'],
        ['New York', 85, '1996-06'],
        ['Houston', 90, '1996-04'],
        ['Houston', 95, '1996-05'],
        ['Houston',127, '1996-06']]

df = pd.DataFrame(data, columns = cols)
print (df)

chart = sns.lineplot(x='Month', y='Price', hue='City', data=df)

enter image description here

这能得到你想要的结果吗?你知道吗

相关问题 更多 >