我有如下数据帧
ID Unit_ID Price
1 1 50
2 2 40
3 1 10000
3 2 10000
3 3 10000
3 4 10000
6 1 10000
8 3 10000从上面的数据帧中,我想用具有相同ID的行数替换Price = 10000,并且Price = 10000,这里count =4
预期输出:
ID Unit_ID Price
1 1 50
2 2 40
3 1 2500
3 2 2500
3 3 2500
3 4 2500
6 1 10000
8 3 10000发布于 2020-01-06 19:21:11
创建掩码,并将筛选的行除以sum的True值计数。
mask = df.Price == 10000
df.loc[mask, 'Price'] /= mask.sum()
#same like
#df.loc[mask, 'Price'] = df.loc[mask, 'Price'] / mask.sum()
print (df)
ID Unit_ID Price
0 1 1 50.0
1 2 2 40.0
2 3 1 2500.0
3 3 2 2500.0
4 3 3 2500.0
5 3 4 2500.0如果想要将所有值除以它们的计数:
df['Price'] /= df.groupby(by="Price")['Price'].transform('size')编辑:
df['Price'] /= df.groupby(by=["ID", "Price"])['Price'].transform('size')
print (df)
ID Unit_ID Price
0 1 1 50.0
1 2 2 40.0
2 3 1 2500.0
3 3 2 2500.0
4 3 3 2500.0
5 3 4 2500.0
6 6 1 10000.0
7 8 3 10000.0发布于 2020-01-06 19:22:07
如果您只想将行替换为10000,您可以这样做:
df.loc[df.Price==10000, 'Price']=10000/len(df.loc[df.Price==10000])如果你想用count值来划分每一行,你可以使用groupby和transform:
df.Price = df.groupby(by="Price").Price.transform(lambda x: x/len(x))
ID Unit_ID Price
0 1 1 50
1 2 2 40
2 3 1 2500
3 3 2 2500
4 3 3 2500
5 3 4 2500https://stackoverflow.com/questions/59611181
复制相似问题