python创建数组并运行_在for循环中创建新数组(Python)

1586010002-jmsa.png

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)

解决方案

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值