Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read CSV file with of data frame with row names in Pandas

Tags:

python

pandas

I have a CSV file (tmp.csv) that looks like this:

        x       y       z
bar     0.55    0.55    0.0
foo     0.3     0.4     0.1
qux     0.0     0.3     5.55

It was created with Pandas this way:

    In [103]: df_dummy 
    Out[103]: 
          x     y     z
    bar  0.55  0.55  0.00
    foo  0.30  0.40  0.10
    qux  0.00  0.30  5.55

   In [104]: df_dummy.to_csv("tmp.csv",sep="\t")   

What I want to do is to read that CSV into the same dataframe representation. I tried this but doesn't give what I want:

In [108]: pd.io.parsers.read_csv("tmp.csv",sep="\t")
Out[108]: 
  Unnamed: 0     x     y     z
0        bar  0.55  0.55  0.00
1        foo  0.30  0.40  0.10
2        qux  0.00  0.30  5.55

What's the right way to do it?

like image 391
pdubois Avatar asked Jan 07 '15 07:01

pdubois


People also ask

How do I read a specific cell from a CSV file in pandas?

for reading a CSV file, call pd. read_csv(file_name, usecols=cols_list) with file_name as the name of the CSV file, delimiter as the delimiter, and cols_list as the list of specific columns to read from the CSV file. Call df[col] with df as the DataFrame from the previous step, and col as the column name to read.

What is the use of Nrows argument in read_csv () method?

nrows : This parameter allows you to control how many rows you want to load from the CSV file. It takes an integer specifying row count. B. skiprows : This parameter allows you to skip rows from the beginning of the file.


1 Answers

You can use index_col parameter:

>>> pd.io.parsers.read_csv("tmp.csv",sep="\t",index_col=0)
        x     y     z
bar  0.55  0.55  0.00
foo  0.30  0.40  0.10
qux  0.00  0.30  5.55
like image 120
Roman Pekar Avatar answered Sep 18 '22 22:09

Roman Pekar