我有以下的大熊猫数据帧
ID Quantity Rate Product
1 10 70 MS
2 10 70 MS
3 100 70 MS
4 10 100 MS
5 700 65 HS
6 1100 65 HS
7 700 100 HS
我想帽Quantity and Rate
对于MS
与平均值的值,如果Quantity is greater than 100 and Rate is greater than 99
那么就应该由平均值和HS
更换,如果Quantity is greater than 1000 and Rate is greater than 99
那么就应该由平均值来代替。
我使用下面的方法
mean_MS = df['Quantity'][(df['Product'] == 'MS') and (df['Quantity'] < 100)].mean()
但是,这是行不通的。
我想要的数据帧将
ID Quantity Rate Product
1 10 70 MS
2 10 70 MS
3 10 70 MS
4 10 70 MS
5 700 65 HS
6 700 65 HS
7 700 65 HS
解决这个的一种方式,
m1=df['Product']=='MS'
m2=(df['Quantity']>=100)|(df['Rate']>99)
df.loc[m1&m2,'Quantity']=df[m1&(df['Quantity']<100)]['Quantity'].mean()
df.loc[m1&m2,'Rate']=df[m1&(df['Rate']<99)]['Rate'].mean()
m3=df['Product']=='HS'
m4=(df['Quantity']>=1000)|(df['Rate']>99)
df.loc[m3&m4,'Quantity']=df[m3&(df['Quantity']<1000)]['Quantity'].mean()
df.loc[m3&m4,'Rate']=df[m3&(df['Rate']<99)]['Rate'].mean()
O / P:
ID Quantity Rate Product
0 1 10.0 70.0 MS
1 2 10.0 70.0 MS
2 3 10.0 70.0 MS
3 4 10.0 70.0 MS
4 5 700.0 65.0 HS
5 6 700.0 65.0 HS
6 7 700.0 65.0 HS
说明:
MS
,另一种是HS
两种含有相同的逻辑,但在数量值不同。MS
行和清理出的值,其中东风取代的平均值我们条件超出。HS
太其中数量条件修改从100到1000。IIUC,你也可以尝试以下:
val1= df.loc[df.Product.eq('MS'),['Quantity','Rate']].mode().values
#array([[10, 70]], dtype=int64)
val2= df.loc[df.Product.eq('HS'),['Quantity','Rate']].mode().values
#array([[700, 65]], dtype=int64)
df.loc[df.Product.eq('MS')&df.Quantity.ge(100)|df.Product.eq('MS')&df.Rate.gt(99),['Quantity','Rate']] = val1
df.loc[df.Product.eq('HS')&df.Quantity.ge(1000)|df.Product.eq('HS')&df.Rate.gt(99),['Quantity','Rate']] = val2
print(df)
ID Quantity Rate Product
0 1 10 70 MS
1 2 10 70 MS
2 3 10 70 MS
3 4 10 70 MS
4 5 700 65 HS
5 6 700 65 HS
6 7 700 65 HS