Ahmed Nishaal
Ahmed Nishaal

Reputation: 96

ValueError on Pandas, and KeyError on Pandas or matplotlib.pyplot

There are two errors in my code, the first one a ValuError, regarding pandas while the second is a KeyError, regarding either pandas or matplotlib.pyplot


import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

This DataFrame is very small compared to the intitial one but I hope this is enough as i get the same errors on the DataFrame

df = {
    'Time': ['2021-07-06 20:51:00', '2021-07-06 20:52:00', '2021-07-06 20:53:00'],
    'Close': ['0.068029', '0.06805', '0.068014']
}


df = pd.DataFrame(df)
df['Time'] = pd.to_datetime(df['Time'])

On the line below, I'm getting a ValueError: Columns must be same length as key. I can run code just fine without this line but for future coding I'd like to know a fix for this

df['Time'] =  df.sort_values('Time', ascending=True)
df = df.set_index(['Time'])
df = df.dropna(how='any')

fig, ax = plt.subplots(figsize=(16, 8))
plt.plot(df.index, df['Close'],
         label="graph", color='gold')

Here, on the line below, I'm getting KeyError: 'Time'

plt.title('Gold' + str(np.min(df['Time']))) + str(np.max(df['Time']))

Upvotes: 1

Views: 54

Answers (1)

Celius Stingher
Celius Stingher

Reputation: 18377

This happens because you have previously set the column Time as the index for your dataframe, therefore df['Time'] will no longer be possible, I suggest you replace then the argument with df.index:

plt.title('Gold' +": "+ str(np.min(df.index)) +"-"+str(np.max(df.index)))

Edit: Modified code to make it more user friendly for the chart as well as adding output.

enter image description here

Upvotes: 3

Related Questions