在for循环中创建新数组(Python)

ono*_*ono 1 python arrays rpy2

我正在准备一个要在程序rpy(R,在Python中运行)中运行的数据集,以进行统计分析。看起来像这样:

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]]   
Run Code Online (Sandbox Code Playgroud)

为了使用此数据,我需要将因变量(y)与自变量(x)隔离开。我需要为年份的每一列创建一个新列表,如下所示:

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]
Run Code Online (Sandbox Code Playgroud)

假设我的数据有67列。有没有一种方法可以遍历所有列并自动创建每个列而不必键入所有列?我不想将所有数组硬编码为67。

与此类似,但不起作用:

i=0
for d in data:
    "x%d"%i = data[:,i-1]
    i+=1
Run Code Online (Sandbox Code Playgroud)

这是其余的代码:

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)
Run Code Online (Sandbox Code Playgroud)

Mas*_*oda 5

为什么不尝试这样的方法来转置列:

x = []

for d in xrange(0,66):
    x.append(data[:,d])
Run Code Online (Sandbox Code Playgroud)

除非绝对必要的是每个项目都有单独的数据结构,但我不知道为什么您需要单独的数据结构...

编辑:如果不是,这应该按照您描述的方式工作:

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