来自R
toPython
并且我似乎无法根据有条件地检查其他列来找出创建新列的简单案例。
# 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().
实现这一目标的pythonic方法是什么?非常感谢 :)
试试这个:
df['z'] = np.where((df.x > 1.0) | (df.y < -1.0), 'outlier', 'normal')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句