【问题标题】:Validation check Excluding VAT - VAT and Total Amount验证检查不包括增值税 - 增值税和总金额
【发布时间】:2021-03-08 16:47:09
【问题描述】:

我正在尝试进行对帐/验证检查是否有两个数字,一个不包括增值税,一个增值税等于总数。

我有以下df:

    Document Type   Factuurnummer   FactuurdatumKvK    ExclBTW   BTW        Totaal  Vervaldatum Item    Omschrijving    ... Betalingsvoorwaarden    Email   Postalcode_Finalp   Postalcodestringp   Cityp   Countryp    Postalcode_Final    Postalcodestring    City    Country
0   NaN 44  2021-02-27  58782494                       1700.00  357.00  2057.00 2021-03-13  

I've tried the following code:
#validation check
for i, row in df1.iterrows():
    if df1['Totaal'][i].astype('float') == (df1['ExclBTW'][i].astype('float') + df1['BTW'][i].astype('float')):
        df1['Totaal'].astype('float') == df1['Totaal'].astype('float')
    else:
        df1['Totaal'] = "ERROR!" 

但是,得到一个无效的 ValueError.. 你们认为最好的是什么?

--------------------------------------------------------------------------- AttributeError                            Traceback (most recent call last) <ipython-input-14-a461c3c9030f> in <module>
    113 #validation check
    114 for i, row in df1.iterrows():
--> 115     if df1['Totaal'][i].astype('float') == (df1['ExclBTW'][i].astype('float') + df1['BTW'][i].astype('float')):
    116         df1['Totaal'].astype('float') == df1['Totaal'].astype('float')
    117     else:

AttributeError: 'str' object has no attribute 'astype'

请帮忙

【问题讨论】:

  • 如果if 语句运行,你想做什么?
  • 要么保持当前值(以防Totaal准确),要么在不匹配的情况下放置错误
  • 如果是真的你想做什么?我想你可以做np.where(df1['Totaal'].astype('float') == (df1['ExclBTW'].astype('float') + df1['BTW'].astype('float')), True, False,)
  • 更改您正在使用的整个列的类型。另一种方法是转换为浮动:float(df1['Totaal'][i])。但前者更好。
  • 它返回什么?

标签: python pandas dataframe syntax


【解决方案1】:

Pandas 允许您以矢量化方式进行这些操作

# have numpy for efficiency
import numpy as np

...
# assuming  no missing values
# np.where(condition, value_if_condition_true, value_if_condition_false, [default_value])

np.where(df1['Totaal'].astype('float') == (df1['ExclBTW'].astype('float') + df1['BTW'].astype('float')), True, False)

【讨论】:

    【解决方案2】:

    您可以使用astypeapply 来做到这一点:

    df.loc[:, ['ExclBTW', 'BTW','Totaal']] = df[['ExclBTW', 'BTW','Totaal']].apply(pd.to_numeric, errors='coerce')
    
    df['new_col'] = df[['ExclBTW', 'BTW','Totaal']].\
                      apply(lambda x: x['Totaal'] if x['Totaal'] == (x['ExclBTW'] + x['BTW']) else 'ERROR!', axis=1)
    

    【讨论】:

    • 乐于助人!如果可以的话,请给它一个赞成票。
    • 我这样做了!缺少值时出现以下错误: ValueError: could not convert string to float: ''
    • 您对此有什么建议吗? :)
    • 是的。发生这种情况是因为在 ''ExclBTW'、'BTW'、'Totaal'' 中有一些值无法转换为数值。但是您可以使用pd.to_numeric(error='coerce') 强制它们变为数字或NaN 值。我编辑了我的答案。请告诉我它是如何工作的。
    • 我编辑了我的答案。请看一下,让我知道它是否有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    相关资源
    最近更新 更多