【问题标题】:How to change multiple column values with np.where?如何使用 np.where 更改多个列值?
【发布时间】: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

标签: python pandas numpy


【解决方案1】:

我们可以在axis=1 上使用DataFrame.filtersum,然后我们将值设置为NaNDataFrame.mask

lines = dftaxitems.filter(like="line")
m = lines.sum(axis=1).ne(dftaxitems["ExclBTW"])
dftaxitems[lines.columns] = lines.mask(m)
   line amount#1  line amount#2  ExclBTW
0            NaN            NaN     0.50
1           0.13           0.05     0.18
2            NaN            NaN     0.05

【讨论】:

  • 这似乎是一个很好的解决方案,但是却得到了不同的结果.. 行数不应该是 NaN'd
  • 您能否调整您的示例数据以重现该问题。现在给定的结果正确
  • 我的值不是浮动的,所以必须使用 .astype(float)
【解决方案2】:

编辑:添加更多通用解决方案,可处理任意数量的类似 lineamount 列

c = dftaxitems.filter(like='line amount#').columns
m = dftaxitems[c].sum(1).eq(dftaxitems['ExclBTW'])
dftaxitems.loc[~m, c] = np.nan
dftaxitems


请您尝试以下操作。简单的解释是:我们可以使用布尔索引来填充 NaN 值。首先在 m 变量中获取掩码(我们正在检查条件,如果 2 列之和等于第 3 列),然后使用 loc 函数相应地设置 NaN 值。

m = (dftaxitems['line amount#1'] + dftaxitems['line amount#2']) == dftaxitems['ExclBTW']

dftaxitems.loc[~m, ['line amount#1', 'line amount#2']] = np.nan
dftaxitems

输出如下:

   line amount#1  line amount#2  ExclBTW
0            NaN            NaN     0.50
1           0.13           0.05     0.18
2            NaN            NaN     0.05

【讨论】:

  • 感谢您的回答:您能否将行数设为动态,因为我想动态地进行,因为行数可能高达 10 行。
  • @Max,当然,请给我一两分钟,我会发帖的。
  • @Max,您能否检查一下我的编辑答案,如果这对您有帮助,请告诉我。
  • @Erfan,可能逻辑是相同的(可能对很多人来说)但实现完全不同,这不能说是复制恕我直言,干杯。
【解决方案3】:
dftaxitems['line amount#1'] = np.where(dftaxitems['line amount#1'] + dftaxitems['line amount#1'] >= dftaxitems['ExclBTW'], dftaxitems['line amount#1'], np.nan)
dftaxitems['line amount#2'] = np.where(dftaxitems['line amount#1'] + dftaxitems['line amount#1'] >= dftaxitems['ExclBTW'], dftaxitems['line amount#2'], np.nan)

我用这个,但一定有更好的办法解决

【讨论】:

    【解决方案4】:
    import pandas as pd
    import numpy as np
    
    d = {'line amount#1': [0.21, 0.13, 0.1], 'line amount#2': [0.0, 0.05, .05], 'ExclBTW': [0.5, 0.18, .05]}
    df = pd.DataFrame(data=d)
    print(df)
    
    df['line amount#1'] = df['line amount#1'].where(df['line amount#1'] + df['line amount#2'] == df['ExclBTW'], other=np.nan)
    df['line amount#2'] = df['line amount#1'].where(df['line amount#1'] + df['line amount#2'] == df['ExclBTW'], other=np.nan)
    print(df)
    

    输出:

       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
    
       line amount#1  line amount#2  ExclBTW
    0            NaN            NaN     0.50
    1           0.13           0.13     0.18
    2            NaN            NaN     0.05
    

    【讨论】:

    • 所以我想动态地做,因为行数可能高达 10 行。
    猜你喜欢
    • 2021-09-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 2017-07-27
    • 1970-01-01
    • 2019-10-03
    相关资源
    最近更新 更多