Tag Archives: Python TypeError

Python TypeError: not all arguments converted during string formatting

Where?

Run the python program, and the error will appear on the line return “unknown object of% s”% value

Why?

% s means to replace the value variable with a string. However, the value is a python tuple. If the tuple cannot be directly formatted by% s and%, an error will be reported

Way?

Use format or format_ Map format string instead of%

error code

def use_type(value):
    if type(value) == int:
        return "int"
    elif type(value) == float:
        return "float"
    else:
        return "Unknow Object of %s" % value

if __name__ == '__main__':
    print(use_type(10))
    # The tuple argument is passed
    print(use_type((1, 3)))

Correcting the code

def use_type(value):
    if type(value) == int:
        return "int"
    elif type(value) == float:
        return "float"
    else:
        # format method
        return "Unknow Object of {value}".format(value=value)
        # format_map method
        # return "Unknow Object of {value}".format_map({
        #     "value": value
        # })


if __name__ == '__main__':
    print(use_type(10))
    # Passing tuple parameters
    print(use_type((1, 3)))

Python Typeerror: super() takes at least 1 argument (0 given) error in Python

Typeerror: super() takes at least 1 argument (0 given) error occurred when writing inheritance subclass

Source code (perfect to run in python3)

class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        
        self.initUI() #Interface drawing is given to the InitUi method
        
        

The reason is super ()__ init__() Function is supported in python3, which is correct, but it will cause problems in python2

If you want to inherit the construction method of the parent class in Python 2, you need to pass in the super parameter: Super (example, self)__ init__();

In python2, it should be written as follows:

class Example(QWidget):
    
    def __init__(self):
        super(Example,self).__init__()
        
        self.initUI() #Interface drawing is given to the InitUi method
         

Python TypeError: can only concatenate str (not “int”) to str

 code

def gcd(x, y):
    (x, y) = (y, x) if x > y else (x, y)
    for factor in range(x, 0, -1):
        if x % factor == 0 and y % factor == 0:
            return factor


if __name__ == '__main__':
    num1 = int(input("Please enter a positive integer: "))
    num2 = int(input("Please enter a positive integer. "))
    print("i" + gcd(num1, num2))

code error

PS G:\vscode_worksapce\vscode_python_workspace> python -u "g:\vscode_worksapce\vscode_python_workspace\test1.py"      
Please enter a positive integer: 3
Please enter a positive integer: 9
Traceback (most recent call last):
  File "g:\vscode_worksapce\vscode_python_workspace\test1.py", line 11, in <module>
    print("i" + gcd(num1, num2))
TypeError: can only concatenate str (not "int") to str

causes and solutions

reference the blog https://blog.csdn.net/feng2147685/article/details/86494905, and https://www.cnblogs.com/Jimc/p/9606112.html

is a Python string concatenation problem;

if __name__ == '__main__':
    num1 = int(input("Please enter a positive integer: "))
    num2 = int(input("Please enter a positive integer. "))
    print("i%d" % (gcd(num1, num2)) + "hahahha")

HMM…

Python TypeError: softmax() got an unexpected keyword argument ‘axis’

There are several solutions to this problem. You can lower the version of keras, for example:

pip install keras==2.1

However, there is a more convenient way. From the error, we can see that softmax does not contain the axis parameter, so we can replace the axis parameter with dim. The source code is as follows:

def softmax(x, axis=-1):
    """Softmax of a tensor.

    # Arguments
        x: A tensor or variable.
        axis: The dimension softmax would be performed on.
            The default is -1 which indicates the last dimension.

    # Returns
        A tensor.
    """
    return tf.nn.softmax(x, axis=axis)

Change to this:

def softmax(x, axis=-1):
    """Softmax of a tensor.

    # Arguments
        x: A tensor or variable.
        axis: The dimension softmax would be performed on.
            The default is -1 which indicates the last dimension.

    # Returns
        A tensor.
    """
    return tf.nn.softmax(x, dim=axis)

That’s to change the last line

[Solved] Python TypeError: sequence item 0: expected str instance, int found

TypeError: sequence item 0: expected str instance, int found

code

list1=[1,'two','three',4]
print(' '.join(list1))

I thought I would print 1 two three 4

It turned out to be a mistake

Traceback (most recent call last):
 File "<pyshell#27>", line 1, in <module>
  print(" ".join(list1))
TypeError: sequence item 0: expected str instance, int found

I checked the information on the Internet and said that the list contains numbers and cannot be directly converted into a string

Solution:

print(" ".join('%s' %id for id in list1))

That is to traverse the elements of the list and convert it into a string. In this way, we can successfully output the result of 1 two three 4

from: https://blog.csdn.net/laochu250/article/details/67649210

Python TypeError: only size-1 arrays can be converted to Python scalars

Traceback (most recent call last):
File “/Users/mac126/111/mayplotlib/mayplotlib.py”, line 50, in <module>
plt.text(x,y ,’%.2f’%y ,ha=’center’,va=’bottom’)
TypeError: only size-1 arrays can be converted to Python scalars

code
import matplotlib.pyplot as plt
import numpy as np
k=10
x=np.arange(k)
y=np.random.rand(k)
plt.bar(x,y)

for x in zip(x,y):
    plt.text(x,y ,'%.2f'%y ,ha='center',va='bottom')
plt.show()

It’s found that one parameter Y is missing and it’s OK to add it

How to Solve Python TypeError: object of type ‘int‘ has no len()

Error: object of type ‘int’ has no len()

solution problems

Error: object of type ‘int’ has no len()

solution path

Type Error: No target type of int ()

Solution methods

Very simple errors, but roughly resulted!
replace
plt.xticks(3, [‘111’, ‘222’, ‘333’]
with
plt.xticks([1,2,3), [‘111’, ‘222’, ‘333’]

 

Python TypeError: Object of type int64 is not JSON serializable

Questions

In the process of using JSON. Dumps (param) to convert Python objects to JSON, the following problems appear: typeerror: object of type Int64 is not JSON serializable type

The code is as follows:

param = {
        'remoteId': 'remoteId',
        'fieldCode': 'fieldCode',
        'paramName': 'paramName',
        'operation': 'operation',
        'operationName': 'operationName',
        'paramValue': 0
    }
...
json.dumps(param)

Why

0 in 'paramvalue ': 0 is converted into Int64 object by pandas, which is not recognized by JSON library

Solution

Change the Int64 object into a normal string type. As follows:

'paramValue': str(0)

or

df['paramValue'].apply(str)

Python TypeError: ‘numpy.float64’ object cannot be interpreted as an index

When training stage1 RPN, there is a prompt error of ‘numpy. Float64’ object cannot be interpreted asanindex. Almost all blogs point out that the version of numpy needs to be changed. After doing so, there is an importerror: numpy. Core. Multiarray failed to import. This problem is caused by the mismatch of numpy, which forms a vicious circle, We can consider solving ‘numpy. Float64’ object cannot be interpreted as an index from the root

TypeError: 'numpy.float64' object cannot be interpreted as an index

1) /home/xxx/py-faster-rcnn/lib/roi_data_layer/minibatch.py

Line 26: fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image)
to fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image).astype(np.int)
Line 174 & 175 to

for ind in inds:
cls = clss[ind]
start =int( 4 * cls)
end = int(start + 4)
bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS

2) /home/xxx/py-faster-rcnn/lib/datasets/ds_utils.py

Line 12: hashes = np.round(boxes * scale).dot(v)
to hashes = np.round(boxes * scale).dot(v).astype(np.int)

3) /home/xxx/py-faster-rcnn/lib/fast_rcnn/test.py

Line 129: hashes = np.round(blobs['rois'] * cfg.DEDUP_BOXES).dot(v)
to hashes = np.round(blobs['rois'] * cfg.DEDUP_BOXES).dot(v).astype(np.int)

4) /home/xxx/py-faster-rcnn/lib/rpn/proposal_target_layer.py

Line 60: fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image)
to fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image).astype(np.int)

After solving the previous problem, there is a typeerror: slice indexes must be integers or none or have an__ index__ If the version of numpy is not changed,
Modify/home/xxx/py fast RCNN/lib/RPN/proposal_ target_ Layer.py, go to line 123:

for ind in inds:
        cls = clss[ind]
        start = 4 * cls
        end = start + 4
        bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
        bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS
    return bbox_targets, bbox_inside_weights

Here, ind, start and end are all numpy.int types, and data of this type cannot be used as indexes, so it is necessary to cast them. The conversion results are as follows:

for ind in inds:
        ind = int(ind)
        cls = clss[ind]
        start = int(4 * cos)
        end = int(start + 4)
        bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
        bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS
    return bbox_targets, bbox_inside_weight

How to Solve Python TypeError: ‘module’ object is not callable

When I am used to writing java code, I will try to define package when I write Python code. However, when I introduce it, I report an error: typeerror: ‘module’ object is not called

Why

For example, I create the person. Py source file in the package, and then create the student class in this file

How to import the student class

Habitual thinking, from clazz. Student is OK, but it is not

The correct way is from clazz.person import student or from clazz.person import*

That is to say, which classes are imported from which py file under which package