如何从 pandas 系列的 dtype 对象中删除具有非整数值的行?

How to remove rows with non-integer values from pandas series of dtype object?

一个基于糖果调查的数据框有一个调查对象的年龄列。目前,该列的数据类型是对象。此列中的一些值是整数,一些是字符串(例如 50+,对于这个来说太旧了)。如何删除有字符串的行?我尝试过的大多数解决方案都没有奏效或仅适用于整个数据帧。

如下面的代码所示,我尝试使用不等式,将列转换为 int 并删除空值,并仅保留具有特定子集中的值的行。

df = df[(df['Age'] >= 3) & (df['Age'] <= 100)]

df = df[pd.to_numeric(df.Age, errors='coerce').notnull()]
df = df.dropna(subset = ['Age'])

df = df.convert_objects(convert_numeric=True).dropna()

a=[]
for i in range(2,101):
    a.append(i)
df = df[~df.Age.isin(a)]

我通常会收到“'>='在 'str' 和 'int' 的实例之间不受支持”或未更改的数据帧。

试试这个:

mport pandas as pd

df=pd.DataFrame({"age": ["45", "50+", "34 ", "34 years", "too old"], "xyz":[1,4,7,3,6]})
print(df)
df.drop(df.index[df["age"].apply(lambda x: not (x.strip().isnumeric()))], axis=0, inplace=True)

print(df)

输出:

age  xyz
0        45    1
1       50+    4
2       34     7
3  34 years    3
4   too old    6


   age  xyz
0   45    1
2  34     7

[Program finished]