Search code examples
pythonpandasdataframeconcatenation

How to add a dictionary with a number of keys less than the number of columns of the dataframe to that dataframe into a new line?


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


Solution

  • 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