简体   繁体   English

如何让我的 dataframe 识别日期?

[英]How can I make my dataframe recognize dates?

I am working on a time series figure where the date progression is on the x axis and the corresponding value for that date is on the y axis.我正在研究一个时间序列图,其中日期进展位于 x 轴上,该日期的相应值位于 y 轴上。

My code:我的代码:

from dateutil.parser import parse
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd

plt.rcParams.update({'figure.figsize': (10, 7), 'figure.dpi': 120})

# Import as Dataframe
df = pd.DataFrame({'date': ['2021-01-03', '2021-01-05', '2021-01-07', '2021-01-09'],
        'value': ['3', '1', '2', '10']})

# Draw Plot
def plot_df(df, x, y, title="", xlabel='Days', ylabel='Tweets per day', dpi=100):
    plt.figure(figsize=(16,5), dpi=dpi)
    plt.plot(x, y, color='tab:blue')
    plt.gca().set(title=title, xlabel=xlabel, ylabel=ylabel)
    plt.show()

plot_df(df, x=df.index, y=df.value, title='Title')

I made two changes below, the first is converting to datetime object:我在下面做了两个更改,第一个是转换为 datetime object:

df['date'] = pd.to_datetime(df['date'])

the second is change the x variable to the correct date column instead of the index in the plot call第二个是将 x 变量更改为正确的日期列,而不是 plot 调用中的索引

plot_df(df, x=df['date'], y=df.value, title='Title')

full code is below for reference完整代码如下供参考

    # Import as Dataframe
df = pd.DataFrame({'date': ['2021-01-03', '2021-01-05', '2021-01-07', '2021-01-09'],
        'value': [3, 1, 2, 10]})
df['date'] = pd.to_datetime(df['date'])
# Draw Plot
def plot_df(df, x, y, title="", xlabel='Days', ylabel='Tweets per day', dpi=100):
    plt.figure(figsize=(16,5), dpi=dpi)
    plt.plot(x, y, color='tab:blue')
    plt.gca().set(title=title, xlabel=xlabel, ylabel=ylabel)
    plt.show()

plot_df(df, x=df['date'], y=df.value, title='Title')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM