簡體   English   中英

內聯if語句條件pandas為新列賦值

[英]Inline if statement conditional pandas assign value to new column

我正在嘗試使用pandas assign有條件地為列分配值。

我嘗試使用pandas assign來創建一個新列,如果列sv_length指定的長度值> = 50,則將其標記為SV,如果長度<50則使用InDel。

df3=df2.assign(InDel_SV='InDel' if df2.sv_length < 50 else 'SV')

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

其他示例使用np.where。 為什么我要使用numpy? 這個簡單的功能不應該成為熊貓的一部分嗎?

https://chrisalbon.com/python/data_wrangling/pandas_create_column_using_conditional/

通過使用apply支持此語法。

df3 = df2.assign(
    InDel_SV=df2.sv_length.apply(lambda x: 'InDel' if x < 50 else 'SV'))

但是,為了提高性能,建議您使用numpy,因為apply是一個緩慢的便利功能 這樣做的pandaic方式是使用numpy.where

df3 = df2.assign(InDel_SV=np.where(df2.sv_length < 50, 'InDel', 'SV'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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