试图将数值转换为单词,但当数据集中存在任何空值时,会出现错误
输入数据:
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)
只有当
x
正好包含一个'.'
时,写入rupees, paise = x.split('.')
才有效。您可以忽略NAN:很可能您只需要将函数应用于非NaN值
这可能比检查函数中的空值要快,但速度稍慢
相关问题 更多 >
编程相关推荐