我正在尝试获取交易数据列表并将其汇总为二维 numpy 数组。我的数据如下所示:
person, product, date, val
A, x, 1/1/2013, 10
A, x, 1/10/2013, 10
B, x, 1/2/2013, 20
B, y, 1/4/2013, 15
A, y, 1/8/2013, 20
C, z, 2/12/2013, 40
我需要将输出放入一个二维数组中,每个人作为行,产品作为列。将删除日期,并对值求和。
输出将如下所示:
[[20, 20, 0],[20, 15, 0],[0, 0, 40]]
这是我拥有的功能,但它真的很慢(我有 110,000,000 条记录):
import numpy as np
from collections import defaultdict
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
import pandas as pd
from scipy import sparse
import os
import assoc
#read in data to a dict object - sums scripts by tuple (doc, drug)
dictObj = {}
rawData = 'subset.txt'
with open(rawData) as infile:
for line in infile:
parts = line.split(',')
key = (parts[0],parts[1])
val = float(parts[3])
if key in dictObj:
dictObj[key] += val
else:
dictObj[key] = val
infile.close()
print "stage 1 done"
#get the number of doctors and the number of drugs
keys = dictObj.keys()
docs = list(set([x[0] for x in keys]))
drugs = sorted(list(set([x[1] for x in keys])))
#read through the dict and build out a 2d numpy array
docC = 0
mat = np.empty([len(docs),len(drugs)])
for doc in docs:
drugC = 0
for drug in drugs:
key = (doc,drug)
if key in dictObj:
mat[(docC,drugC)] = dictObj[(key)]
else:
mat[(docC,drugC)] = 0
drugC += 1
docC+=1
我之前发布了一个类似的帖子(此处 - Transformation of transactions to numpy array),每个人都回应说 Pandas 是可行的方法,但我终究无法将 Pandas 输出转换为正确的格式。我无法将 Pandas dataFrame 传递给我拥有的 kmeans 或 apriori 算法,并且无论我如何安排 dataFrame,df.values 都会让我进入 multiIndex 系列(它简化为 1 个长数组!)。任何指针将不胜感激!
最佳答案
我可能会做类似的事情
>>> df = pd.read_csv("trans.csv", skipinitialspace=True)
>>> w = df.groupby(["person", "product"])["val"].sum().reset_index()
>>> w
person product val
0 A x 20
1 A y 20
2 B x 20
3 B y 15
4 C z 40
>>> w.pivot("person", "product").fillna(0)
val
product x y z
person
A 20 20 0
B 20 15 0
C 0 0 40
>>> w.pivot("person", "product").fillna(0).values
array([[ 20., 20., 0.],
[ 20., 15., 0.],
[ 0., 0., 40.]])
哪个 IIUC 是您要查找的二维数组。请注意,您不必一次将整个文件读入内存,您可以使用 chunksize
参数(请参阅 the docs here )并逐个累积您的表。
关于python - 将文件加载到 2d numpy 数组中的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20184634/