0

I have a pandas dataframe, call it df with 2 columns:

 user_id result --------- --------- 12 0 233 1 189 0 

And so forth. Is there an easy way to write this data frame out to a text file (with column headers removed) that just has comma-separated rows, i.e.,

12, 0 233, 1 189, 0 

Thanks.

1
  • Ok, but it's been good fun whilst it lasted Commented Sep 27, 2019 at 23:27

5 Answers 5

3

df.to_csv("path.txt", header = False, sep = ",", index = False)

This will write it to text file.

Sign up to request clarification or add additional context in comments.

Comments

1

use pandas.to_csv function like

df.to_csv("tst.csv") 

Comments

0

Try using the pandas to_csv function.

Comments

0
df.to_csv("Test.csv",header=False) 

2 Comments

This may be the correct answer. However one line of code isn't as valuable without an explanation of why this code works and how. Please add details to your answer.
The code is self explanatory, the OP just looks up pandas to_csv
0
 df = df.T.reset_index().T.reset_index(drop=True) df.drop(df.index[0], inplace=True) df.to_csv('path/to/file/out.csv') 

The other solution(s) is very pythonic by comparison!!!

The top line of code is simply wrangling around the problem there is no reset_column function in pandas (ok?). It's not worth explaining because header=False is cleaner

  • thereafter the drop command will remove a row, by default the axis=0 meaning the first row is deleted. So now the header, or rather what was the header, is being deleted
  • to_csv will automatically write the dataframe as a comma separated format, by default

The top line transforms, resets the new row index (no column reset), transforms back resets the row index and blocks 0,1 becoming a header. It's a bit nuts but it works.

2 Comments

Although this may be a correct answer. One line of code isn't very useful without an explanation of what and how it solves the original question. Please provide details to your answer.
Actually, since you pointed it out, it was originally very buggy! Now it just looks horrible

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.