Elliot
Elliot

Reputation: 5561

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

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.

Upvotes: 4

Views: 15596

Answers (3)

sriramkumar
sriramkumar

Reputation: 164

it seems like you are looking for filtering data from the existing dataframe and write it into .csv file.

for that you need to filter your data . then apply to_csv command.

here is the command

df[df.index.isin([3,4])]

if this is your data

>>> df
   A  B
0  X  1
1  Y  2
2  Z  3
3  A  4
4  B  5
5  C  6

then this would be your expected filtered content. then you can apply to_csv on top of it.

>>> df[df.index.isin([3,4])]
   A  B
3  A  4
4  B  5

Upvotes: 3

Joe T. Boka
Joe T. Boka

Reputation: 6581

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

Upvotes: 5

GeorgeCaoJ
GeorgeCaoJ

Reputation: 46

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

Upvotes: 3

Related Questions