将Python中的.txt文件解析为Numpy数组
我有一堆.txt文件,其中包含以下格式的指标:将Python中的.txt文件解析为Numpy数组,python,numpy,parsing,Python,Numpy,Parsing,我有一堆.txt文件,其中包含以下格式的指标: |Jaccard: 0.6871114980646424 |Dice: 0.8145418946558747 |Volume Similarity: -0.0006615037672849326 |False Positives: 0.18572742753126772 |False Negatives: 0.185188604940396 我想全部读取它们(大约700个),并将每个值存储到一个numpy数组中,这样我就可以得到诸如平均j
|Jaccard: 0.6871114980646424
|Dice: 0.8145418946558747
|Volume Similarity: -0.0006615037672849326
|False Positives: 0.18572742753126772
|False Negatives: 0.185188604940396
我想全部读取它们(大约700个),并将每个值存储到一个numpy数组中,这样我就可以得到诸如平均jaccard、平均dice等统计数据
我该怎么做呢?这是我的方法。结果是一个包含数组中所有度量的字典,例如
{"|Jaccard" : array...,
....}
代码可能如下所示:
import numpy as np
import os
pathtodir = "filedir"
d = {}
for file in os.listdir(pathtodir):
with open(file, "r") as of:
lines = of.readlines()
for line in lines:
k, v = line.split(": ")
if k in d.keys():
d[k].append(v)
else:
d[k] = [v]
for k in d:
d[k] = np.array(d[k])
您可以使用numpy中的
genfromtxt()
。看见
使用“:”作为分隔符,并提取后跟浮点的字符串
data=np.genfromtxt(路径,分隔符=“:”,dtype='S64,f4')
解析文件并生成以下数据
:
(b'|Jaccard', 6.8711150e-01) (b'|Dice', 8.1454188e-01)
(b'|Volume Similarity', -6.6150376e-04)
(b'|False Positives', 1.8572743e-01)
(b'|False Negatives', 1.8518861e-01)]
我更喜欢打开每个文件并将其内容保存在
pandas.DataFrame
中。与numpy.array
相比,它的明显优势在于更容易执行后续统计。检查此代码:
import pandas as pd
import os
pathtodir = r'data' # write the name of the subfolder where your file are stored
df = pd.DataFrame()
file_count = 0
for file in os.listdir(pathtodir):
with open(os.path.join(pathtodir, file), 'r') as of:
lines = of.readlines()
for line in lines:
header, value = line.split(':')
value = float(value.replace(' ','').replace('\n', ''))
if header not in df.columns:
df[header] = ''
df.at[file_count, header] = value
file_count += 1
for column in df.columns:
df[column] = df[column].astype(float)
通过4个示例文件,我得到以下数据帧:
print(df.to_string())
Jaccard Dice Volume Similarity False Positives False Negatives
0 0.687111 0.814542 -0.000662 0.185727 0.185189
1 0.345211 0.232542 -0.000455 0.678547 0.156752
2 0.623451 0.813345 -0.000625 0.132257 0.345519
3 0.346111 0.223454 -0.000343 0.453727 0.134586
还有一些动态统计数据:
print(df.describe())
Jaccard Dice Volume Similarity False Positives False Negatives
count 4.000000 4.000000 4.000000 4.000000 4.000000
mean 0.500471 0.520971 -0.000521 0.362565 0.205511
std 0.180639 0.338316 0.000149 0.253291 0.095609
min 0.345211 0.223454 -0.000662 0.132257 0.134586
25% 0.345886 0.230270 -0.000634 0.172360 0.151210
50% 0.484781 0.522944 -0.000540 0.319727 0.170970
75% 0.639366 0.813644 -0.000427 0.509932 0.225271
max 0.687111 0.814542 -0.000343 0.678547 0.345519
您想在单个2D数组中使用名称和值吗?如果是这样,请在读取文件时循环,并附加每个元素。或者,您想让700个文件中的每个元素都可供以后处理?读取行、拆分和解析数字。您显示的内容并不意味着任何数组结构,因此我们无法在这方面帮助您。