Home > Blockchain >  KeyError(key) from new variable assigned to dataframe
KeyError(key) from new variable assigned to dataframe

Time:04-19

The rates data frame I read from a csv file:

rates = pd.read_csv(r'C:/Users/Owner/Documents/Research/SOMA/SomaFinal.csv',
                usecols=[0, 1, 2, 3], skiprows=6, parse_dates=['Date'])
date = rates.loc[:, "Date"]
ff = rates.loc[:, "FF"]
res  = rates.loc[:, "WRESBAL"]
iorb = rates.loc[:, "IORB"]

I want to create a percent change in the variable ff (the Fed Funds rate) and add to dataframe rates:

rates.assign(volf=(ff-ff.shift(1))/ff.shift(1))
vol = rates.loc[:, "volf"]

I get the error:

    raise KeyError(key) from err
KeyError: 'volf'

When I did not add vol=reates.loc statement, I got a name error that vol was not defined

CodePudding user response:

pandas.DataFrame.assign doesn't change inplace

rates = rates.assign(volf=(ff-ff.shift(1))/ff.shift(1))

CodePudding user response:

I don't see a specific reason for why assign needs to be used. How about:

rates['volf'] = (rates['ff']-rates['ff'].shift(1)) / rates['ff'].shift(1)
  • Related