2017-06-01 17 views
1

このエラーが発生する理由を調べるのに最も苦労しています。私はたくさんの検索をしましたが、何も解決できません。浮動小数点型の最近傍の浮動小数点数に無効な文字があります

import numpy as np 
import warnings 
from collections import Counter 
import pandas as pd 

def k_nearest_neighbors(data, predict, k=3): 
if len(data) >= k: 
    warnings.warn('K is set to a value less than total voting groups!') 
distances = [] 
for group in data: 
    for features in data[group]: 
     euclidean_distance = np.linalg.norm(np.array(features)- 
np.array(predict)) 
     distances.append([euclidean_distance,group]) 
votes = [i[1] for i in sorted(distances)[:k]] 
vote_result = Counter(votes).most_common(1)[0][0] 
return vote_result 

df = pd.read_csv("data.txt") 
df.replace('?',-99999, inplace=True) 
df.drop(['id'], 1, inplace=True) 
full_data = df.astype(float).values.tolist() 

print(full_data) 

実行後。私はastype(float)プログラムが 私は何をする必要があるの罰金実行削除した場合はエラーに

Traceback (most recent call last): 
File "E:\Jazab\Machine Learning\Lec18(Testing K Neatest Nerighbors 
Classifier)\Lec18(Testing K Neatest Nerighbors 
Classifier)\Lec18_Testing_K_Neatest_Nerighbors_Classifier_.py", line 25, in 
<module> 
full_data = df.astype(float).values.tolist() 
File "C:\Python27\lib\site-packages\pandas\util\_decorators.py", line 91, in 
wrapper 
return func(*args, **kwargs) 
File "C:\Python27\lib\site-packages\pandas\core\generic.py", line 3299, in 
astype 
**kwargs) 
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 3224, in 
astype 
return self.apply('astype', dtype=dtype, **kwargs) 
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 3091, in 
apply 
applied = getattr(b, f)(**kwargs) 
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 471, in 
astype 
**kwargs) 
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 521, in 
_astype 
values = astype_nansafe(values.ravel(), dtype, copy=True) 
File "C:\Python27\lib\site-packages\pandas\core\dtypes\cast.py", line 636, 
in astype_nansafe 
return arr.astype(dtype) 
ValueError: invalid literal for float(): 3) <-----Reappears in Group 8 as: 
Press any key to continue . . . 

を与えますか?

答えて

0

あなたのCSVファイルには3)というエントリがあり、)のためにそれをフロートにキャストできないため、Pandasは不平を言っているようです。

+0

私のCSVは、患者 – Jazab

+0

の記録はたぶん、あなたの質問に、ファイルの例を示しています。とにかく、私はjezraelの答えは、あなたがソースデータを制御できない場合に必要なものだと思います。 – SiHa

+0

yeh、あなたの提案作業。それは今感謝しています – Jazab

1

不良データ(3))がありますので、to_numericapplyが必要です。なぜなら、すべての列を処理する必要があるからです。

数字以外は、NaNに変換されます。これは、fillnaでスカラーに置き換えられます。 0

full_data = df.apply(pd.to_numeric, errors='coerce').fillna(0).values.tolist() 

はサンプル:

df = pd.DataFrame({'A':[1,2,7], 'B':['3)',4,5]}) 
print (df) 
    A B 
0 1 3) 
1 2 4 
2 7 5 

full_data = df.apply(pd.to_numeric, errors='coerce').fillna(0).values.tolist() 
print (full_data) 
[[1.0, 0.0], [2.0, 4.0], [7.0, 5.0]] 
関連する問題