如何过滤数据帧中一列中包含整数的行

2024-05-14 08:28:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python和熊猫还不太熟悉,我在这方面有点挣扎。在

我有一组具有Age列类型为float64的数据集。有些值有小数部分,有些没有。我想删除所有具有Age整数值的行。在

这是我的尝试:

estimatedAges = train[int(train['Age']) < train['Age']]

但我有个错误:

TypeError Traceback (most recent call last) in () 1 #estimatedAges = train[train['Age'] > 1] ----> 2 estimatedAges = train[int(train['Age']) < train['Age']] 3 estimatedAges.info()

C:\Anaconda3\lib\site-packages\pandas\core\series.py in wrapper(self) 76 return converter(self.iloc[0]) 77 raise TypeError("cannot convert the series to " ---> 78 "{0}".format(str(converter))) 79 80 return wrapper

TypeError: cannot convert the series to <class 'int'`>

所以,看起来int()不适用于序列数据,我将不得不找到另一种方法,我只是不确定另一种方法是什么。在


Tags: the数据inselfconvertagereturntrain
3条回答

我最终接受了@jezreal的答案,因为他的速度测试令人信服,但我想再添加一个我找到的解决方案。它需要纽姆,但如果你有进口熊猫,那么你很可能也有进口纽姆。在

import numpy as np
train[np.floor(train['Age']) != train['Age']]

试试这个:

In [179]: train[train.Age != train.Age // 1]
Out[179]:
   Age
2  3.4

我想您可以使用^{}来转换为int

estimatedAges = train[train['Age'].astype(int) < train['Age']]

样品:

^{pr2}$

计时

train = pd.DataFrame({'Age':[1,2,3.4]})
train = pd.concat([train]*10000).reset_index(drop=True)

In [62]: %timeit (train[train['Age'].astype(int) < train['Age']])
The slowest run took 6.59 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 544 µs per loop

In [63]: %timeit (train[train['Age'].apply(int) < train['Age']])
100 loops, best of 3: 11.1 ms per loop

In [64]: %timeit (train[train.Age > train.Age.round(0)])
1000 loops, best of 3: 1.55 ms per loop

ajcr的评论编辑,谢谢:

如果值为负浮点和正浮点,则使用:

train = pd.DataFrame({'Age':[1,-2.8,3.9]})
print (train)
   Age
0  1.0
1 -2.8
2  3.9

print (train[train['Age'].astype(int) != train['Age']])
   Age
1 -2.8
2  3.9

相关问题 更多 >

    热门问题