user391339
user391339

Reputation: 8775

What is the simplest way to dump this column copy of excel data into a python numpy array?

Need to do some filtering today. Since it would have taken me at least an hour in excel I decided learn how to do it in python in about 30 seconds. The hardest part is pasting the data column from excel (a string with carriage return separated values?) into python. In matlab I could do this sort of thing, but in python I suspect I need to maybe put quotations around it and use a simple \n parser or regex? Thanks for the help!

import scipy
import numpy
from scipy import signal

N=10
Fc=0.1
Fs=1.14

h=scipy.signal.firwin(N, Fc, Fs/2)

x = [23.57734807
24.6558011
23.60110497
25.6801105
24.75524862
23.70055249
23.50718232
23.56906077
22.82265193
23.78563536
21.47348066
22.15359116]

I get this error:

    24.6558011
             ^
SyntaxError: invalid syntax

Upvotes: 0

Views: 345

Answers (3)

rayryeng
rayryeng

Reputation: 104503

It looks like you're trying to represent your signal as a Python list. As such, you need to delineate each item in x by a comma if that's the case. In other words, you would need to do:

x = [23.57734807, 24.6558011, 23.60110497, 25.6801105, 24.75524862, 
     23.70055249, 23.50718232, 23.56906077, 22.82265193, 23.78563536, 
     21.47348066, 22.15359116]

In MATLAB, you don't need to place commas between each number as each element can either be comma or space delimited, but for Python lists, you need the comma.

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

I am not sure what the data inside x is but if it is a string, you can use str.split:

import numpy as np



s = """23.57734807
24.6558011
23.60110497
25.6801105
24.75524862
23.70055249
23.50718232
23.56906077
22.82265193
23.78563536
21.47348066
22.15359116
"""
x  = s.split()
print x
print np.array(x,dtype=float)

['23.57734807', '24.6558011', '23.60110497', '25.6801105', '24.75524862', '23.70055249',   '23.50718232', '23.56906077', '22.82265193', '23.78563536', '21.47348066', '22.15359116']

[ 23.57734807  24.6558011   23.60110497  25.6801105   24.75524862
23.70055249  23.50718232  23.56906077  22.82265193  23.78563536
21.47348066  22.15359116]

As per your comment that is is all a string, use str.replace and with split:

import numpy as np

x = """[23.57734807
24.6558011
23.60110497
25.6801105
24.75524862
23.70055249
23.50718232
23.56906077
22.82265193
23.78563536
21.47348066
22.15359116]
"""

 arr = np.array(x.replace("[","").replace("]","").split(),dtype=float)
 print arr

[ 23.57734807  24.6558011   23.60110497  25.6801105   24.75524862
23.70055249  23.50718232  23.56906077  22.82265193  23.78563536
21.47348066  22.15359116]

Upvotes: 2

bakkal
bakkal

Reputation: 55448

You need , commas in your list

x = [23.57734807,
24.6558011,
23.60110497,
25.6801105,
24.75524862,
23.70055249,
23.50718232,
23.56906077,
22.82265193,
23.78563536,
21.47348066,
22.15359116]

Upvotes: 1

Related Questions