Creating new array in for loop (Python)

我们两清 提交于 2020-06-25 06:49:30

问题


I'm preparing a data set to run in the program rpy (R, which runs in Python) for statistical analysis. It looks like this:

data = [[0, 1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0, 0, 0], 
[0, 1, 1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[0, 0, 1, 1, , 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0, 0, 0], 
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0]]   

For me to use this data, I need to isolate the dependent variable (y) from the independent ones (x). I need to create a new list for each column for year as such:

y = data[:,9]
x1 = data[:,0]
x2 = data[:,1]
x3 = data[:,2]
x4 = data[:,3]
x5 = data[:,4]
x6 = data[:,5]
x7 = data[:,6]
x8 = data[:,7]
x9 = data[:,8]
x10 = data[:,9]

Suppose my data has 67 columns. Is there a way to loop through all the columns and create each one automatically without having to type out all of them? I do not want to hard code all the arrays up to 67.

Something along the lines of this, but it doesn't work:

i=0
for d in data:
    "x%d"%i = data[:,i-1]
    i+=1

This is the rest of the code:

rpy.set_default_mode(rpy.NO_CONVERSION)
linear_model = rpy.r.lm(rpy.r("y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10"), data = rpy.r.data_frame(x1=x1,x2=x2,x3=x3,x4=x4,x5=x5,x6=x6,x7=x7,x8=x8,x9=x9,x10=x10,y=y))
rpy.set_default_mode(rpy.BASIC_CONVERSION)
print linear_model.as_py()['coefficients']
summary = rpy.r.summary(linear_model)

回答1:


Why not try something like this to transpose the columns:

x = []

for d in xrange(0,66):
    x.append(data[:,d])

Unless it's absolutely essential that there is a separate data structure for each item, although I don't know why you would need separate data strucures...

EDIT: If not here's something that should work precisely the way you described:

for d in xrange(1,68):
    exec 'x%s = data[:,%s]' %(d,d-1)



回答2:


As you show a little bit of the rpy code, I thought that I could show how it would look like with rpy2.

# build a DataFrame
from rpy2.robjects.vectors import IntVector
d = dict(('x%i' % (i+1), IntVector(data[:, i]) for i in range(68) if i != 9)
d['y'] = data[:, 9]
from rpy2.robjects.vectors import DataFrame
dataf = DataFrame(d)
del(d) # dictionary no longer needed

# import R's stats package
from rpy2.robjects.packages import importr
stats = importr('stats')

# fit model
dep_var = 'y'
formula = '%s ~ %s ' % (dep_var, '+'.join(x for x in dataf.names if x != dep_var))
linear_model = stats.lm(formula, data = dataf) 


来源:https://stackoverflow.com/questions/14327548/creating-new-array-in-for-loop-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!