Home > database >  Return an array of a number and its square in python
Return an array of a number and its square in python

Time:10-31

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]])

CodePudding user response:

Try this:

import numpy as np

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

CodePudding user response:

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)))

CodePudding user response:

I'd prefer arange and c_:

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