简体   繁体   English

在循环中创建列表列表

[英]Creating list of lists in a loop

I am attempting to create a list lists in a for loop from 2 dataframes df3 and df4 我正在尝试从2个数据帧df3和df4的for循环中创建列表列表

df3 = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
df4 = pd.DataFrame(np.random.randn(100, 2), columns=list('EF'))

l=[]
for i in range(len(df3)-2):
    s=df3[i:i+2].values.tolist()
    s.append(df4.iloc[i+2,1]) #this is what one element looks like and works
    l.append(s) 

The output I'm getting is 我得到的输出是

[[[[[[[[[''],
    [[[-1.6901730393462748,
       0.9398299757220133,
       0.5402878560205543,
       -0.2355701586445652],
      …..  2.300820924304919]]

The output I'm looking for is 我正在寻找的输出是

[[[[-1.6901730393462748,
       0.9398299757220133,
       0.5402878560205543,
       -0.2355701586445652],
      [1.789968968313937,
       0.3792557248306339,
       0.5701432920348918,
       1.3781227005819763]],
     1.087047297584572]],
   [[[1.789968968313937,
      0.3792557248306339,
      0.5701432920348918,
      1.3781227005819763], 
and so on.]]]]

I haven't found a thread that is applicable, if there is one, please point me in the right direction. 我没有找到合适的线程,如果有,请指出正确的方向。

I am only fixing your code here, you have lot of problems in your code , for example , for loop should with range not int , and ix will no longer work I am using iloc replace it and list should using append 我只是在这里修复您的代码,您的代码中有很多问题,例如,for循环的range应该不是int ,并且ix将不再起作用我正在使用iloc替换它, list应该使用append

l=[]
for i in range(len(df3)-2):
    s=df3[i:i+2].values.tolist()
    s.append(df4.iloc[i+2,1]) #this is what one element looks like and works
    l.append(s) # this is intended to create a list of all the elements

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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