age
0 55
1 45
2 58
4 N/A
我需要删除上面给定数据帧示例中列年龄中不包含数值的所有行
预期输出如下
age
0 55
1 45
2 58
试试这个
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)
使用
pd.numeric
作为布尔掩码:
df = df.loc[pd.to_numeric(df['age'], errors='coerce').notna()]
print(df)
# Output
age
0 55
1 45
2 58
所有非数值都将转换为
NaN
。
最短的解决方案是使用
_convert(numeric=True)
:
df['age'] = df['age']._convert(numeric=True)
df.dropna(inplace=True)