Решено: dtype не може да бъде bool python

Последна актуализация: 09/11/2023

Основният проблем е, че bool е целочислен тип, докато dtype е str тип. Това може да създаде проблеми, когато се опитвате да сравните две логически стойности или когато прехвърляте една към друга.

I am trying to read a csv file in Python using Pandas. I have a column with values "true" and "false". When I try to read the file, I get the following error: 
<code>ValueError: could not convert string to float: 'true'
</code>
I tried changing the data type of the column to bool but it gives me an error saying that dtype cannot be bool. How can I fix this?


A:

You can use <code>pd.read_csv()</code> with <code>dtype={'column_name':bool}</code>: 
<blockquote>
<p><strong><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">pd.read_csv()</a></strong></p>
<pre><code>&lt;code&gt;dtype : Type name or dict of column -&amp;gt; type, default None  

    Data type for data or columns. E.g. {‘a’: np.float64, ‘b’: np.int32}  

    Use str or object together with suitable na_values settings to preserve and not interpret dtype as numeric type for non-numeric values such as empty strings “” or “NA”:  

    df = pd . read_csv (StringIO ("""A|B|C  

        0|1|2  

        3|4|5"""), dtype=str)  

    For non-standard datetime parsing, use ``pd . date _ parse(format)`` as a converter for ``datetime`` columns or ``pd . Timestamp`` if you want more control over specifying a format specification (e . g . European style MM / DD / YYYY) which overrides the default one , specified by ``dateparse . DEFAULTS ['dateparser']`` : ` ` ` python from dateutil import parser from io import StringIO df = pd . read_csv (StringIO ("""date | time | value 08 / 01 / 2012 | 00 : 00 : 05 | 1 08 / 01 / 2012 | 00 : 00 : 06 | 2 """), parse_dates = [[0 , 1]], date _ parser = parser . parse ) # specify dayfirst=True when parsing European dates # Or for timestamps, use pd . Timestamp instead of datetime and specify format explicitly ` ` ` See also pandas-dev#12169 where it was proposed that partial string indexing be supported on datetime columns when using a converter other than ``datetime`` , e . g :: df = pd . read _ csv (StringIO ("""date time value 08 / 01 / 2012 00 : 00 : 05 1 08 / 01 / 2012 00 : 00 : 06 2 """), parse _ dates = [[0 , 1]], date _ parser = lambda x , y : pd . Timestamp ( f '{x} {y}' )) df [ 'time' ] # results in TypeError currently &lt;/code&gt;</pre></blockquote>
</blockquote>

Относно Dtype

Dtype е тип данни в Python, който представлява число с плаваща запетая.

Заведения

В Python обектите са структури от данни, които ви позволяват да съхранявате информация на едно място. Обектите могат да се създават от всякакъв тип данни, включително числа, низове и списъци.

Обектите могат да бъдат достъпни с помощта на оператора точка ( . ) и те също могат да бъдат присвоени на променливи с помощта на оператора за присвояване ( = ). Можете също да използвате методите на обекта, за да извършвате действия върху обекта.

Например, можете да използвате метода print() на обекта, за да изведете информация за обекта на екрана. Можете също да използвате метода __str__() на обекта, за да върнете низово представяне на обекта.

Подобни публикации:

Оставете коментар