Home > Enterprise >  Appending Last row series of a dataframe to another dataframe nested within dictionary
Appending Last row series of a dataframe to another dataframe nested within dictionary

Time:09-23

import pandas as pd 
d1 = {  }
df1 = pd.DataFrame(
    {
        "A": ["A0", "A1", "A2", "A3"],
        "B": ["B0", "B1", "B2", "B3"],
        "C": ["C0", "C1", "C2", "C3"],
        "D": ["D0", "D1", "D2", "D3"],
    },
    index=[0, 1, 2, 3])

for i in range(1, len(df1)):
    d1[i].append(df1.tail(1))
    print(d1[i])

d1 is dictionary of dataframes. I expect the 4 dataframes to be filled in with last row from df1 dataframe.

I get following error : Traceback (most recent call last): File "C:/Users/xxxx/AppData/Roaming/JetBrains/PyCharmCE2021.2/scratches/Pandas and Dictionary.py", line 14, in d1[i].append(df1.tail(1)) KeyError: 1

CodePudding user response:

Let’s decompose what df1[i].append(…) does:

  • df1[i] is taking the value in df1 that has the key i
  • .append(…) is then calling the append function on this value, as if it were e.g. a list

However your dictionary is empty. What you want instead is:

for i in range(1, len(df1)):
    d1[i] = df1.tail(1)

See also the d[key] and d[key] = value entries of the python dict documentation.

CodePudding user response:

Your

KeyError: 1

is caused by

d1[i].append(...)

in your second last line. If you want to add a new dict entry, you can just do

d1[key] = value

I don't know if this answers your question wholly.

Update:

I would suggest initializing d1 as a pd.DataFrame as well. Then you can fetch the last row of df1 and append it onto d1.

d1 = pd.DataFrame(colums=["A", "B", "C", "D"])
last_row = df1[-1:]
d1 = pd.concat([d1, last_row])

This snippet will append your last row to your global DF, assuming they have matching column names.

  • Related