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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With