【问题标题】:Index a DataFrame using two conditions使用两个条件索引 DataFrame
【发布时间】:2015-02-04 21:56:20
【问题描述】:

我正在尝试根据两个条件获取 DataFrame 的子集。

这是我的简化示例:

import pandas as pd
test = pd.DataFrame(np.ones(48),
                    index=pd.date_range('2015-01-01',
                    periods=48, 
                    freq='1800S'))

我现在想获取时间范围 t > 08:00 和 t

result = test[test.index.hour>8 & test.index.hour<22]

然后我得到ValueError that the truth value of an array with more than one element is ambiguous, use a.any() or a.all() - 我运气不好......

【问题讨论】:

    标签: python pandas datetime dataframe


    【解决方案1】:

    有两个简单的解决方案:

    • 首先:将条件括在大括号中,例如 (test.index.hour &gt; 8) &amp; (test.index.hour&lt;22) 由于运算符和优先级
    • 第二:使用the query function

    【讨论】:

    • 好吧,他们改变了查询函数中的优先级告诉我,我不是唯一一个在这个(相当简单的)问题上苦苦挣扎的人......至少给我的灵魂一点平静:)
    【解决方案2】:

    在使用元素方面的 &amp; 之前,您需要在两个数组周围加上括号:

    (test.index.hour > 8) & (test.index.hour < 22)
    

    &amp; 运算符比该表达式中的比较运算符具有higher precedence,这会导致问题。

    【讨论】:

    • 谢谢,这个答案太明显了,好痛……我看不到森林的树木...... .
    • 没问题 - 这些东西很容易被忽略。
    猜你喜欢
    • 2021-07-14
    • 2020-05-03
    • 2023-04-01
    • 1970-01-01
    • 2023-04-06
    • 2023-02-07
    • 2019-01-11
    • 2015-04-09
    • 1970-01-01
    相关资源
    最近更新 更多