Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas CSV output only the data in a certain row (to_csv)

Tags:

python

pandas

I need to output only a particular row from a pandas dataframe to a CSV file. In other words, the output needs to have only the data in row X, in a single line separated by commas, and nothing else. The problem I am running into with to_CSV is that I cannot find a way to do just the data; I am always receiving an extra line with a column count.

data.to_csv(filename, index=False)

gives

0,1,2,3,4,5
X,Y,Z,A,B,C

The first line is just a column count and is part of the dataframe, not the data. I need just the data. Is there any way to do this simply, or do I need to break out of pandas and manipulate the data further in python?

Note: the preceding example has only 1 row of data, but it would be nice to have the syntax for choosing row too.

like image 863
Elliot Avatar asked Oct 27 '25 18:10

Elliot


2 Answers

You can try this:

df = pd.DataFrame({'A': ['a','b','c','d','e','f'], 'B': [1,2,3,4,5,6]})
   A  B
0  a  1
1  b  2
2  c  3
3  d  4
4  e  5
5  f  6

You can select the row you want, in this case, I select the row at index 1:

df.iloc[1:2].to_csv('test.csv', index=False, header=False)

The output to the csv file looks like this (makes sure you use header=False):

b  2
like image 76
Joe T. Boka Avatar answered Oct 30 '25 07:10

Joe T. Boka


You can use this

data.to_csv(filename, index=False, header=False)

the header means:

header : boolean or list of string, default True Write out column names. If a list of string is given it is assumed to be aliases for the column names

you can find more specific info in pandas.DataFrame.to_csv

like image 43
GeorgeCaoJ Avatar answered Oct 30 '25 09:10

GeorgeCaoJ