Ian Langmore
Ian Langmore

Reputation: 2939

How to write/read pandas Series to/from csv?

I can't figure out how to write/read a Series correctly...The following (and many variations of it) results in the read series being different than the written series...note that the series is read into a DataFrame rather than a series.

In [55]: s = pd.Series({'a': 1, 'b': 2})

In [56]: s
Out[56]: 
a    1
b    2

In [57]: s.to_csv('/tmp/s.csv')

In [58]: !cat /tmp/s.csv
a,1
b,2

In [59]: pd.read_csv('/tmp/s.csv')
Out[59]: 
   a  1
0  b  2

Upvotes: 21

Views: 35383

Answers (4)

Noyer282
Noyer282

Reputation: 984

Apply .squeeze() to the DataFrame returned by pd.read_csv:

>>> s = pd.Series(pd.Series({'a': 1, 'b': 2}))
>>> s.to_csv('s.csv')
>>> pd.read_csv('s.csv', index_col = 0).squeeze()
a    1
b    2
Name: 0, dtype: int64

(The accepted solution with pd.Series.read_csv is depreciated by now.)

Upvotes: 0

johnD
johnD

Reputation: 21

Saving a pandas object to a file, and then re-creating that object from a file, you would use:

s.to_pickle('filename')

and

s = pd.read_pickle('filename')

methods.

Here's the details: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_pickle.html

Upvotes: 2

Wes McKinney
Wes McKinney

Reputation: 105481

In [3]: s.to_csv('/home/wesm/tmp/sfoo.csv')

In [4]: Series.from_csv('/home/wesm/tmp/sfoo.csv')
Out[4]: 
a    1
b    2

You can also pass header=None, index_col=0, squeeze=True to read_csv similar to what Rutger Kassies suggested.

Upvotes: 28

Rutger Kassies
Rutger Kassies

Reputation: 64453

A CSV doesnt contain any information about the structure of your pandas Series. Specifying some extra arguments might help. Getting the data back as normal is possible with:

pd.read_csv('s.csv', index_col=0, header=None)

But that adds default column and index names to it. If you just want to save your Series/DF for later use its better to use the .save() and pd.load() methods.

Upvotes: 6

Related Questions