Portion of my code that's giving trouble below. I open a CSV and want to subtract the 1st row from the last row then append it to a new file. I get an error KeyError: 96 when I try it. I know the problem is the df[96]-df
CodePudding user response:
You can use iloc
to select the first and last row and then subtract
import pandas as pd
import numpy as np
#Create a test df
np.random.seed(1)
df = pd.DataFrame({
'col1':np.random.choice(10,6),
'col2':np.random.choice(10,6),
'col3':np.random.choice(10,6),
})
#subtract the first row from the last row
first_ind = 0
last_ind = len(df)-1
diff_row = df.iloc[last_ind]-df.iloc[first_ind]
print(diff_row)
Here's the test df that is created:
col1 col2 col3
0 5 1 5
1 8 7 2
2 9 6 4
3 5 9 2
4 0 2 4
5 0 4 7
And then diff_row
equals:
col1 -5
col2 3
col3 2
dtype: int64