我有一个(2M,23)维numpy
阵列X
。它有一个<U26
的dtype,即26个字符的unicode字符串。
array([['143347', '1325', '28.19148936', ..., '61', '0', '0'],
['50905', '0', '0', ..., '110', '0', '0'],
['143899', '1325', '28.80434783', ..., '61', '0', '0'],
...,
['85', '0', '0', ..., '1980', '0', '0'],
['233', '54', '27', ..., '-1', '0', '0'],
['���', '�', '�����', ..., '�', '��', '���']], dtype='<U26')
当我将它转换为float数据类型时,使用
X_f = X.astype(float)
我得到如上所示的错误。我试图找到如何解决' '的这个字符串格式错误。
它是什么意思(它叫什么?)以及如何解决这个错误?
编辑:有关如何读取数据的信息: -
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.functions import col
def loading_data(dataset):
dataset=sql_sc.read.format('csv').options(header='true', inferSchema='true').load(dataset)
# #changing column header name
dataset = dataset.select(*[col(s).alias('Label') if s == ' Label' else s for s in dataset.columns])
#to change datatype
dataset=dataset.drop('External IP')
dataset = dataset.filter(dataset.Label.isNotNull())
dataset=dataset.filter(dataset.Label!=' Label')#filter Label from label
print(dataset.groupBy('Label').count().collect())
return dataset
# invoking
ds_path = '../final.csv'
dataset=loading_data(ds_path)
type(dataset)
pyspark.sql.dataframe.DataFrame
import numpy as np
np_dfr = np.array(data_preprocessing(dataset).collect())
X = np_dfr[:,0:22]
Y = np_dfr[:,-1]
>> X
array([['143347', '1325', '28.19148936', ..., '61', '0', '0'],
['50905', '0', '0', ..., '110', '0', '0'],
['143899', '1325', '28.80434783', ..., '61', '0', '0'],
...,
['85', '0', '0', ..., '1980', '0', '0'],
['233', '54', '27', ..., '-1', '0', '0'],
['���', '�', '�����', ..., '�', '��', '���']], dtype='<U26')
这意味着字符串( )维度在图表中不固定,并且可以在运行调用之间变化。问号标记符号表示tf.TensorShape
Session.run或eval返回的任何张量都是NumPy数组。
>>> print(type(tf.Session().run(tf.constant([1,2,3]))))
<class 'numpy.ndarray'>
要么:
>>> sess = tf.InteractiveSession()
>>> print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>
或者,等效地:
>>> sess = tf.Session()
>>> with sess.as_default():
>>> print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>
Session.run或eval()返回的任何张量都不是NumPy数组。例如,稀疏张量作为SparseTensorValue返回:
>>> print(type(tf.Session().run(tf.SparseTensor([[0, 0]],[1],[1,2]))))
<class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'>
虽然不是最好的解决方案,但我通过将其转换为pandas数据框并继续工作取得了一些成功。
# convert X into dataframe
X_pd = pd.DataFrame(data=X)
# replace all instances of URC with 0
X_replace = X_pd.replace('�',0, regex=True)
# convert it back to numpy array
X_np = X_replace.values
# set the object type as float
X_fa = X_np.astype(float)
array([['85', '0', '0', '1980', '0', '0'],
['233', '54', '27', '-1', '0', '0'],
['���', '�', '�����', '�', '��', '���']], dtype='<U5')
array([[ 8.50e+01, 0.00e+00, 0.00e+00, 1.98e+03, 0.00e+00, 0.00e+00],
[ 2.33e+02, 5.40e+01, 2.70e+01, -1.00e+00, 0.00e+00, 0.00e+00],
[ 0.00e+00, 0.00e+00, 0.00e+00, 0.00e+00, 0.00e+00, 0.00e+00]])