How to take user input in a numpy array

43,931

Solution 1

n, m = map(int, input().split()) # taking number of rows and column
array = numpy.array([input().strip().split() for _ in range(n)], int)

Solution 2

Please try this

from numpy import *
arr = array([])
n = int(input("Enter the number of values you want:  "))

for i in range(n):
    v = input("Element:  ")
    arr = append(arr, v)
print(arr)

Solution 3

You take input as list and then put it into a numpy array.

import numpy
op= list(map(int,input().split()))
op = numpy.asarray(op)

Solution 4

numpy.append does not work like this, the array is missing to append to.

Better, build a normal list and convert it to a numpy array afterwards:

import numpy

my_array = []
a = int(input("Size of array:"))
for i in range(a):
    my_array.append(float(input("Element:")))
my_array = numpy.array(my_array)
print(numpy.floor(my_array))

Solution 5

Using List Comprehension

a=int(input()
b=[int(j) for j in input().split()]
print(np.array(b))
Share:
43,931
Kaushal Raj
Author by

Kaushal Raj

I am a code blooded developer!

Updated on August 20, 2020

Comments

  • Kaushal Raj
    Kaushal Raj over 3 years
    import numpy
    
    my_array = numpy.array([])
    a=int(input("Size of array:"))
    for i in range(a):
        x=float(input("Element:"))
        numpy.append(x)
    
    print(numpy.floor(my_array))
    
    • Admin
      Admin over 5 years
      What is your question exactly?
    • Kaushal Raj
      Kaushal Raj over 5 years
      I am trying to solve hackerrank.com question.Here is the link hackerrank.com/challenges/floor-ceil-and-rint/forum .I have found a way to input but the output format is wrong.check my code. import numpy as np A = np.array(input().split(' '),float) print(np.floor(A)) print(np.ceil(A)) print(np.rint(A))
    • MPA
      MPA over 5 years
      Please update your post with a proper question/problem and code formatting, so that others may benefit from reading it.
    • brutuscat
      brutuscat over 3 years
      The question asks how can one read an input from the user to enter the "size of the array" and other parameters. This has been asked and answered before here: stackoverflow.com/a/38670261/53720. Please if you have other problems be more specific about what sort of error you are dealing with.
    • brutuscat
      brutuscat over 3 years
      Does this answer your question? How do you read from stdin?
  • Helper
    Helper over 3 years
    Have you missed the round bracket? a=int(input() ?
  • sree
    sree over 3 years
    oh yes.. silly mistakes,