Dataframe loc syntax

Can someone please explain why i am getting different output for the following tow different lines of code.

  1. f500.loc[‘Dow Chemical’,‘ceo’]=‘Jim Fitterling’

  2. f500[‘Dow Chemical’,‘ceo’]=‘Jim Fitterling’

In the first line the output is fine but when i try not to use loc in the other code.
It changes the value of every element in coloum ‘ceo’ to ‘Jim Fitterling’

Above f500 is a dataframe and dow chemical & ceo are row index and coloumn name respectively.
Can anyone please elaborate the difference and what concept I am missing here.

Here are couple of code examples, that could probably help to understand what is going on.

>>> import pandas as pd
>>> df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
...      index=['cobra', 'viper', 'sidewinder'],
...      columns=['max_speed', 'shield'])
>>> df
            max_speed  shield
cobra               1       2
viper               4       5
sidewinder          7       8


>>> df.loc['viper', 'shield'] = 'Test'
>>> df
            max_speed shield
cobra               1      2
viper               4   Test
sidewinder          7      8


>>> df['viper', 'shield'] = 5
>>> df
            max_speed shield  (viper, shield)
cobra               1      2                5
viper               4   Test                5
sidewinder          7      8                5

Do you see the difference?

Hope this may help.

1 Like

Hi, the difference is that the loc you append to the first line f500.loc['Dow Chemical,''ceo']specifys a particular location in the dataframe.
The short hand version which is the second line doesn’t have this specification and as such it will apply Jim Fitterling to the whole column.
It is usually safer in my opinion to use .loc when referring to specific entries in a dataframe and the short version if you want to access entire rows or columns. IMO.

1 Like

Now got it right.

Thankyou for the explanation.

@jainamw97, glad it helped! Could you, please, mark this as a solution, if you do not mind? Thanks!