1

I am trying to pass a column of numbers to a Python script to then convert into a numpy array.

input.txt

42
42.4
43.5153
44

Bash Code

python script.py ${input}

Python Script

#!/usr/bin/env python3
import sys
import numpy

in = sys.argv[1]

in_out = np.array([float(in)])
print "Inputs:" in_out

sys.exit()

Python Error

Traceback (most recent call last):
  File "script.py", line 8, in <module>
    in_out = np.array([float(in)])
ValueError: invalid literal for float(): 42
2
  • What is in_in and ${input}? I presume you need to read the file instead of reading and parsing the filename as a float Commented Nov 18, 2019 at 10:29
  • Please excuse my typo(s). I have edited the original question Commented Nov 18, 2019 at 10:34

3 Answers 3

1
import numpy as np


with open('input.txt') as input_file:
    data = np.array([float(line.strip()) for line in input_file])

You need to cast all values as float so that numpy is only storing one datatype in the array.

If you want to supply the file as an argument, you can do the following:

import numpy as np
import sys


file_name = sys.argv[1]
with open(file_name) as input_file:
    data = np.array([float(line.strip()) for line in input_file])
Sign up to request clarification or add additional context in comments.

Comments

1

I think the problem is that your in variable (which can't be a variable in Python, but we'll go with that) is a string of all values. So you need to split it and apply float to each individually:

np.array(list(map(float, in.split())))

But I'd suggest reading an input.txt file directly from Python.

Comments

1

Use np.loadtxt

Ex:

import numpy as np

in_out = np.loadtxt(filename, dtype=float)
print(in_out)

Output:

[42.     42.4    43.5153 44.    ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.