python - 如何根据行过滤

标签 python pandas

我在 pandas 中有一个数据框,其中一列(即“b”列)包含带有 $ 符号的字符串:

import numpy as np 
import pandas as pd 

df = pd.DataFrame({'a': [51, 2,32,99,81], 'b': ['$3', '$4','$-','$0','$23']})

我想过滤数据框,这样我只保留“b”列只返回除零以外的整数并且 $ 符号被丢弃的行。

我想要的输出是:

enter image description here

欢迎任何反馈。

最佳答案

In [64]: df = pd.DataFrame({'a': [51, 2,32,99,81], 'b': ['$3', '$4','$-','$0','$23']})

In [65]: df['b'] = pd.to_numeric(df['b'].str.replace(r'\D+', ''), errors='coerce')

In [67]: df
Out[67]:
    a     b
0  51   3.0
1   2   4.0
2  32   NaN
3  99   0.0
4  81  23.0

In [68]: df = df[df['b'].notnull() & df['b'].ne(0)]

In [69]: df
Out[69]:
    a     b
0  51   3.0
1   2   4.0
4  81  23.0

或者我们可以这样过滤:

In [73]: df = df.query("b == b and b != 0")

In [74]: df
Out[74]:
    a     b
0  51   3.0
1   2   4.0
4  81  23.0

关于python - 如何根据行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46839487/

相关文章:

python - 使用数据框的 Pandas 日期时间转换

python - Mongoengine:如何按嵌入式文档字段对嵌入式文档列表进行排序

python - 失败循环 : asking the user if they wish to continue (Python)

Python 3 动态分配基类

python - 是否有用于事件驱动的 Kafka 消费者的 Python API?

python - 我已经安装了 pycrfsuite 仍然出现导入错误

python - Pandas-通过对列和索引的值求和来合并两个数据帧

python - 通过忽略空值来比较列( Pandas )

python - Pandas 数据框导出到 excel 导致 TypeError

python - 使用 Python 两次溢出列