我想sum用另一個列值更改列的符號apple。換句話說,每當它看到apple時,總和都是負值。我以為我可以做到np.where((ef.fruit == 'apple'), (-1 * ef.sum), ef.sum),但它給了我一個錯誤。我該如何克服呢?
import pandas as pd
data = {'id':["ab3e3", "psdds2", "pas13", "ccdf2", "dsda1"],
'fruit':["apple", "others", "organge", "watermelon", "apple"],
'sum':[2, 3, 6, 8, 3]}
ef = pd.DataFrame(data)
ef
id fruit sum
0 ab3e3 apple 2
1 psdds2 others 3
2 pas13 organge 6
3 ccdf2 watermelon 8
4 dsda1 apple 3
uj5u.com熱心網友回復:
如果您確實通過[]not呼叫它,請不要使用 panda 原始函式命名您的列.
np.where((ef.fruit == 'apple'), (-1 * ef['sum']), ef['sum'])
Out[159]: array([-2, 3, 6, 8, -3], dtype=int64)
uj5u.com熱心網友回復:
一種簡單的方法是制作一個掩碼 whereapple對應,-1其他值對應1,然后是多個:
df['sum'] *= np.where(df['fruit'].eq('apple'), -1, 1)
輸出:
>>> df
id fruit sum
0 ab3e3 apple -2
1 psdds2 others 3
2 pas13 organge 6
3 ccdf2 watermelon 8
4 dsda1 apple -3
另一種解決方案是使用.loc:
df.loc[df['fruit'] == 'apple', 'sum'] = -df['sum']
uj5u.com熱心網友回復:
使用numpy.where:
ef['sum'] *= np.where(ef['fruit'].eq('apple'), -1, 1)
或使用熊貓loc索引:
ef.loc[ef['fruit'].eq('apple'), 'sum'] *= -1
輸出:
id fruit sum
0 ab3e3 apple -2
1 psdds2 others 3
2 pas13 organge 6
3 ccdf2 watermelon 8
4 dsda1 apple -3
uj5u.com熱心網友回復:
ef.loc[ef["fruit"]=="apple", "sum"] *= -1
結果:
id fruit sum
0 ab3e3 apple -2
1 psdds2 others 3
2 pas13 organge 6
3 ccdf2 watermelon 8
4 dsda1 apple -3
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/445135.html
