【发布时间】:2021-07-16 09:43:19
【问题描述】:
假设你有以下df:
d = {'line amount#1': [0.21, 0.13, 0.1], 'line amount#2': [0.0, 0.05, .05], 'ExclBTW': [0.5, 0.18, .05]}
dftaxitems = pd.DataFrame(data=d)
dftaxitems
line amount#1 line amount#2 ExclBTW
0 0.21 0.00 0.50
1 0.13 0.05 0.18
2 0.10 0.05 0.05
现在,我想在不加到 BTW 列时将所有行金额的值更改为 np.nan,并在加起来时保留该值。
所以我想动态地做,因为行数可能高达 10 行。
但是使用以下代码得到以下错误:
#change line amount if not totalling into ExclBTW:
dfchecklineamount = dftaxitems.filter(like='line amount').astype(float)
dfchecklineamount['sum'] = dfchecklineamount[list(dfchecklineamount.columns)].sum(axis=1)
dfchecklineamount['check'] = np.where(dfchecklineamount['sum'].astype(float) == dfresult['ExclBTW'].astype(float),True, False)
dfchecklineamount['check'] = np.where(dfchecklineamount['sum'].astype(float) == dfresult['ExclBTW'].astype(float),True, False)
colstochange = dfchecklineamount.filter(regex ='line amount').columns
dfchecklineamount[colstochange] = np.where(dfchecklineamount['check'] == False, np.nan,dfchecklineamount[colstochange] )
ValueError: operands could not be broadcast together with shapes (2,) () (2,4)
请帮忙!
期望的输出:
line amount#1 line amount#2 ExclBTW
0 np.nan np.nan 0.50
1 0.13 0.05 0.18
2 np.nan np.nan 0.05
【问题讨论】:
-
请发布您预期的输出数据框
-
link 这有帮助吗?
-
会做@sammywemmy
-
@AmriRasyidi 不幸的是一栏。
-
您确定预期行的最后一行是 NaN 吗? 0.1 + 0.05 >= 0.05