【问题标题】:For a pandas dataframe column, TypeError: float() argument must be a string or a number对于 pandas 数据框列,TypeError: float() 参数必须是字符串或数字
【发布时间】:2018-01-07 03:02:22
【问题描述】:

这里是 'LoanAmount'、'ApplicantIncome'、'CoapplicantIncome' 是类型对象的代码:

document=pandas.read_csv("C:/Users/User/Documents/train_u6lujuX_CVtuZ9i.csv")


document.isnull().any()
document = document.fillna(lambda x: x.median())

for col in ['LoanAmount', 'ApplicantIncome', 'CoapplicantIncome']:
    document[col]=document[col].astype(float)

document['LoanAmount_log'] = np.log(document['LoanAmount'])
document['TotalIncome'] = document['ApplicantIncome'] + document['CoapplicantIncome']
document['TotalIncome_log'] = np.log(document['TotalIncome'])

在将对象类型转换为浮点数时出现以下错误:

TypeError: float() argument must be a string or a number

请帮忙,因为我需要使用这些功能来训练我的分类模型。这是 csv 文件的 sn-p -

Loan_ID Gender  Married Dependents  Education   Self_Employed   ApplicantIncome CoapplicantIncome   LoanAmount  Loan_Amount_Term    Credit_History  Property_Area   Loan_Status 
LP001002    Male    No  0         Graduate        No                5849            0                               360                        1                Urban           Y 
LP001003    Male    Yes 1         Graduate        No                4583            1508                128         360                        1                Rural           N 
LP001005    Male    Yes 0         Graduate        Yes               3000            0                   66          360                        1                Urban           Y 
LP001006    Male    Yes 0         Not Graduate    No                2583            2358                120         360                        1                Urban           Y

【问题讨论】:

  • 可以添加csv文件的sn-p吗?以及错误的行号
  • 已添加! @Bharathshetty
  • @Bharathshetty 错误是在分类器中的训练数据拟合过程中
  • 这是因为fillna didi中的lambda

标签: python-2.7 pandas numpy


【解决方案1】:

在您的代码中document = document.fillna(lambda x: x.median()) 将返回一个函数而不是一个值,因此函数不能转换为浮点数,它应该是数字字符串或整数。

希望以下代码有所帮助

median = document['LoanAmount'].median()
document['LoanAmount'] = document['LoanAmount'].fillna(median) # Or document = document.fillna(method='ffill')
for col in ['LoanAmount', 'ApplicantIncome', 'CoapplicantIncome']:
    document[col]=document[col].astype(float)

document['LoanAmount_log'] = np.log(document['LoanAmount'])
document['TotalIncome'] = document['ApplicantIncome'] + document['CoapplicantIncome']
document['TotalIncome_log'] = np.log(document['TotalIncome'])

【讨论】:

  • 现在出现以下错误 - ValueError: Input contains NaN, infinity or a value too large for dtype('float32').
  • 由于您有很多列,最好使用ffill 然后拟合数据。
  • 实际上错误在我适合我的分类器的那一行
猜你喜欢
  • 2021-03-30
  • 2023-02-18
  • 1970-01-01
  • 2020-04-24
  • 2020-05-05
  • 2019-11-04
  • 1970-01-01
  • 2018-02-26
  • 2020-10-27
相关资源
最近更新 更多