我构建以下玩具代码来说明我的问题。
我有一些重量,需要选择具体的组合。这可以是一个权重=1(如在掩码1中),或者应用某些权重组合(mask2)。但是,掩码2不知何故不起作用(至少在第二部分)。
举例说明:由于mask1
,只有特定列中权重为1的行应该保留。
但是,输出也给我一些行,比如第1行,这些行不应该存在,因为sumABCD
总是1(见下文)
import numpy as np
import pandas as pd
# random dataframe:
np.random.seed(seed=1)
df = pd.DataFrame(np.random.randint(0,5000,size=(2000, 4)), columns=list('ABCD'))
columns = list(df.columns)
for col in columns: # round up at certain threshold, to simulate weightings of 1
other_columns = [x for x in columns if not x == col]
df.loc[df[col] > 4700, col] = 5000
df.loc[df[col] == 5000, other_columns] = 0
# calculate weights:
df[list(df.columns)] = df.div(df[["A", "B", "C", "D"]].sum(axis=1), axis="index")
df["sumABCD"] = df[["A", "B", "C", "D"]].sum(axis=1)
# filter
mask1 = ((df[["A", "B", "C", "D"]] == 1).any(axis=1))
for x in [0, 0.10]:
mask2 = ((df["B"] <= x) & (df["sumABCD"] < 1.0))
test = df[mask1 | mask2]
print(test.head(20))
A B C D sumABCD
1 0.287745 0.014313 0.419938 0.278004 1.0
3 0.000000 0.000000 0.000000 1.000000 1.0
8 0.000000 0.000000 1.000000 0.000000 1.0
12 1.000000 0.000000 0.000000 0.000000 1.0
编辑:
至于您在
row 1
问题上更新的问题,请尝试对您的数据运行下面的命令它在
sumABCD
列上切片<;1.0. 第1行实际上不是1.0
。它的值几乎是1.0
,四舍五入到1.0
。由于float
在计算机系统中是数字的表示形式,因此无法保证算术运算的精度sumABCD
是每列上的除法之和。这些除法造成精度损失,所以求和只能回到almost 1.0
如果您想了解更多关于
float
的信息,请阅读以下文档https://docs.python.org/3/tutorial/floatingpoint.htmlIIUC,在您的示例代码中,您认为应该得到空的数据帧,但事实并非如此
在这之后
mask2
总是False
,因为(df["sumABCD"] < 1.0)
总是False
但是,在
|
操作符上对df
进行切片,如中所示所以,
mask2
所有False
都不会影响结果。当mask2
全部False
时,结果取决于mask1
。这就是'|'
运算符的性质。因此test
将取决于mask1
的True/False
。这就是test
不是您期望的空数据帧的原因相关问题 更多 >
编程相关推荐