Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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
like image 755
Ian Langmore Avatar asked Nov 26 '12 01:11

Ian Langmore


People also ask

How do I convert CSV to series in Python?

to_csv() function write the given series object to a comma-separated values (csv) file/format. Parameter : path_or_buf : File path or object, if None is provided the result is returned as a string. sep : String of length 1.

How do you write data to CSV file in Python using pandas?

By using pandas. DataFrame. to_csv() method you can write/save/export a pandas DataFrame to CSV File. By default to_csv() method export DataFrame to a CSV file with comma delimiter and row index as the first column.

How do you save series in pandas?

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.


2 Answers

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.

like image 55
Wes McKinney Avatar answered Sep 20 '22 11:09

Wes McKinney


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.

like image 21
Rutger Kassies Avatar answered Sep 18 '22 11:09

Rutger Kassies