using Python 3.7, how to use of numpy complex with an array of values - python-3.x

I am new to Python, so I apologize ahead of time if this question is too basic.
Say I have a complex value 50+ j(10 w), where w is an array of frequencies, for example,
import numpy as np
w=2*np.pi*np.linspace(1800e6,2400e6,100)
how do I use np.complex to calculate the complex value for each value in the w array (or any other way to accomplish this)?
In Matlab, I could do
z = 50 + i.*w.*10
(although I don't think I would need to since everything else is a scalar in the equation, but this helps show what I want to do --element by element multiplication).
Anyway, when I try:
z=np.complex(50,10*w)
I get the following error:
Traceback (most recent call last):
File "<ipython-input-14-a78f7e2cf118>", line 1, in <module>
z=np.complex(50,10*w)
TypeError: only size-1 arrays can be converted to Python scalars'
I appreciate any help. Thank you.

Related

Getting TypeError: list indices must be integers when using list[:,colIndex] to get column data as list

I have a 2D list (a list of lists) and am trying to use the notation list[:,colIndex] to pull out a single column's data into another list, but I'm getting a TypeError: list indices must be integers error.
for example:
lst = [[1,2,3],[10,12,13]]
lst[:,0]
Returns:
Traceback (most recent call last):
File "<input>", line 2, in <module>
TypeError: list indices must be integers
I don't understand...
Edit:
Running this in Python 3.9 gives me:
TypeError: list indices must be integers or slices, not tuple
It would seem that the [:,colIndex] syntax isn't supported by lists and is available to numpy arrays only :(
However I can use: list(zip(*lst))[colIndex] instead from this answer https://stackoverflow.com/a/44360278/1733467

input text file (a double quoted string w/ %e %i sqrt z1 z2 log) into sympy or numpy or scipy for a Laurent series

Lengthy title, but I thought it might be best to be very informative...
I have very long expressions using symbols such as %i, %e, log, z1 and z2, that is sandwiched in between double quotes, e.g. something like,
"(4*z1*z2*%e^(z2^2+z1^2)*((%e^z1^2-%e^z2^2)^2*(96*%e^(13*(((-(202907687053026635*%i*sqrt(1037*sqrt(23)*%i+1463)*(log(9)*sqrt(2)*sqrt(7)*sqrt(1037*sqrt(23)*%i+....."X
(where when viewing the file in a hex editor, the last X is not an X but a hexadecimal 0A - whatever that is - don't think looking it up on an ascii chart will shed much light on it)
I'd like to try out the python/sympy/numpy/scipy/... amalgamations in lieu of other CAS-capable software, but I am having no luck finding out how to do this, at least from a consistent "package". I see snippets from a tutorial on scipy, or a snippet from numpy, etc.
I would like to take the Laurent series of an expression like above - it is exact expression devoid of floats.
Hope this is easy to understand request,
Best wishes.
edit - update Python to 3.6 - still AttributeError
So I saw some errors in converting the symbols exp, etc. into an acceptable string. This seems to work better but "ex" is still not being treated as a Sympy expression after sympify:
(py3_kernel) sbh#sbh-MacBookPro ~ $ ipython
Python 3.6.3 (default, Oct 6 2017, 08:44:35)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import sympy as s
In [2]: import numpy as np
In [3]: from numpy import *
In [4]: from sympy import *
In [5]: from sympy.utilities.lambdify import lambdify, implemented_function, lambdastr
In [6]: with open('c.txt', 'r') as myfile:
...: d=myfile.read().replace('\n', '').replace('%i','I').replace('%e','exp').replace('^','**
...: ').replace('exp**','exp')
...:
In [7]: d
Out[7]: '"(4*z1*z2*exp(z2**2+z1**2)*sqrt(1037*sqrt(23)*I+1463))+log(1/2)+(sqrt(-I)*z1)/(sqrt(3)*23**(1/4))"'
In [8]: z1,z2 = s.symbols('z1,z2', real=True)
In [9]: ex = s.sympify(d)
In [10]: ex
Out[10]: '(4*z1*z2*exp(z2**2+z1**2)*sqrt(1037*sqrt(23)*I+1463))+log(1/2)+(sqrt(-I)*z1)/(sqrt(3)*23**(1/4))'
In [11]: type(ex)
Out[11]: str
In [12]: ex.subs({z1:0, z2:1})
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-12-63eab202c7b1> in <module>()
----> 1 ex.subs({z1:0, z2:1})
AttributeError: 'str' object has no attribute 'subs'
numpy.loadtxt() is generally used to read tabular data from text files into Numpy arrays. It may be better to use Python to read your file into a string variable and then convert it to an Sympy expression using sympy.sympify().
Suppose I have a file cal.txt that contains a one-line string z1^2*exp(z2)*%i. The following lines would read it and convert it into a Sympy expression.
import sympy as s
with open('cal.txt', 'r') as myfile:
d=myfile.read().replace('\n', '').replace('%i',\
'I').replace('^','**').replace('"','')
z1,z2 = s.symbols('z1,z2')
ex = s.sympify(d)
ex2 = ex.subs([(z1,0),(z2,0)])
For this to work cal.txt should contain a valid Sympy expression.
Update:
I modified the content of my file cal.txt to "z1^2*exp(z2)*%i" and now I also get the same AttributeError. So we need to strip the " before and after your strings for sympify to work properly. I have modified the code above to replace('"','') double quotes to null. Hope this will work.
In the code above, if we replace the line z1,z2 = s.symbols('z1,z2') with z1,z2 = s.symbols('z1,z2', real=True), the ex2 = ex.subs([(z1,0),(z2,0)]) line will not give desired output because of the assumption we have specified on z1 and z2. So we need to be careful when specifying assumptions on our symbols when using sympify. The source of this information is "Turning strings into expressions" section of this link.

Python3: ValueError: too many values to unpack (expected 2)

Now I am reading a large number(about 1 million rows) of training data(label: 0 or 1) from txt file to practise the machine learning with scikit-learn: the data like the following data:
label data
0 xd,xw,gh
1 xg,xh,xl,xk,yh,xd
......................................
But there is error after I run my code:
Traceback (most recent call last):
X, y = get_minibatch(train_text, train_label, chunksize=1000)
ValueError: too many values to unpack (expected 2
Please give me you suggestions about this issue!
Thanks for your time and consideration!
get_minibatch(train_x, train_y, chunksize) is using yield rendering it an generator/iterator.
You are calling it like a function, expecting two arguments and unpack them.
But you are not getting two elements, you obtain one generator/iterator-object after calling. (In these cases: always print out print(type(function())). Of course this single object can't be unpacked into two.
You need to use it like an generator/iterator, e.g. in python3:
X, y = next(get_minibatch(train_text, train_label, chunksize=1000))

reading a csv file into a Networkx graph in python 3.5

I am following this tutorial: graph tutorial on my own data file. but I am getting stuck on the last bit. the code seems to throw:
(most recent call last)<ipython-input-193-7227d35394c0> in <module>()
1 for node in links: #loops through each link and changes each dictionary to a tuple so networkx can read in the information
2 edges = node.items()
----> 3 G.add_edge(*edges[0]) #takes the tuple from the list and unpacks the tuples
4
5 nx.draw(G)
TypeError: 'dict_items' object does not support indexing
is there a fix? I'm sort of stuck.
This is probably python-2 only compatible code.
In python 2, dict.items() returns a list of tuples (key, value) as opposed to dict.iteritems()
In python 3, dict.iteritems() has been removed, and dict.items() returns an iterator.
So you have to explicitly convert it to list to get access to the elements by index:
edges = list(node.items())

A simple numpy reshape function in python when making 2D array from 1D array

I had a simple question involving np.reshape. I am trying to learn how to make a 2D array from 1D array using np.reshape. I watched this tutorial that does it but I still have some questions about the tutorial..
import numpy as np
a = np.arange(8*16)
frame_length = 8
a_framed = np.reshape(a, (-1, frame_length))
print (a_framed)
Here are my questions:
Is frame_length determining the number of columns in the new 2D array? If so, why not just put the number 8 in 'a_framed'? Is it not possible to do that?
What is '-1' in 'a_framed'? What does it do? (explanation omitted in the tutorial or not sufficient for me)
Thanks!
Cece
Yes. You could. It is possible, but the example is trying to show you the functionality you ask about in question 2.
-1 is usually a wildcard in python. In this case, it's a.size/frame_length, the other dimension needed to use all of a. Change a_framed to 4 or 16 and it still works. Change it to 5 and:
Traceback (most recent call last):
File "", line 4, in <module>
a_framed = np.reshape(a, (-1, frame_length))
File ". . . fromnumeric.py", line 225, in reshape
return reshape(newshape, order=order)
ValueError: total size of new array must be unchanged
It can't fit, so numpy throws and error.

Resources