繁体   English   中英

查找两列范围之间的样本

[英]Find samples between ranges of two columns

我是python编程的新手。 我找不到任何编写我这部分代码的方法。 如果有人可以帮助我,我将不胜感激。

我有一个具有3个属性(4000条记录)的数据框。 属性x1,x2,class(Binary)。

首先,我做了一个散点图,意识到x1范围在3到13之间, x2范围在3到8之间。

我想获取某些范围内的数据:例如:

if 2.5< x1 < 3.5 and 3.5< x2 < 4.5 ---> df1

if 3.5 <=x1 < 4.5 and 4.5<=x2 < 5.5 ---> df2

if ....

正如Mstaino指出的那样,布尔掩码是访问一列或多列中一系列值的正确策略。

由于您是python编程的新手(因此还不熟悉pandas),因此将其分为两步很重要。

首先,创建一个布尔掩码,然后创建逻辑掩码。

这是一个可以运行和重新运行的mcve ,以查看如何获取相关的被屏蔽列中的值的采样。

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(200,3),columns=['x1', 'x2', 'Class'])
mask1 = (df.x1 > -.4) & (df.x1 < .6)
mask2 = (df.x2 > -.4) & (df.x2 < .5)

# What do the masks look like in context?
df['mask1'] = mask1
df['mask2'] = mask1
print(df.head())

# apply the boolean masks so ranges in mask1 and mask2 are obtained
df1 = df[mask1 & mask2]

# sample the result
print(df1.sample(n=4))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM