Suppose we need to convert array members to integers in an old-fashioned way via a for loop (not as x.astype(int)) :

import numpy as np

x = np.array([[ 2016., 1., 1.], [ 2016., 12., 31.]])
x
array([[  2.01600000e+03,   1.00000000e+00,   1.00000000e+00],
       [  2.01600000e+03,   1.20000000e+01,   3.10000000e+01]])

In a for loop this would have been achieved as:

y = []
for element in x:
    for el in element:
        y.append(int(el))
y
[2016, 1, 1, 2016, 12, 31]

The same could have been achieved via a nested list comprehension:

[int(el) for element in x for el in element]
[2016, 1, 1, 2016, 12, 31]

NOTE:

  1. Nested loops are entered in the same order, as they appear in an usual loop:
    • first, outer loop
    • second, inner loop
  2. Alternative explanation: the loops are executed from left to right. As the first leftmost loop entered, the Python interpreter has element value and proceeds to the second loop. As the second loop entered, it runs until all el of element exhausted. If the order is reversed, there will be an error

An alternative nested list comprehension:

[[int(el) for el in element] for element in x]
[[2016, 1, 1], [2016, 12, 31]]
Write a comment:

*

Your email address will not be published.

© 2014 In R we trust.
Top
Follow us: