python - 在 pandas python 列中获取非数字行

标签 python pandas

我查看了这篇文章:finding non-numeric rows in dataframe in pandas? 但它并没有真正回答我的问题。

我的示例数据:

import pandas as pd


d = {
 'unit': ['UD', 'UD', 'UD', 'UD', 'UD','UD'],
 'N-D': [ 'Q1', 'Q2', 'Q3', 'Q4','Q5','Q6'],
 'num' : [ -1.48, 1.7, -6.18, 0.25, 'sum(d)', 0.25]

}
df = pd.DataFrame(d)

看起来像这样:

  N-D   num   unit
0  Q1  -1.48   UD
1  Q2   1.70   UD
2  Q3  -6.18   UD
3  Q4   0.25   UD
4  Q5   sum(d) UD
5  Q6   0.25   UD

我只想过滤掉“num”列中非数字的行。我希望所有列仅包含列“num”的非数字值的行。

期望的输出:

  N-D   num   unit
4  Q5   sum(d) UD

我的尝试:

nonnumeric=df[~df.applymap(np.isreal).all(1)] #didn't work, it pulled out everything, besides i want the condition to check only column 'num'. 

nonnumeric=df['num'][~df.applymap(np.isreal).all(1)] #didn't work, it pulled out all the rows for column 'num' only.

最佳答案

使用boolean indexing带有由 to_numeric 创建的掩码+ isnull
注意:此解决方案不会查找或过滤保存为字符串的数字:如“1”或“22”

print (pd.to_numeric(df['num'], errors='coerce'))
0   -1.48
1    1.70
2   -6.18
3    0.25
4     NaN
5    0.25
Name: num, dtype: float64

print (pd.to_numeric(df['num'], errors='coerce').isnull())
0    False
1    False
2    False
3    False
4     True
5    False
Name: num, dtype: bool

print (df[pd.to_numeric(df['num'], errors='coerce').isnull()])
  N-D     num unit
4  Q5  sum(d)   UD

另一种使用isinstanceapply 的解决方案:

print (df[df['num'].apply(lambda x: isinstance(x, str))])
  N-D     num unit
4  Q5  sum(d)   UD

关于python - 在 pandas python 列中获取非数字行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44140489/

相关文章:

python - 在 Windows 上安装 python 库 cffi

python - SQLAlchemy 一对一关系

python - 从 Pandas 时间戳转换时区

python - 替换 pandas 系列中的值,其中要替换的元素包含要替换的元素的一部分

python - 在函数 : Wrong handling indentation/bad-continuation. 中使用列表作为参数的 Pylint 错误无法找出原因

python - 如何在Python国际象棋中获得白棋的获胜机会

python - 生产者/消费者 : Should i write condition. release() 给消费者?

python - Pandas:合并数据帧并将多个连接值合并到一个数组中

python - Pandas 结合两个分组依据,过滤并合并分组(计数)

python - Nltk:从列表列表中消除停用词