gpt4 book ai didi

python - 如何根据行过滤

转载 作者:太空宇宙 更新时间:2023-11-04 06:48:14 25 4
gpt4 key购买 nike

我在 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/

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