0
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(0)  
df_new = pd.DataFrame(np.random.randn(5,3), columns=list('ABC'))
display(df_new)

diff_BC= []
for i in range(len(df_new)):
    diff_BC.append(df_new.loc[i]['B'] - df_new.loc[i]['C'])
df_new['difference'] = diff_BC
display(df_new['difference'])
print(type(i))

I don't understand why df_new.loc[i]['B'] - df_new.loc[i]['C'] works, I think it should give an error , because type(i) is int and should use iloc.

Ajoe
  • 1,397
  • 4
  • 19
  • 48
  • Because unless specified otherwise, a dataframe will have a `RangeIndex` which assigns keys from 0..len(df)... so the index for the row is the same as the location for the row... `print(df.index)` for instance... – Jon Clements Nov 10 '19 at 11:39
  • `.loc` finds the *name* of the index. And if your index is numbers, as it is, it will find them. – Aryerez Nov 10 '19 at 11:40
  • Does this answer your question? [How are iloc, ix and loc different?](https://stackoverflow.com/questions/31593201/how-are-iloc-ix-and-loc-different) – gosuto Nov 10 '19 at 14:15

0 Answers0