python - 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)”
解决方案
只有在恰好包含一个时,写作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))
推荐阅读
- vb.net - 为什么 AndAlso 语句比嵌套的 If 条件慢得多?
- angular - 当用户在弹出窗口中选择 No 时,将变量设置为 null
- c++ - 如何修复从 ascii 值到 int 的数组赋值
- python - RecursionError:混合 SKlearn 模型时超出最大递归深度
- reactjs - 给反应无状态功能组件一个打字稿类型的正确方法是什么
- php - 如何从数据库中获取特定行?
- rust - 检查 HashSet 中是否包含字符串切片
> 不分配新字符串 - angular - 如何正确制作放置在与项目/dockerfile不同的路径中的Docker Compose?
- python - 以实数形式将时间跨度字符串转换为秒
- python - 如何进行仅类型注释的类型断言?