Home > Blockchain >  Trying to remove all rows without a numeric value in a column using python pandas
Trying to remove all rows without a numeric value in a column using python pandas

Time:03-24

       age    
0       55
1       45
2       58
4      N/A

i need to remove all the rows that doesn't contain numeric values in column age above given dataframe example

Expected output is given bellow

       age
0       55
1       45
2       58

CodePudding user response:

Try this

import pandas as pd
import numpy as np
data = {
"age": [0, 55, 1,55,4,'N/A',5]

}
df = pd.DataFrame(data)
df=df[df['age'].apply(lambda x: type(x) in [int, np.int64, 
float, np.float64])]

print(df) 

CodePudding user response:

Use pd.numeric as boolean mask:

df = df.loc[pd.to_numeric(df['age'], errors='coerce').notna()]
print(df)

# Output
  age
0  55
1  45
2  58

All non numeric values will be converted as NaN.

CodePudding user response:

import pandas as pd
import numpy as np
data={"Name":["jhon","alex","lisa","maya"],"age":[10,14,np.nan,15]}
df=pd.DataFrame(data)
df.dropna()

Hope it was some help to you. dropna() method drop the rows with na valueCode snippet for refrence

  • Related