Reputation: 363
Apologies I'm a python noob and I'm super rusty. Just getting back into code. Need help.
I have a dataframe (df) that looks like this:
2020-10-21 2020-09-30 2020-08-31 2020-07-31 2020-06-30 2020-05-29
close 513.19 470.11 325.10 253.91 253.54 179.48
I'm trying to add a new column that calculates the difference between the most recent column (2020-10-21) and the last column (2020-05-29).
df['Val_Diff'] = df[0] - df[5]
print(df)
When it runs I'm getting the following error.
KeyError: 0
What's the right way to do this?
Upvotes: 0
Views: 48
Reputation: 3066
If you are talking about columns' index (instead of name). use df.iloc[:,0] - df.iloc[:,5]
.
iloc
receive index while loc
receive column name.
Also, loc
and iloc
are looking for [rows, columns]
, hence to choose all rows in a specific column: .iloc[:, column_index]
Upvotes: 1