在python中每次迭代for循环后为数据创建新列

时间:2016-06-07 00:09:09

标签: python numpy

使用下一个代码我想将结果放在m

的不同值的列中
import numpy as np 
for m in np.arange(0, 4, 1):
   for n in np.arange(1, 4, 1):
       coef = 2*m/n
       print coef

结果如下:

0
0
0
2
1
0
4
2
1
6
3
2

我想得到这个

0 0 0
2 1 0
4 2 1
6 3 2

或直接获取列,这是行的值的总和

0 + 0 + 0 = 0
2 + 1 + 0 = 3
4 + 2 + 1 = 7
6 + 3 + 2 = 11

3 个答案:

答案 0 :(得分:2)

在打印后添加一个逗号,这样我们就不会在内循环外添加换行符和另一个打印来分隔每一行:

NODE                     EXPLANATION
----------------------------------------------------------------------
  ^                        the beginning of a "line"
----------------------------------------------------------------------
  (?:                      group, but do not capture (1 times):
----------------------------------------------------------------------
    "                        '"'
----------------------------------------------------------------------
    [^"]*                    any character except: '"' (0 or more
                             times (matching the most amount
                             possible))
----------------------------------------------------------------------
    ",                       '",'
----------------------------------------------------------------------
  ){1}                     end of grouping
----------------------------------------------------------------------
  "                        '"'
----------------------------------------------------------------------
  (                        group and capture to \1:
----------------------------------------------------------------------
    [^"]*                    any character except: '"' (0 or more
                             times (matching the most amount
                             possible))
----------------------------------------------------------------------
  )                        end of \1
----------------------------------------------------------------------
  "                        '"'
----------------------------------------------------------------------

哪个会给你:

import numpy as np
for m in np.arange(0, 4, 1):
   for n in np.arange(1, 4, 1):
       coef = 2*m/n
       print coef,
   print 

或使用print作为函数:

0 0 0
2 1 0
4 2 1
6 3 2

为了得到总和,我们可以在内循环中使用generator expression使用内置的 sum 函数:

from __future__ import print_function


import numpy as np

for m in np.arange(0, 4, 1):
    print(*(2 * m / n for n in np.arange(1, 4, 1)))

哪个会给你:

import numpy as np

for m in np.arange(0, 4, 1):
    print(sum(2 * m / n for n in np.arange(1, 4, 1)))

为了完整性,第一个示例的等效print_function代码将设置为0 3 7 11

end=" "

答案 1 :(得分:1)

正如我所理解的那样,你想要创建一个新的数组,其列就像你指定的那样。

import numpy as np 
a = np.zeros([3,4])
for m in np.arange(0, 4, 1):
    col = []
    for n in np.arange(1, 4, 1):
        coef = int(2*m/n)
        col.append(coef)
    a[:, int(m)] = col

print(a.T)

答案 2 :(得分:1)

使用循环执行的操作与range一样有效。无需使用numpy

但如果这是学习numpy的练习,我建议采用不同的方法。

直接从范围制作数组。 //是整数除法。

In [99]: A=2*np.arange(4)[:,None]//np.arange(1,4)

In [100]: A
Out[100]: 
array([[0, 0, 0],
       [2, 1, 0],
       [4, 2, 1],
       [6, 3, 2]], dtype=int32)

您可以使用数组方法对列进行求和:

In [101]: A.sum(axis=1)
Out[101]: array([ 0,  3,  7, 11], dtype=int32)

要获得一个不错的格式,没有括号等,请创建一个行格式化字符串:

In [102]: fmt = '%d + %d + %d = %d'               

In [103]: for row in A:                           
    print(fmt%(tuple(row)+(row.sum(),))) 
   .....:     
0 + 0 + 0 = 0
2 + 1 + 0 = 3
4 + 2 + 1 = 7
6 + 3 + 2 = 11

(打印的函数形式在Python3中是正常的,在2.7中可用)

我本可以使用此变体通过np.savetxt将其写入文件。

In [104]: A.sum(axis=1,keepdims=True)  # sum in column array shape
Out[104]: 
array([[ 0],
       [ 3],
       [ 7],
       [11]], dtype=int32)

In [105]: A1 = np.concatenate((A, A.sum(axis=1,keepdims=True)),axis=1)

In [106]: A1     # the values and sum in one array
Out[106]: 
array([[ 0,  0,  0,  0],
       [ 2,  1,  0,  3],
       [ 4,  2,  1,  7],
       [ 6,  3,  2, 11]], dtype=int32)

In [107]: np.savetxt('test.txt',A1,fmt=fmt)

In [108]: cat test.txt    # look at the resulting file
0 + 0 + 0 = 0
2 + 1 + 0 = 3
4 + 2 + 1 = 7
6 + 3 + 2 = 11

没有numpy的Python2.7版本:

>>> for m in range(4):
...     row = [2*m/n for n in range(1,4)]
...     fmt = '%d + %d + %d = %d'
...     print fmt%(tuple(row)+(sum(row),))
... 
0 + 0 + 0 = 0
2 + 1 + 0 = 3
4 + 2 + 1 = 7
6 + 3 + 2 = 11