Home > database >  How to drop records containing cell values equals to the header in pandas
How to drop records containing cell values equals to the header in pandas

Time:04-06

I have read in this dataframe (called df):

enter image description here

As you can see there is a record that contains the same values as the header (ltv and age).

How do I drop that record in pandas?

Data:

df = pd.DataFrame({'ltv':[34.56, 50, 'ltv', 12.3], 'age':[45,56,'age',45]})

CodePudding user response:

Check with

out = df[~df.eq(df.columns).any(1)]
Out[203]: 
     ltv age
0  34.56  45
1     50  56
3   12.3  45

CodePudding user response:

One way is to just filter it out (assuming the strings match the column name they are in):

out = df[df['ltv']!='ltv']

Another could be to use to_numeric dropna:

out = df.apply(pd.to_numeric, errors='coerce').dropna()

Output:

     ltv age
0  34.56  45
1     50  56
3   12.3  45
  • Related