Python Pandas - Change Order of DataFrame Columns & Rows

preview_player
Показать описание
In this Python Pandas programming tutorial we will go over how to change the order of your DataFrame columns and/or rows using reindex. You can also use reindex to add/change columns/rows.
Рекомендации по теме
Комментарии
Автор

Esto es todo lo que necesitaba, gracias

cesarhernandezr
Автор

I think I mention in a previous tutorial how to reorder or maintain column order however just in case I did not, the code below shows an example. Basically, you can specify your column labels and add them into the DataFrame to maintain the desired order (or to reorder).

import pandas

# df1 column order may not be what is expected/desired but is fixed in df2
df1 = pandas.DataFrame({'State': ['Indiana', 'Massachusetts', 'Illinois'],
'Capital': ['Indianapolis', 'Boston', 'Springfield'],
'Population': [6_600_000, 6_800_000, 12_800_000],
'Sports_Teams': ['Pacers', 'Celtics', 'Bulls']
})

# add in index/row labels
# add in column labels (this should reorder and maintain display order)
index_labels=list('abc')
columns_labels = ['State', 'Capital', 'Population', 'Sports_Teams']
df2 = pandas.DataFrame({'State': ['Indiana', 'Massachusetts', 'Illinois'],
'Capital': ['Indianapolis', 'Boston', 'Springfield'],
'Population': [6_600_000, 6_800_000, 12_800_000],
'Sports_Teams': ['Pacers', 'Celtics', 'Bulls']
}, index=index_labels, columns=columns_labels)

RyanNoonan
welcome to shbcf.ru