Home > Blockchain >  How to append a dictionary with multiple keys to a dataframe
How to append a dictionary with multiple keys to a dataframe

Time:08-04

I am trying to append a dictionary to my DataFrame.

This is how the DataFrame looks:

NR   RS   BP
0471 10   11.41
0652 10   11.50
0650 20   11.35
6519 40   11.06

And this is the dictionary:

bpDict = {"nr":["0471","0652","0650","6519"],
          "bp2":[11.39,11.47,nan,11.07],
          "bp3":[11.43,11.46,11.33,11.08],
          "bp4":[11.44,11.44,11.37,nan]}

I need to append this dictionary to my df. I know how to do it when I append one column (using map) but this is not going to work here.

Any ideas on how to append this?

CodePudding user response:

You can use the merge() method from Pandas dataframes. You can do something like that :

df = pd.DataFrame({
    "nr":["0471","0652","0650","6519"],
    "RS":[10,10,20,40],
    "BP":[11.41, 11.50, 11.35, 11.06],
})
bpDict = {"nr":["0471","0652","0650","6519"],
          "bp2":[11.39,11.47,11.38,11.07],
          "bp3":[11.43,11.46,11.33,11.08],
          "bp4":[11.44,11.44,11.37,11.11]}
df_2 = pd.DataFrame(bpDict)
df.merge(df_2, on="nr")

CodePudding user response:

NaNs work just fine...

from numpy import nan

data = {"nr":["0471","0652","0650","6519"],
          "bp2":[11.39,11.47,nan,11.07],
          "bp3":[11.43,11.46,11.33,11.08],
          "bp4":[11.44,11.44,11.37,nan]}
df2 = pd.DataFrame(data)

out = df.merge(df2, left_on='NR', right_on='nr')
print(out)

Output:

     NR  RS     BP    nr    bp2    bp3    bp4
0  0471  10  11.41  0471  11.39  11.43  11.44
1  0652  10  11.50  0652  11.47  11.46  11.44
2  0650  20  11.35  0650    NaN  11.33  11.37
3  6519  40  11.06  6519  11.07  11.08    NaN
  • Related