[英]Replace missing value in a row if there's a match in two columns from another row using Pandas
[英]replace 0.01 with the row maximum value from another columns
有這樣的數據框 df
article price1 price2 price3
0 A9911652 0.01 0.01 2980.31
1 A9911653 7041.33 0.01 2869.40
2 A9911654 0.01 9324.63 0.01
3 A9911659 4785.74 0.01 1622.78
4 A9911661 6067.27 6673.99 0.01
我想用行的最大值替換 0.01 值,所以它應該是這樣的:
article price1 price2 price3
0 A9911652 2980.31 2980.31 2980.31
1 A9911653 7041.33 7041.33 2869.40
2 A9911654 9324.63 9324.63 9324.63
3 A9911659 4785.74 4785.74 1622.78
4 A9911661 6067.27 6673.99 6673.99
我嘗試了以下方法:
df.replace(0.01,df[['price3','price2','price1']].max(axis=1),inplace=True)
但它不會改變任何東西。 這樣做的正確方法是什么?
使用帶有axis=0
參數的DataFrame.mask
:
df = df.mask(df == 0.01, df[['price3','price2','price1']].max(axis=1), axis=0)
print (df)
article price1 price2 price3
0 A9911652 2980.31 2980.31 2980.31
1 A9911653 7041.33 7041.33 2869.40
2 A9911654 9324.63 9324.63 9324.63
3 A9911659 4785.74 4785.74 1622.78
4 A9911661 6067.27 6673.99 6673.99
如果要為設置新值指定列:
c =['price3','price2','price1']
df[c] = df[c].mask(df[c] == 0.01, df[c].max(axis=1), axis=0)
print (df)
article price1 price2 price3
0 A9911652 2980.31 2980.31 2980.31
1 A9911653 7041.33 7041.33 2869.40
2 A9911654 9324.63 9324.63 9324.63
3 A9911659 4785.74 4785.74 1622.78
4 A9911661 6067.27 6673.99 6673.99
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.