簡體   English   中英

從數字值列中減去並將結果限制為零?

[英]Subtracting from a number value column and limiting the result to zero?

我正在嘗試查看是否可以從col減去一個數字,但是如果在減法后該數字為負數以將輸出限制為0,則不小於或為負。

對於前。 DF中的col看起來像

Mins | new_col
 5.0    2.0
 1.0    0.0
 2.0    0.0
 0.5    0.0
 1.2    0.0
 4.0    1.0

如果我想創建一個新列,該列為我提供相同的值,但從該列中的每個值中減去3。

您可以減去,然后使用以下方式clip

df['new_col'] = np.clip(df['Mins']-3, 0, None)
#alternative df['new_col'] = np.clip(df['Mins'].sub(3), 0, None)

這解決了..使用np.where

df['new_col'] = np.where(df['Mins']-3 > 0, df['Mins']-3, 0)

產量

   Mins  new_col
0   5.0      2.0
1   1.0      0.0
2   2.0      0.0
3   0.5      0.0
4   1.2      0.0
5   4.0      1.0

您可以使用pandas.Series.clip

df['new_col'] = df['Mins'].sub(3).clip(0)

可以通過簡單的for循環來解決。 將輸入值存儲在列表list1

list2=[] for value in list1: sub=value-3.0 if sub <= 0: list2.append(0.0) else: list2.append(sub) print list2

暫無
暫無

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

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