【问题标题】:How do I load data from a text file and then put them in a dictionary?如何从文本文件中加载数据,然后将它们放入字典中?
【发布时间】:2017-09-03 13:58:46
【问题描述】:

我有一个数据文件,其中前 4 个 csv 是浮点数,最后一个值 是一个字符串,表示该行的标签

.5, .3, .2, .1, FAA
.2., .3, .5., .2, FXX
.5., .3, .2 , .9, FXX
.3, .3, .9, .3, FCA

我想将文件加载到一个 numpy 数组中,该数组通过 类,所以输出会是这样的:

FAA: [[.5, .3, .2, .1]]
FXX: [[.2., .3, .5., .2],
      [.5., .3, .2 , .9]]
FCA: [.3, .3, .9, .3]

这与此非常相似,但我无法在我自己的代码中使用它: Best way to separate data into 3 classes

此代码有效,但我不知道如何不在每个数据点内添加标签:

import numpy as np

data = np.genfromtxt('data.txt', delimiter=',', dtype=None, names=('length', 'width', 'distance', 'strength', 'label'))

separated = {}
for i in range(len(data)):
    vector = data[i]
    if (vector[-1] not in separated):
        separated[vector[-1]] = []
    separated[vector[-1]].append(vector)
for i in range(len(separated)):
               print separated
               print '\n'

一旦我得到我想要的方式,我将从那里计算均值和协方差矩阵。

编辑:当我从链接页面运行代码时,出现以下错误:

filtered = [map(float, item[:4]) for item in data if item[4] == 'Iris-virginica']
IndexError: invalid index

索引无效怎么办?

【问题讨论】:

  • 请不要发布到外部代码存储库,也不要询问有关外部发布代码的问题。

标签: python numpy dictionary file-io


【解决方案1】:

为此使用熊猫

import pandas as pd

df = pd.read_csv('data.txt',
                 delimiter=', ',
                 names=['length', 'width', 'distance', 'strength', 'label'])

output = {}
for label in ['FAA', 'FXX', 'FCA']:
    output[label] = df[df['label'] == label].copy().drop('label', 1).as_matrix()

【讨论】:

  • 嗯。有没有办法不使用熊猫来做到这一点?
  • @cparks10 如果你使用 numpy,为什么不使用 pandas?
  • @cparks10 当然可以,但那样会更痛苦。
【解决方案2】:

您可以使用 CSV 阅读器和 itertools 做到这一点:

from operator import itemgetter
import csv, itertools
# Create a reader
with open('data.txt') as infile:
    rdr = csv.reader(infile)
    # Group the rows by the last column
    data = itertools.groupby(sorted(rdr, key=itemgetter(-1)), key=itemgetter(-1))
# Build a dictionary
dict((key.strip(), [value[:-1] for value in values]) for key,values in data)
#{'FXX': [['.2.', ' .3', ' .5.', ' .2'], ['.5.', ' .3', ' .2 ', ' .9']], 
# 'FCA': [['.3', ' .3', ' .9', ' .3']], 
# 'FAA': [['.5', ' .3', ' .2', ' .1']]}

你也可以对 pandas 做同样的事情:

import pandas as pd
# Create a dataframe; note how the regular expression cleanses whitespaces
df = pd.read_csv('data.txt', header=None, delimiter='\s*,\s*')
# Group rows by the last column
df.groupby(4).apply(lambda x: x.iloc[:,:-1].values.tolist()).to_dict()

请注意,pandas 解决方案要短一些。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多