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

问题描述 投票:0回答:1

基于有关糖果的调查的数据框的一栏列出了调查对象的年龄。当前,此列的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'的实例之间或不改变数据框的情况下不支持“'> ='。

python pandas dataframe series
1个回答
0
投票

尝试一下:

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]
© www.soinside.com 2019 - 2024. All rights reserved.