[英]Creating an Array from a text file with more than one data type in Python
我試圖從同時包含數字和字母(作為標題)的文本文件中創建一個數組,但是當我嘗試轉換並打開文件時,最終出現錯誤:
ValueError:無效的float()文字:0
要么
ValueError:無法將字符串轉換為浮點型:AA
我了解這是一個數據類型問題,想知道是否有人知道解決方法? 我是python的新手,通常在Matlab中編寫代碼。 我的文本文件包括:
AA, AB, AC, AD, AE, AF, AG, AH, AI
0, 1, 0, 1, 1, 0, 1, 0, 0
我嘗試過的代碼如下
import numpy as np
a = np.loadtxt('test.txt')
print
之后,我需要剪切所有具有零的列,並保留其中具有1的列。 每次加載的文本文件都會有所不同,我只需要查看哪些單元格和標題已填充了1。
numpy.loadtxt()
允許使用numpy.loadtxt()
參數,如下所示將讀取混合數據:
import numpy as np
a = np.loadtxt('test.txt', dtype=object)
因此,既然我們已經回答了如何使numpy.readtxt()
讀取我的文件,那么讓我們繼續探討如何解決分析文件中的零和一的問題。 下面的代碼片段讀入文件,然后查找哪些列包含任何列,以及所有列。
1:使用csv模塊
csv模塊可用於解析此文件。
import csv
with open('file1', 'rU') as csvfile:
csv_reader = csv.reader(csvfile)
# read the first line as the header
header = [c.strip() for c in next(csv_reader)]
# read the remaining lines, and transpose them into columns using zip()
cols = list(zip(*((int(c) for c in l) for l in csv_reader)))
# now lets find all the columns which have any and all ones
any_ones = [l for l, v in zip(header, cols) if any(v)]
all_ones = [l for l, v in zip(header, cols) if all(v)]
print(any_ones)
print(all_ones)
2:使用熊貓
pandas
也可以用來做這項工作。 比上面的學習曲線更多,但是您得到了所需要的。
df = pd.read_csv('file1')
# remove spaces from column names
df = df.rename(columns={x: x.strip() for x in df.columns})
any_ix = df.any()
all_ix = df.all()
print(list(any_ix[any_ix].index))
print(list(any_ix[all_ix].index))
CSV和熊貓的結果
['AB', 'AD', 'AE', 'AG']
['AB', 'AE']
文件1:
AA, AB, AC, AD, AE, AF, AG, AH, AI
0, 1, 0, 1, 1, 0, 0, 0, 0
0, 1, 0, 0, 1, 0, 1, 0, 0
假設您的文件名為file.text
,其中包含:
AA, AB, AC, AD, AE, AF, AG
0, 1, 0, 1, 1, 0, 1, 0, 0
您可以使用以下方式讀取文件:
with open('file.txt', 'r') as f:
read_file = f.read()
從字符串創建列表(即read_file
現在):
list_entries = read_file.split(',')
打印列表中的每個條目(替換\\n
新行字符):
for entry in list_entries:
print entry.replace('\n', '')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.