gpt4 book ai didi

Python Pandas 从列中删除非数字行

转载 作者:行者123 更新时间:2023-12-01 04:00:47 24 4
gpt4 key购买 nike

我有一个数据框,想要删除Score列中的非数字行

import pandas as pd

df=pd.DataFrame({
'Score': [4.0,6,'3 1/3',7,'43a'],
'Foo': ['Nis','and stimpy','d','cab','abba'],
'Faggio':[0,1,0,1,0]
})

我想要的结果应该是这样的:

   Faggio         Foo  Score
0 0 Nis 4
1 1 and stimpy 6
3 1 cab 7

我已经尝试过:

ds=df[df['Score'].apply(lambda x: str(x).isnumeric())]

print(ds)

ds2=df[df['Score'].apply(lambda x: str(x).isdigit())]

print(ds2)

但是他们都用 float 删除了该列。

最佳答案

我认为你需要添加isnull用于检查 NaN 值,因为如果不是数字,您的函数将返回 NaN 。更好更快的是使用text method str.isnumeric()str.isdigit()boolean indexing :

print df['Score'].str.isnumeric()
0 NaN
1 NaN
2 False
3 NaN
4 False
Name: Score, dtype: object

print df['Score'].str.isnumeric().isnull()
0 True
1 True
2 False
3 True
4 False
Name: Score, dtype: bool

print df[df['Score'].str.isnumeric().isnull()]
Faggio Foo Score
0 0 Nis 4
1 1 and stimpy 6
3 1 cab 7

print df[df['Score'].str.isdigit().isnull()]
Faggio Foo Score
0 0 Nis 4
1 1 and stimpy 6
3 1 cab 7

to_numeric 类似的解决方案和 notnull :

print df[pd.to_numeric(df['Score'], errors='coerce').notnull()]
Faggio Foo Score
0 0 Nis 4
1 1 and stimpy 6
3 1 cab 7

关于Python Pandas 从列中删除非数字行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36592021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com