Return an array of a number and its square in python

Viewed 96

How do I create an array of 1:100 numbers that contains the number and its square?

The function would return the result of in python:

x1= np.array([[1,1],
        [2,4],
        [3,9],
        [4,16],
        [5,25]])
3 Answers

I'd prefer arange and c_:

nums = np.arange(1, 101)
np.c_[nums, nums ** 2]

Try this:

import numpy as np

result = np.asarray([[x,x*x] for x in range(1, 101)])

We can use np.arange to generate numbers from 1 to 100. And np.power to squaring here we use np.power which gives more flexibility. Then use np.column_stack to weave them together.

nums = np.arange(1, 101)
np.column_stack((nums, np.power(nums, 2)))
Related