Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
Seleccione ciertas filas por índice de otro DataFrame

Tengo un DataFrame y seleccionaría solo filas que contienen valor de índice en df1.index.

por ejemplo:

 In [96]: df Out[96]: ABCD 1 1 4 9 1 2 4 5 0 2 3 5 5 1 0 22 1 3 9 6

y estos índices

 In[96]:df1.index Out[96]: Int64Index([ 1, 3, 4, 5, 6, 7, 22, 28, 29, 32,], dtype='int64', length=253)

Me gustaría esta salida:

 In [96]: df Out[96]: ABCD 1 1 4 9 1 3 5 5 1 0 22 1 3 9 6
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Usar isin :

 df = df[df.index.isin(df1.index)]

O obtenga todos los índices intersectados y seleccione por loc :

 df = df.loc[df.index & df1.index] df = df.loc[np.intersect1d(df.index, df1.index)] df = df.loc[df.index.intersection(df1.index)]

 print (df) ABCD 1 1 4 9 1 3 5 5 1 0 22 1 3 9 6

EDITAR:

Probé la solución: df = df.loc[df1.index]. ¿Crees que esta solución es correcta?

La solución es incorrecta:

 df = df.loc[df1.index] print (df) ABCD 1 1.0 4.0 9.0 1.0 3 5.0 5.0 1.0 0.0 4 NaN NaN NaN NaN 5 NaN NaN NaN NaN 6 NaN NaN NaN NaN 7 NaN NaN NaN NaN 22 1.0 3.0 9.0 6.0 28 NaN NaN NaN NaN 29 NaN NaN NaN NaN 32 NaN NaN NaN NaN C:/Dropbox/work-joy/so/_t/t.py:23: FutureWarning: Passing list-likes to .loc or [] with any missing label will raise KeyError in the future, you can use .reindex() as an alternative. See the documentation here: http://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike print (df)
over 4 years ago · Santiago Trujillo Report

0

Pasar el índice al indexador/segmentador de filas de .loc ahora funciona, solo debe asegurarse de especificar las columnas también, es decir:

 df = df.loc[df1.index, :] # works

y no

 df = df.loc[df1.index] # won't work

En mi opinión, esto es más ordenado/coherente con el uso esperado de .loc

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!