尝试使用 python pandas 删除列中没有数值的所有行

问题描述 投票:0回答:4
       age    
0       55
1       45
2       58
4      N/A

我需要删除上面给定数据帧示例中列年龄中不包含数值的所有行

预期输出如下

       age
0       55
1       45
2       58
python pandas dataframe
4个回答
1
投票

试试这个

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) 

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

希望对您有帮助。

dropna()
方法删除具有na值的行


0
投票

使用

pd.numeric
作为布尔掩码:

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

# Output
  age
0  55
1  45
2  58

所有非数值都将转换为

NaN


0
投票

最短的解决方案是使用

_convert(numeric=True)

df['age'] = df['age']._convert(numeric=True)
df.dropna(inplace=True)
© www.soinside.com 2019 - 2024. All rights reserved.