Say I create an empty dataframe:
df = pd.DataFrame()
and I add a dict via df.append()
:
df.append({'A': 'foo', 'B': 'bar'}, ignore_index=True)
This gives me the intended result of
A B
0 foo bar
However, if there are any booleans in the dict values, i.e.,
df.append({'A': True, 'B': False}, ignore_index=True)
The booleans are converted into floats.
A B
0 1.0 0.0
Why this is happening / how can I prevent this conversion? I'd prefer not do anything to the finished dataframe if possible (i.e., prefer not to coerce from float back to boolean).
EDIT: found my own solution, but still would like to know why the above behavior is happening. My solution is:
df.append(pd.DataFrame.from_dict({'A': True, 'B': False}, orient='index').T, ignore_index=True)
Which gives the desired
A B
0 True False
You can multiply the return Boolean values (TRUE or FALSE) by 1, and then the TRUE will change to 1, and FALSE to 0.
Integers and floating point numbers can be converted to the boolean data type using Python's bool() function. An int, float or complex number set to zero returns False . An integer, float or complex number set to any other number, positive or negative, returns True .
Dataframe append syntax Using the append method on a dataframe is very simple. You type the name of the first dataframe, and then . append() to call the method. Then inside the parenthesis, you type the name of the second dataframe, which you want to append to the end of the first.
You can convert your dict to a DataFrame before appending to keep the data types consistent:
df = pd.DataFrame()
df.append(pd.DataFrame({'A': True, 'B': False}, index = [0]))
A B
0 True False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With