2017-06-23 178 views
2

来自RPython我似乎无法弄清楚创建新列的一个简单情况,基于有条件地检查其他列。根据系列条件创建新的熊猫列

# In R, create a 'z' column based on values in x and y columns 
df <- data.frame(x=rnorm(100),y=rnorm(100)) 
df$z <- ifelse(df$x > 1.0 | df$y < -1.0, 'outlier', 'normal') 
table(df$z) 
# output below 
normal outlier 
    66  34 

尝试在Python中相当于声明:

import numpy as np 
import pandas as pd 
df = pd.DataFrame({'x': np.random.standard_normal(100), 'y': np.random.standard_normal(100)}) 
df['z'] = 'outlier' if df.x > 1.0 or df.y < -1.0 else 'normal' 

但是,下面的异常被抛出: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

什么是实现这一目标的Python的方式?非常感谢:)

回答

3

试试这个:

df['z'] = np.where((df.x > 1.0) | (df.y < -1.0), 'outlier', 'normal') 
1

如果你想要做列的elementwise操作不能ADRESS你列这样。使用numpy where