Home > Mobile >  How to add a dictionary with a number of keys less than the number of columns of the dataframe to th
How to add a dictionary with a number of keys less than the number of columns of the dataframe to th

Time:02-04

I have a Dataframe like this:

df enter image description here

and a dict like this:

result={'a':'cat,'b':'kiss'}

Can someone please help me to create a simple dataframe like below image? Thanks! enter image description here

CodePudding user response:

You can use concat with the DataFrame constructor :

df = pd.concat([df, pd.DataFrame(result, index=[len(df) 1])])

Alternatively, use loc :

df.loc[len(df) 1, list(result.keys())] = list(result.values())

​ Output :

print(df)

      a     b      c
1  food  hate   rain
2   dog  like  storm
3  same  love  flood
4   cat  kiss    NaN

CodePudding user response:

You can use same this append() method

  1. Let's say df1 = df
  2. Converting dictionary to dataframe using pd.Dataframe(result), let's say df2
  3. Appending df2 to the df1 using append()

A continuous index value will be maintained

df1.append(df2, ignore_index = True)
  • Related