How to invert a column in Python?

Asked

Viewed 1,572 times

1

I would like to know how to invert "First Name, Last Name, Age" to "Age, First Name, Last Name" inserir a descrição da imagem aqui

Follows my code:

    import pandas as pd #Importa a biblioteca "Python Data Analysis"

df = pd.read_excel('Pasta1.xlsx') #Lê o arquivo xlsx

df = df.drop('MiddleInitial', axis = 1) #Remove a coluna "MiddleInitial"
df = df.drop('Gender', axis = 1) #Remove a coluna "Gender"
df.rename(columns = {"Age": "Idade", "GivenName": "Nome", "Surname": "Sobrenome"}, inplace = True) #Altera o nome das colunas
df.head() #lê a linha a cima


dfOrdenado = df.sort_values(by = 'Nome', ascending = True) #Ordena a lista
print(dfOrdenado) #Imprime a Lista

2 answers

3

You can change the order of the columns by passing the list with the columns to the dataframe. In the same way that you can change the order, you can also select fewer columns if there is need.

dfOrdenado[['Idade', 'Nome', 'Sobrenome']]

1

Enter the following code:

dfOrdenado[['Idade','Nome','Sobrenome']]

It will sort by column name

  • This answer is identical to what had already been posted before, there is nothing you want to add to make it more complete or different? Related: https://pt.meta.stackoverflow.com/q/4566/3117

Browser other questions tagged

You are not signed in. Login or sign up in order to post.