Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

df.append() with dicts converts booleans to 1s and 0s

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
like image 217
wkzhu Avatar asked Apr 13 '18 20:04

wkzhu


People also ask

How do you replace true and false with 0 and 1?

You can multiply the return Boolean values (TRUE or FALSE) by 1, and then the TRUE will change to 1, and FALSE to 0.

How do you convert boolean to number in Python?

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 .

How do you append to a data frame?

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.


1 Answers

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
like image 124
jeremycg Avatar answered Sep 30 '22 19:09

jeremycg