在某些情况下,如何将一列乘以一个数字?
How can I multiply one column by a number, under some condition?
我有以下数据框,名称为 a.
symbol position strategy industry Fund EX Date Pay Date Record Date Type Net Rate Gross Rate Product Type
0 7203 44000.00 L Trans.Equip. 59107 2021/03/30 2021/05/28 2021/03/31 Cash Dividend 102.00 120.00 EQ
1 6758 28500.00 L Elec. App. 59107 2021/03/30 2021/06/04 2021/03/31 Cash Dividend 25.00 30.00 EQ
2 4063 12500.00 L Chemicals 59107 2021/03/30 2021/06/29 2021/03/31 Cash Dividend 110.00 130.00 EQ
16 8306 256000.00 L Banks 59107 2021/03/30 2021/06/30 2021/03/31 Cash Dividend 11.00 13.00 EQ
17 3003 115000.00 L Real Estate 59107 NaN NaN NaN <NA> nan nan <NA>
现在我想添加一个新列,为我提供 position*Rate
然后当我的“策略”是“S”时,我想将新列乘以 (-1)
但是这段代码给了我一个错误
a['Earning'] = a['position']*a['Net Rate']
def short(row):
if row["strategy"] == 'S':
return row['Earning'] *(-1)
a["final_earning"] = a.apply(short, axis=1)
错误的最后一行是
TypeError: boolean value of NA is ambiguous
如何获得“最终收入”。提前谢谢。
这应该适合你:
import numpy as np
a['Earning'] = a["position"].mul(a["Net Rate"])
def short(row):
if row["strategy"] == 'S' and not np.isnan(row["Earning"]):
return row['Earning'] * (-1)
return np.nan
a["final_earning"] = a.apply(short, axis=1)
Pandas mul
函数为您处理 nan
值。
我有以下数据框,名称为 a.
symbol position strategy industry Fund EX Date Pay Date Record Date Type Net Rate Gross Rate Product Type
0 7203 44000.00 L Trans.Equip. 59107 2021/03/30 2021/05/28 2021/03/31 Cash Dividend 102.00 120.00 EQ
1 6758 28500.00 L Elec. App. 59107 2021/03/30 2021/06/04 2021/03/31 Cash Dividend 25.00 30.00 EQ
2 4063 12500.00 L Chemicals 59107 2021/03/30 2021/06/29 2021/03/31 Cash Dividend 110.00 130.00 EQ
16 8306 256000.00 L Banks 59107 2021/03/30 2021/06/30 2021/03/31 Cash Dividend 11.00 13.00 EQ
17 3003 115000.00 L Real Estate 59107 NaN NaN NaN <NA> nan nan <NA>
现在我想添加一个新列,为我提供 position*Rate 然后当我的“策略”是“S”时,我想将新列乘以 (-1) 但是这段代码给了我一个错误
a['Earning'] = a['position']*a['Net Rate']
def short(row):
if row["strategy"] == 'S':
return row['Earning'] *(-1)
a["final_earning"] = a.apply(short, axis=1)
错误的最后一行是
TypeError: boolean value of NA is ambiguous
如何获得“最终收入”。提前谢谢。
这应该适合你:
import numpy as np
a['Earning'] = a["position"].mul(a["Net Rate"])
def short(row):
if row["strategy"] == 'S' and not np.isnan(row["Earning"]):
return row['Earning'] * (-1)
return np.nan
a["final_earning"] = a.apply(short, axis=1)
Pandas mul
函数为您处理 nan
值。