Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringIO and pandas read_csv

Tags:

python

pandas

I'm trying to mix StringIO and BytesIO with pandas and struggling with some basic stuff. For example, I can't get "output" below to work, whereas "output2" below does work. But "output" is closer to the real world example I'm trying to do. The way in "output2" is from an old pandas example but not really a useful way for me to do it.

import io   # note for python 3 only             # in python2 need to import StringIO  output = io.StringIO() output.write('x,y\n') output.write('1,2\n')  output2 = io.StringIO("""x,y 1,2 """) 

They seem to be the same in terms of type and contents:

type(output) == type(output2) Out[159]: True  output.getvalue() == output2.getvalue() Out[160]: True 

But no, not the same:

output == output2 Out[161]: False 

More to the point of the problem I'm trying to solve:

pd.read_csv(output)   # ValueError: No columns to parse from file pd.read_csv(output2)  # works fine, same as reading from a file 
like image 514
JohnE Avatar asked Dec 24 '15 04:12

JohnE


People also ask

What is the difference between read_table and read_csv in pandas?

The difference between read_csv() and read_table() is almost nothing. In fact, the same function is called by the source: read_csv() delimiter is a comma character. read_table() is a delimiter of tab \t .

What does read_csv do in pandas?

The pandas. read_csv is used to load a CSV file as a pandas dataframe. In this article, you will learn the different features of the read_csv function of pandas apart from loading the CSV file and the parameters which can be customized to get better output from the read_csv function.

How do I read a Textframe file in pandas?

We can read data from a text file using read_table() in pandas. This function reads a general delimited file to a DataFrame object. This function is essentially the same as the read_csv() function but with the delimiter = '\t', instead of a comma by default.


1 Answers

io.StringIO here is behaving just like a file -- you wrote to it, and now the file pointer is pointing at the end. When you try to read from it after that, there's nothing after the point you wrote, so: no columns to parse.

Instead, just like you would with an ordinary file, seek to the start, and then read:

>>> output = io.StringIO() >>> output.write('x,y\n') 4 >>> output.write('1,2\n') 4 >>> output.seek(0) 0 >>> pd.read_csv(output)    x  y 0  1  2 
like image 50
DSM Avatar answered Sep 20 '22 18:09

DSM