簡體   English   中英

根據系列條件創建新的熊貓列

[英]Creating new pandas column based on Series conditional

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(). 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM