将负值更改为0,而不更改其他列

时间:2020-01-14 14:59:05

标签: python pandas data-analysis

我有一个DF,正在其中分析客户的总价。我通过从产品的销售价值中减去折扣(因为它已经是一个负数)而得出了客户支付的总价。

transaction_df_clean['customer_price'] = transaction_df_clean['sales_value'] + transaction_df_clean['coupon_disc']

因此,某些总价格为负数,我想将其更改为0,以避免出现负数。

输入:

transaction_df_clean.loc[transaction_df_clean['customer_price'] < 0].head(10)

输出(显示1行):

index   household_key   basket_id   day product_id  quantity    sales_value store_id    retail_disc trans_time  week_no coupon_disc coupon_match_disc   customer_price
----------
13895   988  27282152470     25  1088634    2   1.00    408 -0.98   2353    4   -1.49   0.00    -0.49

但是,当尝试将“ customer_price”列中的负值更改为0时,其他未定位的列也更改为0。

输入:

transaction_df_clean.loc[transaction_df_clean['customer_price'] < 0] = 0
transaction_df_clean.loc[transaction_df_clean['customer_price'] == 0].head(20)

输出:

index household_key basket_id   day product_id  quantity    sales_value store_id    retail_disc trans_time  week_no coupon_disc coupon_match_disc   customer_price
----------
13895   0   0   0   0   0   0.00    0   0.00    0   0   0.00    0.00    0.0

为什么会发生这种情况?

3 个答案:

答案 0 :(得分:2)

您还需要选择该列。

m = transaction_df_clean['customer_price'] < 0
transaction_df_clean.loc[m,'customer_price']=0

我会使用Series.clip

transaction_df_clean['customer_price'] = transaction_df_clean['customer_price'].clip(lower=0)

我们也可以使用Series.mask

transaction_df_clean['customer_price']=transaction_df_clean['customer_price'].mask(m,0)

因此您需要Series.add + Series.clip

transaction_df_clean['customer_price'] = transaction_df_clean['sales_value'].add(transaction_df_clean['coupon_disc']).clip(lower=0)

答案 1 :(得分:1)

transaction_df_clean.loc[transaction_df_clean['customer_price'] < 0] = 0实际执行的操作是将条件应用于整个数据帧,并且当您放置= 0时,0将广播到所有数据点。您要告诉它选择数据框中customer_price小于0的所有行,然后将所有过滤的行更改为0。

除了应用条件之外,您还必须选择要更改的列/系列。

我记得如何使用.locdf.loc[row filter/selection, column filter/selection]

另一种方法是

transaction_df_clean.loc[transaction_df_clean['customer_price'] < 0,'customer_price'] = 0

文档中有很多关于设置值的部分,称为“ 设置值”。 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html

答案 2 :(得分:0)

您可以使用numpy.max来处理它(pandas也有一个max,但它不太直观,因为它默认是聚合数据而不是按行工作)

import numpy as np 

transaction_df_clean['customer_price'] = np.max(0, transaction_df_clean['sales_value'] + transaction_df_clean['coupon_disc'])

这样,就不会有任何负数