Python/Pandas data frame time data in rows (grouped by name)

Viewed 45

I have a data frame in Pandas that is like this:

Name Date       Value
A    2020-09-30 7.82
A    2020-04-22 3.23
A    2020-02-01 1.34
B    2020-09-30 8.89
B    2020-09-01 4.56
C    2020-09-30 9.56
C    2020-03-30 8.23

And the goal is to create a graph where the different values of each name's value is plotted on a timeline graph. So, for example, A will have 3 values on the chart mapped according to the date it had those values.

I tried the following:

df.set_index('Date', inplace=True)
df.groupby('Name')['Value'].plot(legend=True)

However, the graph doesn't plot correctly, with the latest date to the left instead of the right. Also, since some Name's might have up to 5 Values and others only have up to 3, the graph doesn't seem to handle this very well. Finally, the data goes all the way from A to Z with a lot of entries and as such the above code creates an unreadable chart.

I am seeking guidance so I can better understand what approaches in Python/Pandas will work for this type of data.

1 Answers

This likely because your Date is string type, not datetime type; so Pandas/Matplotlib will just plot by the range index and label the data as the order the data shows up.

To fix the issue, just convert the Date to datetime type. Also, you can pass figsize option to plot so you can get a bigger plot:

df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
df.groupby('Name')['Value'].plot(legend=True, marker='o', figsize=(10,6))

Output:

enter image description here

Related