我有一个要使用seaborn来创建tsplot的数据框,将DateTime从字符串转换为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进行绘制。
答案 0 :(得分:1)
您遇到的问题是DateTime对象将始终包含日期对象和时间对象的所有组件。无法拥有仅包含年份和月份信息的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)
能得到您想要的结果吗?