Reputation: 13736
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.
Upvotes: 1
Views: 894
Reputation: 403030
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))
Upvotes: 3