gpt4 book ai didi

python - 如何将 bool 条件向量应用于数据帧的每一列,例如 : Dataframe[booleanVector, :]

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:30 24 4
gpt4 key购买 nike

令 IX 为某个 bool 向量(或者可以是具有逻辑值的数据帧), df - 相同长度的数据帧。

我想要得到类似df[IX,:]的东西, 即对于数据帧的每一列,获取 IX = true 的元素。

问题:有一些简单的方法吗?

<小时/>

我尝试了:我尝试的方法 1) df[IX] 2) df.loc[IX,:] 似乎不起作用

df = pd.DataFrame(data={ 'Col' : 1. , 'Col2' : 1.1 }, index= ['A', 'B'])
df2 = pd.DataFrame(data={ 'ColDF2' : 2. }, index= ['C', 'D'])
IX = df2>0
IX.index = df.index
print(df)
print(df2)
print(IX)
print(df[IX] )

输出:

   Col  Col2
A 1.0 1.1
B 1.0 1.1
ColDF2
C 2.0
D 2.0
ColDF2
A True
B True
Col Col2
A NaN NaN
B NaN NaN

我想要得到:

   Col  Col2
A 1.0 1.1
B 1.0 1.1

最佳答案

您需要选择条件列,然后使用 boolean indexing 通过 boolean numpy array创建者 values :

IX = df2['ColDF2']>0

print(df[IX.values])
Col Col2
A 1.0 1.1
B 1.0 1.1

print(IX.values)
[ True True]

或者在掩码中创建相同的索引值,就像您的答案一样:

IX = df2['ColDF2'] > 0
IX.index = df.index
print(df[IX])
Col Col2
A 1.0 1.1
B 1.0 1.1

print(IX)
A True
B True
Name: ColDF2, dtype: bool

如果df2只有一列:

IX = df2>0
print (IX)
ColDF2
C True
D True

print(df[IX.values])
Col Col2
A 1.0 1.1
B 1.0 1.1

print (IX.values)
[[ True]
[ True]]

关于python - 如何将 bool 条件向量应用于数据帧的每一列,例如 : Dataframe[booleanVector, :],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46646240/

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