René
René

Reputation: 4827

Python Pandas - Creating a timeseries from a csv file

I would like to create a timeseries 'aapl' by reading a csv file and set the first column as DatetimeIndex.

Here some lines from the csv file:

2000-01-03, 111.937502
2000-01-04, 102.500003
2000-01-05, 103.999997
2000-01-06,  94.999998
2000-01-07,  99.500001

The result show be like:

In [1]: aapl.head()
Out[1]: 
Date
2000-01-03    111.937502
2000-01-04    102.500003
2000-01-05    103.999997
2000-01-06     94.999998
2000-01-07     99.500001
Name: AAPL, dtype: float64

In [2]: type(aapl)
Out[2]: pandas.core.series.Series

In [3]: type(aapl.index)
Out[3]: pandas.tseries.index.DatetimeIndex

I tried:

aapl = pd.read_csv('aapl.csv', header=None)
aapl[0] = pd.to_datetime(aapl[0])
aapl.set_index(0, inplace=True)
aapl.index.name = 'Date'
print(type(aapl))
print(type(aapl.index))
print(aapl.head())

But that leaves me with:

<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>
                     1
Date                  
2000-01-03  111.937502
2000-01-04  102.500003
2000-01-05  103.999997
2000-01-06   94.999998
2000-01-07   99.500001

It's still a dataframe, not a series. And column with the values still has a column name.

All suggestions are welcome!

Upvotes: 3

Views: 1462

Answers (1)

jezrael
jezrael

Reputation: 863741

I think you can use parameter squeeze for convert to Series mainly:

import pandas as pd
from pandas.compat import StringIO

temp=u"""2000-01-03,111.937502
2000-01-04,102.500003
2000-01-05,103.999997
2000-01-06,94.999998
2000-01-07,99.500001"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
aapl = pd.read_csv(StringIO(temp), 
                   squeeze=True, 
                   index_col=[0], 
                   parse_dates=True, 
                   names=['Date','col'])

print(type(aapl))
<class 'pandas.core.series.Series'>

print(type(aapl.index))
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>

print(aapl.head())
Date
2000-01-03    111.937502
2000-01-04    102.500003
2000-01-05    103.999997
2000-01-06     94.999998
2000-01-07     99.500001
Name: col, dtype: float64

Upvotes: 4

Related Questions