Pandas 将某个值替换为该值除以该值存在的时间数
我有如下数据帧Pandas 将某个值替换为该值除以该值存在的时间数,pandas,numpy,pandas-groupby,Pandas,Numpy,Pandas Groupby,我有如下数据帧 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 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
从上面的数据框中,我想替换价格=10000
通过对具有相同ID且价格为10000的行的计数,这里的计数为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
创建掩码并将过滤行按
True
s值的计数除以sum
:
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')
编辑:
如果只想将行替换为10000行,可以执行以下操作:
df.loc[df.Price==10000, 'Price']=10000/len(df.loc[df.Price==10000])
如果要使用值计数分割每一行,可以使用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 2500
编辑问题,仅当相同ID具有相同价格时才替换价格
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 2500