Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the dates from pandas dataframe?

Tags:

python

pandas

I would like to put the dates in a variable in order to pass them via django to charts.js.

Now I have the problem, that I cannot access the dates, since they are apparently in the second row.

print df['Open'] or print df['High'] works fpr example, but print df['Date'] doesn't work.

Can you guys tell me how I can restructure the df in a way that I can print the dates as well?

Thanks a lot for your help and kind regards.

Dates are not accessable

like image 734
Mars Avatar asked Jun 19 '17 10:06

Mars


1 Answers

First column is called index, so for select need:

print (df.index)

dates = df.index

Or add DataFrame.reset_index for new column from values of index:

df = df.reset_index()
dates = df['Date']

Sample:

df = pd.DataFrame({'Open':[1,2,3], 'High':[8,9,2]},
                  index=pd.date_range('2015-01-01', periods=3))
df.index.name = 'Date'
print (df)
            High  Open
Date                  
2015-01-01     8     1
2015-01-02     9     2
2015-01-03     2     3

print (df.index)
DatetimeIndex(['2015-01-01', '2015-01-02', '2015-01-03'], 
dtype='datetime64[ns]', name='Date', freq='D')

df = df.reset_index()
print (df['Date'])
0   2015-01-01
1   2015-01-02
2   2015-01-03
Name: Date, dtype: datetime64[ns]
df.reset_index(inplace=True)
print (df['Date'])
0   2015-01-01
1   2015-01-02
2   2015-01-03
Name: Date, dtype: datetime64[ns]
like image 168
jezrael Avatar answered Nov 19 '22 23:11

jezrael