Tag Archives: Python TypeError

[How to Solve] Python TypeError: ‘int‘ object is not subscriptable

The title is the teacher’s lesson, which is adapted from the python language design basis of Songtian teacher of Beijing Institute of technology, page 4.7, 121

Please modify example 5: body mass index BMI with exception handling, so that it can receive and process any input from the user

while True:
try:
Height, weight = Eval (input (“please input height (m) and weight (kg) [separated by commas]:”)
0         bmi = weight/pow(height,2)
Print (“BMI value is: {. 2F}”. Format (BMI))
0         if height > 3:
if h[:-1].isinstance():
Print (“height value is {. 2F}”. Format (height))
0                 break
elif weight > 150:
if   w[:-1].isinstance():
Print (“body weight value is {. 2F}”. Format (weight))
0                 break
except NameError:
Print (“input error, please input correct information”)
the     else:
Print (“no exception occurred”)
finally:
Print (“complete”)

The cause of the error is an operation on an object that cannot be operated on

The original errors were height [: – 1]. Isinstance and weight [: – 1]. Isinstance, which were changed to h and W

Please input height (m) and weight (kg) [comma separated]: 4,85
BMI value: 5.31
input error, please input correct information
complete
please input height (m) and weight (kg) [comma separated]: 1.85,85
BMI value: 24.84
no abnormality
complete
please input height (m) and weight (kg) [comma separated]: 1.85, 200
BMI value: 58.44
input error, please input correct information
complete
please input height (m) and weight (kg) [separated by commas]:

Python TypeError: Unrecognized value type: <class ‘str‘>dateutil.parser._parser.ParserError: Unknow

When I want to convert a column of dates in the data frame into the date format of panda, I encountered this kind of error.

reader = pd.read_csv(f'new_files/2020-12-22-5-10.csv', usecols=['passCarTime'],dtype={'passCarTime':'string'})
pd.to_datetime(reader.passCarTime.head())
Out[98]: 
0   2020-12-22 10:00:00
1   2020-12-22 10:00:00
2   2020-12-22 10:00:00
3   2020-12-22 10:00:00
4   2020-12-22 10:00:00
Name: passCarTime, dtype: datetime64[ns]
pd.to_datetime(reader.passCarTime)
Traceback (most recent call last):
  File "D:\PyCharm2020\python2020\lib\site-packages\pandas\core\arrays\datetimes.py", line 2085, in objects_to_datetime64ns
    values, tz_parsed = conversion.datetime_to_datetime64(data)
  File "pandas\_libs\tslibs\conversion.pyx", line 350, in pandas._libs.tslibs.conversion.datetime_to_datetime64
TypeError: Unrecognized value type: <class 'str'>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "D:\PyCharm2020\python2020\lib\site-packages\IPython\core\interactiveshell.py", line 3427, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-99-e1b00dc18517>", line 1, in <module>
    pd.to_datetime(reader.passCarTime)
  File "D:\PyCharm2020\python2020\lib\site-packages\pandas\core\tools\datetimes.py", line 801, in to_datetime
    cache_array = _maybe_cache(arg, format, cache, convert_listlike)
  File "D:\PyCharm2020\python2020\lib\site-packages\pandas\core\tools\datetimes.py", line 178, in _maybe_cache
    cache_dates = convert_listlike(unique_dates, format)
  File "D:\PyCharm2020\python2020\lib\site-packages\pandas\core\tools\datetimes.py", line 465, in _convert_listlike_datetimes
    result, tz_parsed = objects_to_datetime64ns(
  File "D:\PyCharm2020\python2020\lib\site-packages\pandas\core\arrays\datetimes.py", line 2090, in objects_to_datetime64ns
    raise e
  File "D:\PyCharm2020\python2020\lib\site-packages\pandas\core\arrays\datetimes.py", line 2075, in objects_to_datetime64ns
    result, tz_parsed = tslib.array_to_datetime(
  File "pandas\_libs\tslib.pyx", line 364, in pandas._libs.tslib.array_to_datetime
  File "pandas\_libs\tslib.pyx", line 591, in pandas._libs.tslib.array_to_datetime
  File "pandas\_libs\tslib.pyx", line 726, in pandas._libs.tslib.array_to_datetime_object
  File "pandas\_libs\tslib.pyx", line 717, in pandas._libs.tslib.array_to_datetime_object
  File "pandas\_libs\tslibs\parsing.pyx", line 243, in pandas._libs.tslibs.parsing.parse_datetime_string
  File "D:\PyCharm2020\python2020\lib\site-packages\dateutil\parser\_parser.py", line 1374, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "D:\PyCharm2020\python2020\lib\site-packages\dateutil\parser\_parser.py", line 649, in parse
    raise ParserError("Unknown string format: %s", timestr)
dateutil.parser._parser.ParserError: Unknown string format: passCarTime

I’m not a professional, and my English is not good. I can’t understand what’s wrong. I have seen that there is no missing value in the date column of the file, and there is no date that does not conform to the format… This is very strange, welcome to leave a message, thanks in advance!

Solution

When converting, add a parameter errors ='coerce '.

reader = pd.read_csv(f'new_files/2020-12-22-5-10.csv', usecols=['passCarTime'],dtype={'passCarTime':'string'})
reader.passCarTime = pd.to_datetime(reader.passCarTime,errors='coerce') 
reader.passCarTime.head()
Out[120]: 
0   2020-12-22 10:00:00
1   2020-12-22 10:00:00
2   2020-12-22 10:00:00
3   2020-12-22 10:00:00
4   2020-12-22 10:00:00
Name: passCarTime, dtype: datetime64[ns]
reader.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 307707 entries, 0 to 307706
Data columns (total 1 columns):
 #   Column       Non-Null Count   Dtype         
---  ------       --------------   -----         
 0   passCarTime  307703 non-null  datetime64[ns]
dtypes: datetime64[ns](1)
memory usage: 2.3 MB

can‘t multiply sequence by non-int of type ‘numpy.float64‘

{TypeError}can’t multiply sequence by non-int of type ‘numpy.float64’

Multiplying float64 and tuples raises an error

    a=(2,4,6)
    b=35.6
    c=a*b

The reason is that a is of int type and B is of float type, and the types are inconsistent, so the multiplication operation cannot be performed

The solution is to change the data type to consistent.

    a=(2,4,6)
    b=35
    c=a*b
    print(c)

How to Fix TypeError: Cannot cast array data from dtype(‘float64‘) to dtype(‘<U32‘)….

Both U32 and S32 indicate that your NumPy array is a string array, not a number array. Check whether there are strings in the dataset. If there are, just delete them. In NumPy array, as long as one item is a string, the type returned by the array is a string array.
If you need to convert numpy to floating-point number, please refer to the code:
train= train.astype (float)
train_ target = train_ target.astype (float)

[How to Fix] TypeError: Cannot cast array data from dtype(‘float64‘) to dtype(‘<U32‘)….

Both U32 and S32 indicate that your numpy array is a string array, not a number array. Check whether there are strings in the dataset. If there are, just delete them. In numpy array, as long as one item is string, the type returned by the array is string array.
If you need to convert numpy to floating-point number, please refer to the code:
train= train.astype (float)
train_ target = train_ target.astype (float)

Typeerror in Python regular expression: expected string or bytes like object

The following error occurs when parsing web page data with beautifulSoup and processing data with regular expressions:
TypeError: Expected string or bytes-like object TypeError: Expected string or bytes-like object TypeError: Expected string or bytes-like object
It is generally caused by data type mismatch.
There are six standard data types in Python3: 

Print (type(object)) to check the current data type, where object is the object to query.

First, there is a code that looks like this:

import re
import requests
from bs4 import BeautifulSoup
import lxml

#get the html data
urlSave = "https://www.douban.com/people/yekingyan/statuses"
req = requests.get(urlSave)
soup = BeautifulSoup(req.text,'lxml')

# After parsing beautifulsoup, get the required data
times = soup.select('div.actions > span')
says = soup.select('div.status-saying > blockquote')

And then I’m going to look at it and I’m going to get the data what is the numeric type

print('says:',type(says))

The result: Says: lt; class ‘list’>
This tells us that the data selected from beautifulSoup in soup.select() is of the list type.
Next, extract the data in the list separately

#Traversing the output
for say in says:
    print(type(say))

Let’s see what type it is
The result: <<; class ‘bs4.element.Tag’> , different from the above six types
Beautiful Soup converts a complex HTML document into a complex tree structure, where each node is a Python object. All objects can be classified into four types:
TagNavigableStringBeautifulSoupComment
Use regular expressions directly to the data

for say in says:
    # Regular expressions to get the necessary data
    say = re.search('<p>(.*?)</p>',say)

There is an error
TypeError: expected string or bytes-like object
Therefore, before the regular expression, the problem is solved by converting the data type. As follows:

for say in says:
    # Convert the data type, otherwise an error will be reported
    say = str(say)
    # Regular expressions to get the necessary data
    say = re.search('<p>(.*?)</p>',say)

 

Python TypeError: coercing to Unicode: need string or buffer, NoneType found


Where train_accuracy_top5_nbatch_filename is the name of the file, and the code is as shown in the assignment

train_accuracy_top5_nbatch_filename = "a" + "b" + "c" + ".log"

But in execution

train_accuracy_top5_nbatch_file_op = open(train_accuracy_top5_nbatch_filename, "a")

An error occurred when.
Solutions:

train_accuracy_top5_nbatch_file_op = open(str(train_accuracy_top5_nbatch_filename), "a")