0

I am a bit new to NumPy and Python. I have string text in the format like below:

lat0 37.792480, lon0 -122.397450
lat1 39.792480, lon1 -132.397450

...

I want to load the only floating numbers to my array as 2d array with 0th column as lat and 1st column as lan. What should be the pattern for this kind of data loading.

2 Answers 2

1

Since you mention numpy, this is one way:

import numpy as np

lst = ['lat0 37.792480, lon0 -122.397450',
       'lat1 39.792480, lon1 -132.397450']

res = np.array([[i.rsplit(None, 1)[-1] for i in x.split(',')] for x in lst]).astype(float)

# array([[  37.79248, -122.39745],
#        [  39.79248, -132.39745]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I didn't think of this way, I was thinking in the direction of np.loadtxt and all
0

If you have string mytext.txt like so,

lat0 37.792480, lon0 -122.397450

lat1 39.792480, lon1 -132.397450

You can read input from a text file into your python program run.py likepython run.py < mytext.txt

You can also open and read your textfile in python like

with open('mytext.txt') as f:
    text = f.readlines()

Because i've recently been using python 3's input(), I'll explain using that option.

However you need to know the number of lines in mytext.txt, because input() is line by line.

Apparently in unix you can run wc -l < mytext.txt for # of lines.

import numpy as np

coordinates = np.zeros([numlines, numlines])  # Instantiate array.

for i in range(numlines):
    data = input()  # How we can read text from standard input.
    data = data.split(',')  # Split by comma, giving ['latN float1', ' lonN float2']  

    lat = data[0].split()[1]  # Isolate 'latN float1', split by ' ', get 'float1'.
    lon = data[1].split()[1]  # Isolate 'lonN float2', split by ' ', get 'float2'.

    lat = float(lat)  # Convert from string to float.
    lon = float(lon)  # Convert from string to float.

    coordinates[i] = lat, lon  # Replace zeros with lat, lon

You'll have a numpy array: array([[lat0, lon0], [lat1, lon1]...,[, latN, lonN]])

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.