0

when I run the code to change the data type of the value in each cell in a column while reading the csv file with the pandas library read_csv() function an error occurs. The following is the error message on the ipython console:

Traceback (most recent call last):

  File pandas\_libs\parsers.pyx:1124 in pandas._libs.parsers.TextReader._convert_tokens

TypeError: Cannot cast array data from dtype('O') to dtype('int32') according to the rule 'safe'


During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File ~\anaconda3\lib\site-packages\spyder_kernels\py3compat.py:356 in compat_exec
    exec(code, globals, locals)

  File c:\users\user\.spyder-py3\belajar\dpt kota madiun pemilu 2024.py:9
    DPT = pd.read_csv("DPT KOTA MADIUN.csv", dtype={"USIA":int},low_memory=False)

  File ~\anaconda3\lib\site-packages\pandas\util\_decorators.py:211 in wrapper
    return func(*args, **kwargs)

  File ~\anaconda3\lib\site-packages\pandas\util\_decorators.py:331 in wrapper
    return func(*args, **kwargs)

  File ~\anaconda3\lib\site-packages\pandas\io\parsers\readers.py:950 in read_csv
    return _read(filepath_or_buffer, kwds)

  File ~\anaconda3\lib\site-packages\pandas\io\parsers\readers.py:611 in _read
    return parser.read(nrows)

  File ~\anaconda3\lib\site-packages\pandas\io\parsers\readers.py:1778 in read
    ) = self._engine.read(  # type: ignore[attr-defined]

  File ~\anaconda3\lib\site-packages\pandas\io\parsers\c_parser_wrapper.py:235 in read
    data = self._reader.read(nrows)

  File pandas\_libs\parsers.pyx:790 in pandas._libs.parsers.TextReader.read

  File pandas\_libs\parsers.pyx:890 in pandas._libs.parsers.TextReader._read_rows

  File pandas\_libs\parsers.pyx:1037 in pandas._libs.parsers.TextReader._convert_column_data

  File pandas\_libs\parsers.pyx:1130 in pandas._libs.parsers.TextReader._convert_tokens

ValueError: invalid literal for int() with base 10: 'USIA'

I have tried but always get the same error message. I hope to get answers from all my friends so that my problem can be solved

to make it easier for friends to understand my problem, here I provide the code snippet that I have:

import pandas as pd

DPT = pd.read_csv("DPT KOTA MADIUN.csv", dtype={"USIA":int()},low_memory=False)

asrl94
  • 1
  • 1
  • It seems as though one of your rows contains "USIA" - this is a string and cannot be converted to a number, causing an error. – some3128 Aug 03 '23 at 11:12
  • Please provide enough code so others can better understand or reproduce the problem. – Community Aug 03 '23 at 13:58

0 Answers0