首页 > 解决方案 > ValueError:没有足够的值来解包(预期 2,得到 1)Python

问题描述

尝试将数值转换为单词,但是当数据集中有任何 Null 值时,它会给出错误。

输入数据 :

Total_value

253897
587619.10
15786
NaN
354783.36

输出

value_words

Two Lakh Fifty-Three Thousand Eight Hundred And Ninety-Seven Rupees
Five Lakh Eighty-Seven Thousand Six Hundred And Nineteen Rupees And One Paise
Fifteen Thousand Seven Hundred And Eighty-Six Rupees
NaN
Three Lakh Fifty-Four Thousand Seven Hundred And Eighty-Three Rupees And Thirty-Six Paise

当所有行都具有值时它工作正常,但当任何行具有 NaN 值时会出错

我一直在使用的代码:

from num2words import num2words

def word(x):
    rupees, paise = x.split('.')
    rupees_word = num2words(rupees, lang ='en_IN') + ' Rupees'
    if int(paise) > 0:
        paise_word = ' and ' + num2words(paise, lang ='en_IN') + ' Paise'
        word =  rupees_word + paise_word
    else:
        word = rupees_word
    word = word.replace(',','').title()
    return word
    
    
df['Total_value'] = df.Total_value.astype(str).apply(lambda x: word(x))

但是在执行上述脚本时,它会在找到任何具有 NaN 值的行时给出错误。“ValueError:没有足够的值来解包(预期 2,得到 1)”

标签: pythonpandas

解决方案


只有在恰好包含一个时,写作rupees, paise = x.split('.')才有效。您可以简单地忽略 NaN:x'.'

from num2words import num2words

def word(x):
    if x == "nan":
        return x
    rupees, paise = x.split('.')
    rupees_word = num2words(rupees, lang ='en_IN') + ' Rupees'
    if int(paise) > 0:
        paise_word = ' and ' + num2words(paise, lang ='en_IN') + ' Paise'
        word =  rupees_word + paise_word
    else:
        word = rupees_word
    word = word.replace(',','').title()
    return word
    
    
df['Total_value'] = df.Total_value.astype(str).apply(lambda x: word(x))

推荐阅读