![](/img/trans.png)
[英]Plot a CSV file where the delimiter is '; ' (semicolon + space)
[英]Read CSV file with semicolon as delimiter
我有一個numpy
2D 數組,它的形狀為(4898, )
,其中每行中的元素用分號分隔,但仍存儲在單列而不是多列中(所需的結果)。 如何在二維數組的每個數組中每次出現分號時創建拆分。 我已經編寫了以下 Python 腳本來執行此操作,但它會引發錯誤。
stochastic_gradient_descent_winequality.py
import numpy
import pandas
if __name__ == '__main__' :
with open('winequality-white.csv', 'r') as f_0 :
with open('winequality-white-updated.csv', 'w') as f_1 :
f_0.next()
for line in f_0 :
f_1.write(line)
wine_data = pandas.read_csv('winequality-white-updated.csv', sep = ',', header = None)
wine_data_ = wine_data
wine_data = numpy.array([x.split(';') for x in wine_data_], dtype = numpy.float)
print (numpy.shape(wine_data))
錯誤
Traceback (most recent call last):
File "stochastic_gradient_descent_winequality.py", line 16, in <module>
wine_data = numpy.array([x.split(';') for x in wine_data_], dtype = numpy.float)
AttributeError: 'numpy.int64' object has no attribute 'split'
如果您使用分號 ( ;
) 作為 csv 文件分隔符而不是逗號 ( ,
),則可以調整第一行:
wine_data = pandas.read_csv('winequality-white-updated.csv', sep = ';', header = None)
您的列表理解的問題在於[x.split(';') for x in wine_data_]
迭代列名稱。
在這種情況下,您不需要使用列表理解的行。 您可以讀入您的數據並完成。
wine_data = pandas.read_csv('winequality-white-updated.csv', sep = ',', header = None)
print (numpy.shape(wine_data))
假設你的 csv 文件是這樣的:
2.12;5.12;3.12
3.1233;4;2
4;4.9696;3
2;5.0344;3
3.59595;4;2
4;4;3.59595
...
然后像這樣更改您的代碼:
import pandas, numpy
wine_data = pandas.read_csv('test.csv', sep = ',', header = None)
wine_data_ = wine_data
wine_data = numpy.array([x.split(';') for x in wine_data_[0]], dtype = numpy.float)
wine_data
wine_data
將是:
array([[ 2.12 , 5.12 , 3.12 ],
[ 3.1233 , 4. , 2. ],
[ 4. , 4.9696 , 3. ],
[ 2. , 5.0344 , 3. ],
[ 3.59595, 4. , 2. ],
[ 4. , 4. , 3.59595]])
提高效率:
import pandas, numpy
wine_data = pandas.read_csv('test.csv', sep = ';', header = None)
wine_data = numpy.array(wine_data,dtype = numpy.float)
在這
x.split(';') for x in wine_data_
無論你得到什么x
都不是字符串。 只有字符串有split()
。 如果它不是字符串,那么它會給出這個錯誤
對象沒有屬性 'split
檢查您的x
值。
你可以試試這樣的...
def get_y(r):
return str(r['label']).split(' ')
result :
(PILImage mode=RGB size=800x800, TensorMultiCategory([0., 0., 0., 1., 0., 0.]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.