Pandas:向dataframe添加新列,这是索引列的副本

时间:2016-04-29 07:57:17

标签: python pandas matplotlib

我有一个数据帧,我想用matplotlib绘制,但索引列是时间,我无法绘制它。

这是数据帧(df3):

enter image description here

但是当我尝试以下内容时:

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

我明显收到错误:

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

所以我想做的是在我的数据帧中添加一个新的额外列(名为'Time),它只是索引列的副本。

我该怎么做?

这是整个代码:

#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')  

谢谢!

2 个答案:

答案 0 :(得分:10)

我认为你需要reset_index

df3.reset_index(inplace=True)

或者:

df3 = df3.reset_index()

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

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')

答案 1 :(得分:1)

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

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()

enter image description here

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

enter image description here