【问题标题】:How to select certain values based on a condition in a data frame?如何根据数据框中的条件选择某些值?
【发布时间】:2020-10-01 19:29:18
【问题描述】:

我有一个名为 df 的数据框,如下所示:

Date        Reading1 Reading2 Reading3 Reading4
2000-05-01     15        13        14       11
2000-05-02     15        14        18        9
2000-05-03     14        12        15        8
2000-05-04     17        11        16       13

我使用 df.setindex('Date') 将日期设为索引。 我有 3 个问题。

1) 如何在整个数据框中显示读数大于 13 的天数,而不仅仅是在单个列中?

我试过 df.[(df.Reading1:df.Reading4>13)].shape[0] 但显然语法错误。

2) 如何显示 2000-05-03 列读数 1、3 和 4 的值?

我试过 df.loc[["20000503"],["Reading1","Reading3,"Reading4"]]

但我收到错误“索引(['20000503'],dtype='object')] 不在 [index] 中”

3) 如果读数 1 列的值是读数 2 列中值的两倍,我该如何查找?以及如何显示这些值(读数 1 中的两倍大)?

我什至不知道从哪里开始。

【问题讨论】:

    标签: python pandas dataframe indexing shapes


    【解决方案1】:

    试试这个:

    1. (df > 13).any(axis=1).sum()
    Create a boolean dataframe then check to see if any value is True along the row and sum rows to get number of days.
    
    2. df.loc['2000-05-03', ['Reading1', 'Reading3', 'Reading4']]
    Use partial string indexing on DatetimeIndex to get a day, then column filtering with a list of column header.
    
    3. df.loc[df['Reading1']  > (df['Reading2'] * 2)].index
       df.loc[df['Reading1']  > (df['Reading2'] * 2)].to_numpy().tolist()
    Create a boolean series to do boolean indexing and get the index to return date.  Next convert the dataframe to numpy array then tolist to get values.
    

    【讨论】:

    • 第一个不工作说“dtype=datetime64 [ns] 和 int 之间的比较无效
    • 啊.. 将您的日期列移动到索引。使用df=df.set_index('Date') 我假设您的日期列是数据框索引。
    猜你喜欢
    • 2021-08-18
    • 2016-10-17
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多