0

I was using code from this site (Pandas CSV output only the data in a certain row (to_csv)) to write a dataframe row to a csv row:

df.iloc[-1].to_csv('output.csv', mode='a', index=False, header=False)

but the result is

1
2
3
4
5

instead of

1, 2, 3, 4, 5

What is wrong here?

I want to make this work with df.to_csv and I've tried a few options. I know I could use different code such as with open(...) but the open() function conflicts with another list variable that I cannot change.

1
  • try df.iloc[:-1]. what is output? Commented Feb 23, 2023 at 18:35

2 Answers 2

0

in your solution, you are getting pd.Series so you cant get the desired result. But the below solution will return you a pd.DataFrame row, so i think you can get what you want.

df.iloc[-1:].to_csv('output.csv', mode='a', index=False, header=False)
Sign up to request clarification or add additional context in comments.

1 Comment

Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach?
0

df.iloc[-1] gives you a pd.Series whose separate value is analogues to pd.DataFrame row with a single column, and that's how it's exported into your output csv (each value on a separate line).
To get the expected result you need to transform your Series into a DataFrame with one record/row and that's could be achieved in 2 ways:

  • "long" way: pd.DataFrame(columns=df.iloc[-1].index, data=[df.iloc[-1]]).to_csv('output.csv', mode='a', header=False, index=False)

  • short way: df.iloc[-1].to_frame().T.to_csv('output.csv', mode='a', header=False, index=False)

Comments

Your Answer

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