我有一个要使用matplotlib绘制的数据框,但是索引列是时间,我无法绘制它。

这是数据框(df3):



,但是当我尝试以下操作时:

plt.plot(df3['magnetic_mag mean'], df3['YYYY-MO-DD HH-MI-SS_SSS'], label='FDI')


我显然遇到了错误:

KeyError: 'YYYY-MO-DD HH-MI-SS_SSS'


所以我想做的是向数据框添加一个新的额外列(名为“时间”),它只是索引列的副本。

我该怎么办是吗?

这是完整的代码:

#Importing the csv file into df
df = pd.read_csv('university2.csv', sep=";", skiprows=1)

#Changing datetime
df['YYYY-MO-DD HH-MI-SS_SSS'] = pd.to_datetime(df['YYYY-MO-DD HH-MI-SS_SSS'], 
                                               format='%Y-%m-%d %H:%M:%S:%f')

#Set index from column
df = df.set_index('YYYY-MO-DD HH-MI-SS_SSS')

#Add Magnetic Magnitude Column
df['magnetic_mag'] = np.sqrt(df['MAGNETIC FIELD X (μT)']**2 + df['MAGNETIC FIELD Y (μT)']**2 + df['MAGNETIC FIELD Z (μT)']**2)

#Subtract Earth's Average Magnetic Field from 'magnetic_mag'
df['magnetic_mag'] = df['magnetic_mag'] - 30

#Copy interesting values
df2 = df[[ 'ATMOSPHERIC PRESSURE (hPa)',
          'TEMPERATURE (C)', 'magnetic_mag']].copy()

#Hourly Average and Standard Deviation for interesting values 
df3 = df2.resample('H').agg(['mean','std'])
df3.columns = [' '.join(col) for col in df3.columns]

df3.reset_index()
plt.plot(df3['magnetic_mag mean'], df3['YYYY-MO-DD HH-MI-SS_SSS'], label='FDI')  


谢谢!

#1 楼

我认为您需要reset_index

df3 = df3.reset_index()


inplace 不是一个好习惯,请检查以下内容:

df3.reset_index(inplace=True)


但是,如果您需要新的列,请使用:

df3['new'] = df3.index


我认为您可以更好地使用read_csv

df = pd.read_csv('university2.csv', 
                 sep=";", 
                 skiprows=1,
                 index_col='YYYY-MO-DD HH-MI-SS_SSS',
                 parse_dates='YYYY-MO-DD HH-MI-SS_SSS') #if doesnt work, use pd.to_datetime


然后忽略:

#Changing datetime
df['YYYY-MO-DD HH-MI-SS_SSS'] = pd.to_datetime(df['YYYY-MO-DD HH-MI-SS_SSS'], 
                                               format='%Y-%m-%d %H:%M:%S:%f')
#Set index from column
df = df.set_index('YYYY-MO-DD HH-MI-SS_SSS')


#2 楼

您可以直接访问索引并进行绘制,下面是一个示例:

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

df = pd.DataFrame(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))

#Get index in horizontal axis
plt.plot(df.index, df[0])
plt.show()




 #Get index in vertiacal axis
 plt.plot(df[0], df.index)
 plt.show()