[英]How to generate new column with values based on condition in another column in pandas
[英]How to add new column based on the condition of another column in pandas?
我有一個 dataframe,它包含一些變量,例如國家/地區、收入、成本,並且我有一個常數值。
我想根據我定義的某個范圍創建新列,我試過這個:
my_df['flag'] = my_df.apply(lambda row: row.cost - constant < row.revenue < row.cost + constant, 1,0)
它給了我一個結果,但標志列充滿了“假”值。 問題是什么?
使用Series.between
和numpy.where
:
my_df['flag'] = np.where(my_df.revenue.between(my_df.cost - constant,
my_df.cost + constant,
inclusive='neither'), 1, 0)
或者:
my_df['flag'] = my_df.revenue.between(my_df.cost - constant,
my_df.cost + constant,
inclusive='neither').astype(int)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.