python - 从数据框中的列中选择特定值

标签 python pandas

我有一个只有两列的数据集。我想根据一列的某些条件从中提取一小部分。将此视为我的数据集。

A    B
1    10
1    9
2    11
3    12
3    11
4    9

假设我只想提取那些在 B 中具有 10 - 12 值的行。所以我会得到一个新的数据集:

A    B
1    10
2    11
3    12
3    11

我尝试使用 df.loc[df["B"] == range(10, 12)] 但它不起作用,有人可以帮我解决这个问题吗?

最佳答案

你可以使用.between

In [1031]: df.loc[df.B.between(10, 12)]
Out[1031]:
   A   B
0  1  10
2  2  11
3  3  12
4  3  11

或者,isin

In [1032]: df.loc[df.B.isin(range(10, 13))]
Out[1032]:
   A   B
0  1  10
2  2  11
3  3  12
4  3  11

或者,查询

In [1033]: df.query('10 <= B <= 12')
Out[1033]:
   A   B
0  1  10
2  2  11
3  3  12
4  3  11

或者,good'ol boolean

In [1034]: df.loc[(df.B >= 10) & (df.B <= 12)]
Out[1034]:
   A   B
0  1  10
2  2  11
3  3  12
4  3  11

关于python - 从数据框中的列中选择特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46011246/

相关文章:

python - 在 Python 中线程化相同的函数以获得不同的结果

python - 如何得到n(n-1)(n-2)/6的结果

python - 如何在 Linux 的窗口中显示交互式 SVG?

python - SQLAlchemy 返回元组而不是字典

python - Python中两个数组所有可能总和的数据框

python - 将随机数写入Python文件并使用换行符连接

python - pandas loc 使用多索引修改 dataFrame?

python - "Merging"具有共同维度的 numpy 数组

python - 如何指定用于绘制数据框的 x 轴和 y 轴

python - 如何在 Python 中使用 factorize() 后获取原始值?