在for循环中创建新数组(Python) [英] Creating new array in for loop (Python)

查看:2201
本文介绍了在for循环中创建新数组(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]]   

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

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]

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

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

这是其余的代码:

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)


推荐答案

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

Why not try something like this to transpose the columns:

x = []

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

除非绝对必要,否则必须有一个单独的数据结构r每个项目,尽管我不知道为什么您需要单独的数据结构...

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...

编辑:如果没有,那么这应该与您描述的方式完全一样:

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)

这篇关于在for循环中创建新数组(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆