bio_dan
bio_dan

Reputation: 78

How to correctly append values of a dictionary to an empty dataframe?

Hi I am trying to create a dataframe that will have rows added to it in a for loop. So I decided to first create an empty version of the dataframe, and then create a dictionary for a new row and append that dictionary to the dataframe in each iteration of the loop. The problem is that the values in the dataframe do not properly match the values that were in the dictionary:

I create an empty dataframe as follows:

import pandas
df = pandas.DataFrame({"a":[], "b":[], "c":[]})

I would then create a dictionary and append it to the dataframe like:

dict = {"a":1, "b":2, "c":True}
df = df.append(dict, ignore_index=True)

The problem is that instead of getting a=1, b=1, c=True the dataframe has a=1.0, b=1.0, c=1.0

So how can I make the columns of a and b integers, and the column of c a boolean value?

Upvotes: 1

Views: 603

Answers (1)

Prakash Dahal
Prakash Dahal

Reputation: 4875

You should not convert dictionary to dataframe in the first line. Better convert it at last

import pandas
dicts = {"a":[], "b":[], "c":[]} #do not convert dict to df
new_dict = {"a":1, "b":2, "c":True}

for k,v in new_dict.items():
  dicts[k].append(new_dict[k])

df = pd.DataFrame(dicts)

Output:

df

    a   b   c
0   1   2   True

Upvotes: 1

Related Questions