1

I'm trying to write a pandas dataframe to a CSV file with the associated headers in tact row by row. I've accomplished this using

    new_df = pd.DataFrame(old_df).T

Which appears to produce a format (I think a dict?) where I can then write to a csv file line by line using the following

    with open('new.csv', 'a') as f:
        new_df.to_csv(f)

However in the CSV file I have two new columns both with incremental numbers (1,2,3..) for each row. The second column has the key 'Unnamed: 0' while the first column has no key (i.e. key = '').

I would prefer to not have these headers, I can delete the second on using

del new_df['Unnamed: 0']

but I can't do this for the second as it has no key (del new_df[''] does not work).

Would anyone know either how to delete the first column or a better way to write a dataframe to a csv file row by row..

2
  • Just slice and write: df.iloc[:, 1:].to_csv(...) Commented Sep 7, 2017 at 7:45
  • To be sure, please provide some actual data. What is it you're getting. How do you want it written. Words don't help much. Commented Sep 7, 2017 at 7:45

1 Answer 1

2

It seems you need parameter index=False for not write first column called index (0,1,2...) and header=False for no columns names:

df.to_csv('file', index=False, header=False)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.