【问题标题】:Pandas - list of numerous conditions, with logical operator, used with 'select' statementPandas - 众多条件列表,带有逻辑运算符,与“选择”语句一起使用
【发布时间】:2020-03-30 13:17:51
【问题描述】:

我收到以下错误:

ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()

似乎找不到解决方案。

请帮忙。

import numpy as np
import pandas as pd


t = np.arange(0,100,1); t = pd.Series(t)
y = np.random.randint(1,20,100); y = pd.Series(y)

df = pd.DataFrame({'t': t,'y': y})
mean = np.mean(df['y'])
st_dev = np.std(df.y)

conds = [(df['y'].values > mean + 3*st_dev), (df['y'].values < mean - 3*st_dev),
         (df['y'].values <= (mean + 3*st_dev) and (mean - 3*st_dev) <= df['y'].values )]
choices = [1,0,2]

【问题讨论】:

    标签: python pandas conditional-statements


    【解决方案1】:

    问题是 and 使用标量,这里需要 &amp; 用于按位 AND 并且还需要添加 () 因为优先运算符:

    conds = [(df['y'].values > mean + 3*st_dev), (df['y'].values < mean - 3*st_dev),
             (df['y'].values <= (mean + 3*st_dev)) & ((mean - 3*st_dev) <= df['y'].values )]
    choices = [1,0,2]
    
    df['new'] = np.select(conds, choices)
    print (df)
         t   y  new
    0    0   4    2
    1    1   2    2
    2    2  13    2
    3    3   8    2
    4    4  14    2
    ..  ..  ..  ...
    95  95   5    2
    96  96  10    2
    97  97   8    2
    98  98   6    2
    99  99  16    2
    
    [100 rows x 3 columns]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-04
      • 1970-01-01
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      相关资源
      最近更新 更多