1

Wondering how to specify a first column using pandas?

For example, I have a dataframe df with variables var1, var2, var3,...varx, I would like the first column to be var3 in the csv generated.

df.to_csv('location/export.csv', index=False)

2
  • 1
    Does this answer your question? Set order of columns in pandas dataframe Commented Nov 21, 2019 at 20:24
  • Would the resulting ordering be [var3, var1, var2, var4,..., varX] or [var3, var4 ... varX, var1, var2] Commented Nov 21, 2019 at 20:24

1 Answer 1

4

You can rearrange the columns in any way you want by doing

df[['var3', 'var1', 'var2', ..., 'varx']].to_csv('location/export.csv', index=False)

If you just want to have var3 in the beginning, there's a less manual way in

cols = df.columns.tolist()
cols.remove('var3')
df[['var3'] + cols].to_csv('location/export.csv', index=False)
Sign up to request clarification or add additional context in comments.

2 Comments

Yes!!! Thanks - I have a long list of variables and really just care about the first column.
@AnneHsiao Be sure to accept this answer if it solved the problem. Welcome to SO!

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.