Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

92
Vistas
How to re-order the columns based on another dataframe with the same columns but different order

I wonder if there is a handy method to order the columns of a dataframe based on another one that has the same columns but with different order. Or, do I have to make a loop to achieve this?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Try this:

df2 = df2[df1.columns]

Demo:

In [1]: df1 = pd.DataFrame(np.random.randint(0, 10, (5,4)), columns=list('abcd'))

In [2]: df2 = pd.DataFrame(np.random.randint(0, 10, (5,4)), columns=list('badc'))

In [3]: df1
Out[3]:
   a  b  c  d
0  8  3  9  6
1  0  6  4  7
2  7  2  0  7
3  0  5  1  8
4  6  2  5  4

In [4]: df2
Out[4]:
   b  a  d  c
0  3  8  0  4
1  7  7  4  2
2  2  7  3  8
3  2  4  9  6
4  3  4  7  1

In [5]: df2 = df2[df1.columns]

In [6]: df2
Out[6]:
   a  b  c  d
0  8  3  4  0
1  7  7  2  4
2  7  2  8  3
3  4  2  6  9
4  4  3  1  7

Alternative solution:

df2 = df2.reindex_axis(df1.columns, axis=1)

Note: Pandas reindex_axis is deprecated since version 0.21.0: Use reindex instead.

df2 = df2.reindex(df1.columns, axis=1)
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda