Using anaconda distribution, Python 3.61 and using Jupyter notebook for Scipy/Numpy. I can use the print(' blah {} '.format(x)) to format numbers but if I iterate over a nparray I get an error.
# test of formatting
'{:+f}; {:+f}'.format(3.14, -3.14) # show it always
example stolen from the Python 3.6 manual section 6.1.3.2 Here and I get the expected response. So I know that it isn't that I've forgotten to import something i.e. it is built in.
if I do this:
C_sense = C_pixel + C_stray
print('Capacitance of node')
for x, y in np.nditer([Names,C_sense]):
print('The {} has C ={} [F]'.format(x,y))
I get output
Capacitance of node
The 551/751 has C =8.339999999999999e-14 [F]
The 554 has C =3.036e-13 [F]
The 511 has C =1.0376e-12 [F]
But if I do this:
# now with formatting
C_sense = C_pixel + C_stray
print('Capacitance of node')
for x, y in np.nditer([Names,C_sense]):
print('The {} has C ={:.3f} [F]'.format(x,y))
I get the following error:
TypeError Traceback (most recent call last)
<ipython-input-9-321e0b5edb03> in <module>()
3 print('Capacitance of node')
4 for x, y in np.nditer([Names,C_sense]):
----> 5 print('The {} has C ={:.3f} [F]'.format(x,y))
TypeError: unsupported format string passed to numpy.ndarray.__format__
I've attached a screen shot of my Jupyter notebook to show context of this code.
The error is clearly coming from the formatter, not knowing what to do with the numpy iterable you get from np.nditer.
Does the following work?
for x,y in zip(Names,C_sense):
print('The {} has C ={:.3f} [F]'.format(x,y))
Related
In Tensorflow 2.2, how do I take the output from tf.encode_jpeg() (which is a tensor of type string) and convert it into bytes that would be accepted as input by tf.train.BytesList(value=[xxx])? Eventually, I want to add this to a TFRecord. When I try running some basic code (shown below in the error), I get the following error:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-25-0a8dec1885d5> in <module>
4 x = np.array([[[1],[2]],[[3],[4]]], dtype=np.uint8)
5 x = tf.io.encode_jpeg(x)
----> 6 x = tf.train.BytesList(value=[x])
7
TypeError: <tf.Tensor: shape=(), dtype=string,
numpy=b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x01,\x01,\x
has type tensorflow.python.framework.ops.EagerTensor, but expected one of: bytes
I've already tried using tf.compat.as_bytes to convert the tensor to bytes, but that just creates a different error.
P.S. Is it foolish to combine tf.encode_jpeg() and tf.train.BytesList()?
Use tf.io.serialize_tensor(image) to convert to bytes.
if isinstance(value, type(tf.constant(0))): #<-Add this.
value = value.numpy() #<-Add this. BytesList won't unpack a string from an EagerTensor.
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
I googled this question extensively and I can't figure out what's wrong. I keep getting:
"TypeError: '>' not supported between instances of 'numpy.ndarray' and 'int'".
I searched it and the websites led me to download a package and that still didn't solve my issue. My code looks as follows:
result=[]
FracPos = np.array(result)
for x in lines:
result.append(x.split())
TotalCells = np.array(result)[:,2]
print(type(TotalCells))
print(type(FracPos))
FracPos = np.sum((TotalCells)>0)
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-0972db6a45c4> in <module>
17 TotalCells = np.array(result)[:,2]
18 print(type(TotalCells))
---> 19 FracPos = np.sum((TotalCells)>0)
TypeError: '>' not supported between instances of 'numpy.ndarray' and 'int'
I can't figure out why I get the error at the last line and how to change it. I am very new to Python so I'm sure I'm missing something obvious, but the other questions like this are about nympy.ndarray and strings or lists which I understand why you can't compare.
It is because result is a list containing str objects. If you only have numbers in your array, then do:
result = [float(x) for x in result]
TotalCells = ...
Then, in order to get the sum of positive elements, you would have to do:
FracPos = np.sum(TotalCells[TotalCells > 0])
The line you wrote counts the number of postiive elements, it does not sum them.
I am using PyLaTex to create a pdf document. I'm facing some issues with compilers.
I am running my program on MacOS-High Sierra, and have installed basic version of MacTeX Mactex Download and latexmk is also installed using
sudo tlmgr install latexmk
For the following starter code, I'm getting error in compilers loop. Here's the error log attached after code.
import numpy as np
from pylatex import Document, Section, Subsection, Tabular, Math, TikZ, Axis, \
Plot, Figure, Matrix, Alignat
from pylatex.utils import italic
import os
if __name__ == '__main__':
# image_filename = os.path.join(os.path.dirname(__file__), 'kitten.jpg')
geometry_options = {"tmargin": "1cm", "lmargin": "10cm"}
doc = Document(geometry_options=geometry_options)
with doc.create(Section('The simple stuff')):
doc.append('Some regular text and some')
doc.append(italic('italic text. '))
doc.append('\nAlso some crazy characters: $&#{}')
with doc.create(Subsection('Math that is incorrect')):
doc.append(Math(data=['2*3', '=', 9]))
with doc.create(Subsection('Table of something')):
with doc.create(Tabular('rc|cl')) as table:
table.add_hline()
table.add_row((1, 2, 3, 4))
table.add_hline(1, 2)
table.add_empty_row()
table.add_row((4, 5, 6, 7))
doc.generate_pdf('full', clean_tex=False, compiler_args='--latexmk')
Error code:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-dbe7f407e095> in <module>()
27
28
---> 29 doc.generate_pdf('full', clean_tex=False, compiler_args='--latexmk')
~/anaconda3/lib/python3.6/site-packages/pylatex/document.py in generate_pdf(self, filepath, clean, clean_tex, compiler, compiler_args, silent)
227
228 for compiler, arguments in compilers:
--> 229 command = [compiler] + arguments + compiler_args + main_arguments
230
231 try:
TypeError: can only concatenate list (not "str") to list
Please help me understand the error and fix the same
Regards,
Looks like a confusion between the compiler keyword argument, which accepts a string and compiler_args which accepts a list.
Maybe something like this is what you're after:
doc.generate_pdf('full', clean_tex=False, compiler='latexmk', compiler_args=['-c'])
I'm learning SymPy now. Here is the problem I got:
x = symbols('x',real=True)
h = symbols('h',real=True)
f = symbols('f',cls=Function)
sym_dexpr = f_diff.subs(f(x), x*exp(-x**2)).doit()
f_diff = f(x).diff(x,1)
expr_diff = as_finite_diff(f_diff, [x, x-h,x-2*h,x-3*h])
w=Wild('w')
c=Wild('c')
patterns = [arg.match(c*f(w)) for arg in expr_diff.args]
coefficients = [t[c] for t in sorted(patterns, key=lambda t:t[w])]
print(coefficients)
But I got following error:
TypeError Traceback (most recent call
last) in ()
----> 1 coefficients = [t[c] for t in sorted(patterns, key=lambda t:t[w])]
2 print(coefficients)
C:\Program Files\Anaconda3\lib\site-packages\sympy\core\relational.py
in nonzero(self)
193
194 def nonzero(self):
--> 195 raise TypeError("cannot determine truth value of Relational")
196
197 bool = nonzero
TypeError: cannot determine truth value of Relational
I am using Windows 7, Python 3.5.2 and Anaconda 3.
Thank you.
The problem is the sort you perform on patterns.
sorted(patterns, key=lambda t:t[w]) attempts to return patterns sorted by every item's value for the key w, yet these values can not be compared with each other.
Why is that? because they are "relational" values, means they depend on the values of the variable in them. Lets check:
>>> [t[w] for t in patterns]
[-h + x, -3*h + x, -2*h + x, x]
Is -h + x greater than -3*h + x or the other way around? well, that depends on what h and x are, and since SymPy can't determine the order of these values, you get an error.
I have the following python code:
text = "this’s a sent tokenize test. this is sent two. is this sent three? sent 4 is cool! Now it’s your turn."
from nltk.tokenize import sent_tokenize
sent_tokenize_list = sent_tokenize(text)
import numpy as np
lenDoc=len(sent_tokenize_list)
features={'position','rate'}
score = np.empty((lenDoc, 2), dtype=object)
score=[[0 for x in range(sent_tokenize_list)] for y in range(features)]
for i,sentence in enumerate(sent_tokenize_list):
score[i,features].append((lenDoc-i)/lenDoc)
But it results in the following error:
TypeError Traceback (most recent call last) <ipython-input-27-c53da2b2ab02> in <module>()
13
14
---> 15 score=[[0 for x in range(sent_tokenize_list)] for y in range(features)]
16 for i,sentence in enumerate(sent_tokenize_list):
17 score[i,features].append((lenDoc-i)/lenDoc)
TypeError: 'set' object cannot be interpreted as an integer
range() takes int values. features is a set so it throws an error. you made the same mistake with range(sent_tokenize_list). sent_tokenize_list is a list value not an int.
If you want x and y to be indexes of features and sent_tokenize_list then you have to use this: score=[[0 for x in range(len(sent_tokenize_list))] for y in range(len(features))]
But if you want x and y to be values of features and sent_tokenize_list then you have to remove range() from that line.