Convert Django QuerySet to Pandas Dataframe and Maintain Column Order Convert Django QuerySet to Pandas Dataframe and Maintain Column Order pandas pandas

Convert Django QuerySet to Pandas Dataframe and Maintain Column Order


qs.values() converts the QuerySet into a dictionary, which is unordered. You are OK with qs.values_list(), which returns a list of tuples.

Try:

df = pd.DataFrame.from_records(    A.objects.all().values_list('A', 'B', 'C', 'D', 'E', 'F'))

check the docs about Django's QuerySets


try:

df = pd.DataFrame.from_records("DATA_GOES_HERE", columns=['A','B','C'.. etc.) 

I'm using the columns= parameter found here.

I believe you could also construct the DataFrame by just using pd.DataFrame and put your lists in there with the corresponding column names. This may be more manual work up-front, but if this is for an automated job it could work as well. (may have the ordering issue here again, but can easily be solved by rearranging the columns.. Again, may be more work upfront)