gpt4 book ai didi

pandas - 使用 loc 的 bool 索引返回 NaN

转载 作者:行者123 更新时间:2023-12-04 07:23:10 27 4
gpt4 key购买 nike

import pandas as pd
numbers = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

df = pd.DataFrame(numbers)
condition = df.loc[:, 1:2] < 4
df[condition]
    0   1   2
0 NaN 2.0 3.0
1 NaN NaN NaN
2 NaN NaN NaN

为什么我会得到这些错误的结果,我该怎么做才能得到正确的结果?

最佳答案

bool 条件必须是 Series,但这里您选择的列返回 DataFrame:

print (condition)
1 2
0 True True
1 False False
2 False False

因此,要将 bool 数据框转换为掩码,请使用 DataFrame.all用于测试每行是否所有 TrueDataFrame.any如果每行至少有一个 True:

print (condition.any(axis=1))
print (condition.all(axis=1))
0 True
1 False
2 False
dtype: bool

或者只选择一列作为条件:

print (df.loc[:, 1] < 4)
0 True
1 False
2 False
Name: 1, dtype: bool

print (df[condition.any(axis=1)])
0 1 2
0 1 2 3

关于pandas - 使用 loc 的 bool 索引返回 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68374993/

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