[英]Pandas - Creating a new column based on conditional math done on other columns
[英]Creating new pandas column based on Series conditional
从R
到Python
,我似乎无法根据有条件地检查其他列来弄清楚创建新列的简单情况。
# 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().
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
实现这一目标的Python方法是什么? 非常感谢 :)
尝试这个:
df['z'] = np.where((df.x > 1.0) | (df.y < -1.0), 'outlier', 'normal')
如果要对列执行元素化操作,则无法像这样处理您的列。 使用numpy其中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.