1

I have code like this with many columns. The first piece of this code is meant to hard-wire the column order for the final result, as the appended dataframe may have a different order.

pd.DataFrame(columns=['foo', 'bar', 'ddd', 'ccc', 'bbb']).append(pd.DataFrame(data)) 

With newer versions of pandas I cannot use sort while being backwards compatible to run on e.g. google colab which uses an older version of pandas.

How do I maintain the column order specified above, when appending?

This is not a question about this warning which is elsewhere debated in many places:

FutureWarning: Sorting because non-concatenation axis is not aligned. A future version of pandas will change to not sort by default.

To accept the future behavior, pass 'sort=True'.

It's a question about how to maintain the column order while being backward compatible to older versions of pandas.

2
  • 1
    What is data? A dictionary? Commented Dec 29, 2018 at 11:17
  • Yes. Apologies for not mentioning. Commented Dec 29, 2018 at 11:18

1 Answer 1

3

For backward compatibility, I would suggest a reindex step before appending.

df = pd.DataFrame(columns=['foo', 'bar', 'ddd', 'ccc', 'bbb'])

df.append(pd.DataFrame(data).reindex(columns=df.columns))
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.