'KeyError(key) from new variable assigned to dataframe

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



Solution 1:[1]

pandas.DataFrame.assign doesn't change inplace

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

Solution 2:[2]

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

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

Solution 3:[3]

This code works:

volf = (rates.FF-rates.FF.shift(1))/rates.FF.shift(1)    
rates["volf"]=volf  

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ynjxsjmh
Solution 2
Solution 3 halfer