将列中的0替换为python中另一列中显示的产品数

时间:2017-08-28 12:11:12

标签: python pandas

美好的一天

我有一个如下所示的数据框:

df: 
ID  |   Types of product    | Number of product
----|-----------------------|-------------------
1   | NDA,0D002             |                 2
2   | CALL'NA               |                 0
3   | MMCDP,PRCP,0D002      |                 3
4   | C0D002,CALL'NA        |                 1
5   | CALL'NA,NDA,HLA       |                 2
6   | CALL'NA               |                 0
7   | CALL'NA               |                 0
8   | 0D23, CALL'NA         |                 1
9   | SA,CALL'NA            |                 0
10  | IS,SA,CALL'NA,0D003   |                 1

我的df['Types of Products']包含的数据包含不同类型的产品,然后列df['Number of Products']会选择有多少种类型的产品并对其进行计数,但随后您会发现零条目在df['Number of Products']列中。 请帮我写一个有助于计算正确数量的产品的代码。

我写了下面的代码用1代替所有的零,但我怀疑它是正确的。请帮忙。

def product_value(df):
ProductNumber = df['NUMBER_OF_PRODUCTS'].astype(int)
NUMBER_OF_PRODUCTS = pd.Series(0)
for i in range(df.shape[0]):
    if  NUMBER_OF_PRODUCTS[i]==0:
        ProductNumber[i] = 1
return ProductNumber

1 个答案:

答案 0 :(得分:1)

对于具有相同尺寸的新Series,您似乎首先需要transform,然后替换0值:

new=df.groupby('Types of product')['Types of product'].transform('size')
df['Number of product'] = df['Number of product'].mask(df['Number of product'] == 0, new)
print (df)
   ID     Types of product  Number of product
0   1            NDA,0D002                  2
1   2              CALL'NA                  3
2   3     MMCDP,PRCP,0D002                  3
3   4       C0D002,CALL'NA                  1
4   5      CALL'NA,NDA,HLA                  2
5   6              CALL'NA                  3
6   7              CALL'NA                  3
7   8        0D23, CALL'NA                  1
8   9           SA,CALL'NA                  1
9  10  IS,SA,CALL'NA,0D003                  1

类似的解决方案:

df.loc[df['Number of product'] == 0, 'Number of product'] = new
print (df)
   ID     Types of product  Number of product
0   1            NDA,0D002                  2
1   2              CALL'NA                  3
2   3     MMCDP,PRCP,0D002                  3
3   4       C0D002,CALL'NA                  1
4   5      CALL'NA,NDA,HLA                  2
5   6              CALL'NA                  3
6   7              CALL'NA                  3
7   8        0D23, CALL'NA                  1
8   9           SA,CALL'NA                  1
9  10  IS,SA,CALL'NA,0D003                  1