[英]how to load a libsvm file using python ( fill missing values)
令v = [10:1,15:2,20:3]; (i = [0,1,2]列表中值的索引)
n = 10 - (i + 1) = 10 - (0 + 1) = 9 ==> newV = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
n = 15 - (9 + i + 1) = 15 - (9 + 1 + 1) = 4 ==> newV =[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2]
n = 20 - ( 9 + 4 + 2 + 1 ) = 20 - 16 = 4 ==> newV =[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3]
finalV = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3]`
if __name__ == '__main__':
v = ['1:1', '15:2', '30:3']
previous_Idx = []
newV = []
for i in range(0, len(v)):
idx = int(v[i].split(':')[0])
val = float(v[i].split(':')[-1])
n = idx - (sum(previous_Idx) + i + 1)
for _ in range(n):
newV.append(0)
previous_Idx.append(n)
newV.append(val)
print newV
谢谢你的铅笔和纸。
您的问题中有一些不清楚的地方,但这是可能的解决方案
for line in open("file.txt", 'r').readlines():
line = line.strip().split(" ")
lineName = line.pop(0)
arr = [0.0] * int(line[-1].split(":")[0]) # fills the array with zeros
for element in line:
index,value = element.split(":")
arr[int(index)-1] = float(value)
print lineName + " " + " ".join(map(str, arr)) # /questions/6507431
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.