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

237
Views
Compruebe si el valor de la columna está en otras columnas en pandas

Tengo el siguiente marco de datos en pandas

 target ABC 0 cat bridge cat brush 1 brush dog cat shoe 2 bridge cat shoe bridge

¿Cómo pruebo si df.target está en alguna de las columnas ['A','B','C', etc.] , donde hay muchas columnas para verificar?

He intentado fusionar A, B y C en una cadena para usar df.abcstring.str.contains(df.target) pero esto no funciona.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Puede usar drop , isin y any .

  • drop la columna de target para tener un df con sus columnas A , B , C solamente
  • compruebe si los valores isin en la columna de destino
  • y verifique si any resultado presente

Eso es todo.

 df["exists"] = df.drop("target", 1).isin(df["target"]).any(1) print(df) target ABC exists 0 cat bridge cat brush True 1 brush dog cat shoe False 2 bridge cat shoe bridge True
over 4 years ago · Santiago Trujillo Report

0

Enfoque OneHotEncoder:

 In [165]: x = pd.get_dummies(df.drop('target',1), prefix='', prefix_sep='') In [166]: x Out[166]: bridge cat dog cat shoe bridge brush shoe 0 1 0 0 1 0 0 1 0 1 0 0 1 1 0 0 0 1 2 0 1 0 0 1 1 0 0 In [167]: x[df['target']].eq(1).any(1) Out[167]: 0 True 1 True 2 True dtype: bool

Explicación:

 In [168]: x[df['target']] Out[168]: cat cat brush bridge bridge 0 0 1 1 1 0 1 0 1 0 0 0 2 1 0 0 0 1
over 4 years ago · Santiago Trujillo Report

0

Otro enfoque utilizando el método de diferencia de índice:

 matches = df[df.columns.difference(['target'])].eq(df['target'], axis = 0) # ABC #0 False True False #1 False False False #2 False False True # Check if at least one match: matches.any(axis = 1) #Out[30]: #0 True #1 False #2 True

En caso de que quisiera ver qué columnas cumplen con el objetivo, aquí hay una posible solución:

 matches.apply(lambda x: ", ".join(x.index[np.where(x.tolist())]), axis = 1) Out[53]: 0 B 1 2 C dtype: object
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!