python - 如何将字符串转换为 float ?值错误: could not convert string to float: '0,25691372'

标签 python machine-learning neural-network spyder xgboost

我使用 XGBoost 来衡量功能重要性,我想选择给我 90% 重要性的功能,所以首先我构建了一个 Dataframe,因为我需要它用于 excel,然后我编写了一个 while 循环来评估给我 90% 重要性的功能。之后是一个神经网络(但它不在下面的代码中)。我知道也许有一些最简单的方法可以做到这一点,但它给了我一个错误:

ValueError: could not convert string to float: '0,25691372'

代码是

  import pandas as pd
import numpy as np

from sklearn.ensemble import RandomForestRegressor
from sklearn.feature_selection import SelectFromModel
from sklearn import preprocessing

from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor
from matplotlib import pyplot as plt


dataset = pd.read_csv('CompleteDataSet_original_Clean_CONC.csv', decimal=',', delimiter = ";")
from sklearn.metrics import r2_score

label = dataset.iloc[:,-1]
features = dataset.drop(columns = ['Label'])
y_max_pre_normalize = max(label)
y_min_pre_normalize = min(label)

def denormalize(y):
    final_value = y*(y_max_pre_normalize-y_min_pre_normalize)+y_min_pre_normalize
    return final_value
X_train1, X_test1, y_train1, y_test1 = train_test_split(features, label, test_size = 0.20, random_state = 1, shuffle = True)

y_test2 = y_test1.to_frame()
y_train2 = y_train1.to_frame()

scaler1 = preprocessing.MinMaxScaler()
scaler2 = preprocessing.MinMaxScaler()
X_train = scaler1.fit_transform(X_train1)
X_test = scaler2.fit_transform(X_test1)


scaler3 = preprocessing.MinMaxScaler()
scaler4 = preprocessing.MinMaxScaler()
y_train = scaler3.fit_transform(y_train2)
y_test = scaler4.fit_transform(y_test2)


sel = XGBRegressor(colsample_bytree= 0.7, learning_rate = 0.005, max_depth = 5, min_child_weight = 3, n_estimators = 1000)
sel.fit(X_train, y_train)
importances = sel.feature_importances_

importances = [str(i) for i in importances]

importances = [i.replace(".", ",") for i in importances]

df1 = pd.DataFrame(features.columns)
df1.columns = ['Features']
df2 = pd.DataFrame(importances)
df2.columns = ['Importances [%]']
result = pd.concat([df1,df2],axis = 1)
result = result.sort_values(by='Importances [%]', ascending=False)

result.to_excel("Feature_Results.xlsx") 

i = 0
somma = 0
feature = []
while somma <=0.9:
    a = result.iloc[i,-1]
    somma = float(a) + somma
    feature.append(result.iloc[i,-2])
    i = i + 1

最佳答案

float('0,25691372'.replace(",", "."))

关于python - 如何将字符串转换为 float ?值错误: could not convert string to float: '0,25691372' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60140956/

相关文章:

c++ - 在 S 型神经网络 C++ 中使用反向传播,异或总是向 0.5 收敛

python - 为什么我翻译成 Python 的 Haskell 不能正常工作?

python - Scrapy spider_idle 调用以重新启动 scrape

python - 如何通过构造简单的 pandas Series 来定义正确的索引?

python - 树分类器的极高准确度指标

c++ - 为什么 HDF5 Output Caffe 层会写入看似不正确维度的数据?

python - 创建具有默认值的字典列表

python - 在 Python 中将单词分类

python - 如何将 2 个输出一个作为键,另一个作为值存储在字典中

tensorflow - 无法使用tensorflow 2.0.0 beta1保存模型