pythonpandasmatplotlibdatetimedate-parsing

Pandas date parsing from CSV file


I have one csv file:

year;month;day;hour;min;sec;temperature
2022;10;27;13;36;42;5.835
2022;10;27;14;36;42;6.435
2022;10;27;15;36;42;6.335
2022;10;27;16;36;42;6.435

And I would like to plot a simple graph from it. I am not able to combine separate datetime parts. This is my code:

import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime

def parser(year, month, day, hour, minute, second):
    return pd.to_datetime(day + '.' + month + '.' + year + ' ' + hour + ':' + minute + ':' + second

df = pd.read_csv('temp_data.csv',sep=';',parse_dates={'datetime':['year', 'month', 'day', 'hour', 'min', 'sec']}, date_parser=parser,index_col=0)

time = df['datetime'].values
temp = df['temperature'].values

plt.plot(time, temp)

Solution

  • Update

    I would like the x-axis date format to be: 27.10.22

    You have to handle manually formatting.

    Simply use df.plot:

    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    
    # df = pd.read_csv(...)
    
    ax = df.plot()
    loc = mdates.DayLocator()
    fmt = mdates.DateFormatter('%d.%m.%y')
    ax.xaxis.set_major_locator(loc)
    ax.xaxis.set_major_formatter(fmt)
    plt.show()
    

    Output:

    enter image description here