简体   繁体   中英

Adding list elements to empty list

I'm trying to take the first element of a list created within a loop, and add it to a empty list.

Easy right? But my code is not working...

The empty list is index

The list I'm pulling the numbers from is data

import pandas as pd
import numpy as np

ff = open("/Users/me/Documents/ff_monthly.txt", "r")
data = list(ff)

f = []
index = []

for i in range (1, len(data)):

    t = data[i].split()
    index.append(int(t[0]))

    for j in range(1, 5):

        k = float(t[j])
        f.append(k / 100)

n = len(f)

f1 = np.reshape(f,[n / 4, 4])

ff = pd.DataFrame(f1, index= index, columns = ['Mkt_Rf','SMB','HML','Rf'])
ff.to_pickle("ffMonthly.pickle")
print ff.head()

When I create the list t in the loop, I've checked to see if it is being created correctly.

len(t) =   5

print t[0] =  192607

print t = ['192607', '2.95', '-2.54', '-2.65', '0.22']

The code:

index.append(t[0])

It should add the 1st element of the list t to index ... correct?

However, I get this error:

IndexError: list index out of range

What am I missing here?

Edit:

Posted the entire code above.

Here are the first few rows of "ff_monthly.txt"

          Mkt-RF   SMB     HML     RF
192607    2.95   -2.54   -2.65    0.22
192608    2.64   -1.22    4.25    0.25
192609    0.37   -1.21   -0.39    0.23
192610   -3.24   -0.09    0.26    0.32
192611    2.55   -0.15   -0.54    0.31
192612    2.62   -0.13   -0.08    0.28

Check if there is an empty line in your txt file.

Because "".split() will return an empty list which will fail the t[0]

Quick and uggly:

for i in range (1, len(data)):
   t = data[i].split()
   if t:
       index.append(int(t[0]))
       for j in range(1, 5):
          k = float(t[j])
          f.append(k / 100)

Reason:

You have empty lines at the end of the file. Reproduced locally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM