熊猫 - 许多条件的列表,带有逻辑运算符,与“选择”语句一起使用

我收到以下错误:


值错误:具有多个元素的数组的真值是不明确的。使用 a.any() 或 a.全部 ()


似乎找不到解决方案。


请帮忙。


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]


慕姐4208626
浏览 54回答 1
1回答

Smart猫小萌

问题是使用标量,这里对于按位是必要的,也是必要的添加,因为优先级运算符:and&AND()conds = [(df['y'].values > mean + 3*st_dev), (df['y'].values < mean - 3*st_dev),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(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)&nbsp; &nbsp; &nbsp;t&nbsp; &nbsp;y&nbsp; new0&nbsp; &nbsp; 0&nbsp; &nbsp;4&nbsp; &nbsp; 21&nbsp; &nbsp; 1&nbsp; &nbsp;2&nbsp; &nbsp; 22&nbsp; &nbsp; 2&nbsp; 13&nbsp; &nbsp; 23&nbsp; &nbsp; 3&nbsp; &nbsp;8&nbsp; &nbsp; 24&nbsp; &nbsp; 4&nbsp; 14&nbsp; &nbsp; 2..&nbsp; ..&nbsp; ..&nbsp; ...95&nbsp; 95&nbsp; &nbsp;5&nbsp; &nbsp; 296&nbsp; 96&nbsp; 10&nbsp; &nbsp; 297&nbsp; 97&nbsp; &nbsp;8&nbsp; &nbsp; 298&nbsp; 98&nbsp; &nbsp;6&nbsp; &nbsp; 299&nbsp; 99&nbsp; 16&nbsp; &nbsp; 2[100 rows x 3 columns]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python