gpt4 book ai didi

python - 用python中另一列中出现的产品数替换一列中的0

转载 作者:太空宇宙 更新时间:2023-11-04 05:00:12 25 4
gpt4 key购买 nike

美好的一天

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

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

最佳答案

看来你需要transform首先为具有相同大小的新 Series 替换 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

关于python - 用python中另一列中出现的产品数替换一列中的0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45918694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com