Hani Goc
Hani Goc

Reputation: 2441

how to load a libsvm file using python ( fill missing values)

Let v = [10:1, 15:2, 20:3]; (i = [0, 1, 2] the indices of the values in the list)


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

thank you pencil and paper.

Upvotes: 0

Views: 235

Answers (1)

enthus1ast
enthus1ast

Reputation: 2109

there are some unclear points in your question but here is a possible solution

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

Upvotes: 1

Related Questions