11

Hi I want to append dictionary to DataFrame, but in this dictionary I dont have any index value. I also need to remove everything except "1393" from 'KP' value. This looks like this:

To this df:enter image description here

I want to append dictionary like this:

dict = {'KP': [1.0    1393
  Name: KP, dtype: int64],
 'Wiek': [Timedelta('176 days 12:59:43.042156102')],
 'KY1': [113.0],
 'OKO': [57.51],
 'GS': [10.59],
 'T': [654.31],
 'MP': [58.9]}

I try this:

df.append(dict,ignore_index=True)

But nothing happend, df is still the same and i dont get any error. I try to convert this dictionary to list and append list as row to df but I got the same result.

Ok i try this:

df = df.append(dict, ignore_index = True)

I get this output: enter image description here

This is not good enought i need clear data.

3
  • 2
    Use df = df.append(dict, ignore_index = True). Commented Jan 28, 2022 at 8:07
  • 3
    You can convert the dictionary into a dataframe: df1 = pd.DataFrame(dict) and then append: df = df.append(df1, ignore_index = True). Btw using dict as a variable name is highly non-recomended as dict is a built-in keyword; also please never post images of dataframes, post them as text as explained in here: stackoverflow.com/questions/20109391/… Commented Jan 28, 2022 at 8:51
  • You can use df.loc[len(df)] = dict. See this answer. Commented Feb 17, 2024 at 8:44

1 Answer 1

12

As the 'append' method is deprecated, you may need to consider to use 'concat':

the_dict = {'k1':'v1','k2':'v2'}
df_the_dict = pd.DataFrame({'name':the_dict.keys(), 'value':the_dict.values()})

df_final = pd.concat([df_final, df_the_dict], ignore_index=True)
Sign up to request clarification or add additional context in comments.

5 Comments

I find adding rows to Pandas unbelievably unelegant un unpythonic. I cannot believe that the append method was dropped, which was intuitive and which would accept dictionaries.
it's unreal. Concat to add a row? Come on.
Yes @vega, I have a table and want to add a row. Natural way of storing a row is as a dict. Doing this mambo jumbo with concat is counter-intuitive. Why are you not doing this with lists? Instead of [].append(item), you could do newlist = [] + [item]. Better?
@Paloha in some situations you need to stick with dataframes. I think it's nuts they dropped append(). Creating a new dataframe by concatenation every time you want to just add a row is really unpythonic.
@vega from your comment before I thought you were advocating for it. Now I see we agree. Yes, also in my opinion it is unpythonic.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.