如何根据条件将一列中的值设置为另一列

时间:2019-04-02 12:04:32

标签: pandas loc

我有以下df:

if (substr($sku_code, 0, 1) === 'F') { $select->setValue($configValue); }

我想将“总计”的值转移到“金额”,如果“金额”列中已经有值,当然还有“总计”。

我过滤了:

subscription|amount| Total
a           |500   |
x           | 0    | 5000
x           |7500  | 5000
y           |7500  | 5000
y           | 0    | 5000
z           |7500  | 5000
z           | 0    | 5000
b           | 0    | 
b           |1000  |

但无法将值从总计(5000)转移到金额。

所需的输出:

df.loc[(df['total'].notnull()) & (df['amount']!=0)]

1 个答案:

答案 0 :(得分:1)

还有更多解决方案,如果将列更改为浮点数,则没有问题-DataFrame.locnumpy.where

mask = (df['Total'].notnull()) & (df['amount']!=0)

df.loc[mask, 'amount'] = df['Total']

df['amount'] = np.where(mask, df['Total'], df['amount'])

print (df)
  subscription  amount   Total
0            a   500.0     NaN
1            x     0.0  5000.0
2            x  5000.0  5000.0
3            y  5000.0  5000.0
4            y     0.0  5000.0
5            z  5000.0  5000.0
6            z     0.0  5000.0
7            b     0.0     NaN
8            b  1000.0     NaN

无变化整数列的解决方案以Series.maskSeries.where浮动或以integers强制转换为np.where

df['amount'] = df['amount'].mask(mask, df['Total'])

df['amount'] = df['amount'].where(~mask, df['Total'])

df['amount'] = df['amount'].where(~mask, df['Total']).astype(int)

print (df)
  subscription  amount   Total
0            a     500     NaN
1            x       0  5000.0
2            x    5000  5000.0
3            y    5000  5000.0
4            y       0  5000.0
5            z    5000  5000.0
6            z       0  5000.0
7            b       0     NaN
8            b    1000     NaN