I have below data frame
import pandas as pd
dat1 = pd.DataFrame({'x' : [1,2,4], 'y' : [3,4,10]}).set_axis(['a', 'b', 'c'], axis = 0)
Now I want chance values of certain cells by calling those cells by name. I tried below
dat1.iloc['b']['y'] = 999
However this generates error as below,
>>> dat1.iloc['b']['y'] = 999
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.11/site-packages/pandas/core/indexing.py", line 1103, in __getitem__
return self._getitem_axis(maybe_callable, axis=axis)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/pandas/core/indexing.py", line 1653, in _getitem_axis
raise TypeError("Cannot index by location index with a non-integer key")
TypeError: Cannot index by location index with a non-integer key
Could you please help how to change the cell values under above setup?
Note, there are some good discussions on above subject (e.g. How to remove square bracket from pandas dataframe), however I dont find any discussion where cell is called by row and column index names to change it’s value
>Solution :
Looks like your problem is that you are using data.iloc (which is integer based, like indexing a python list)
since you want to access a specific row/column by label, you would use data.loc
here is your revised code :
import pandas as pd
dat1 = pd.DataFrame({'x' : [1,2,4], 'y' : [3,4,10]}).set_axis(['a', 'b', 'c'], axis = 0)
# Using .loc to change the value based on labels
dat1.loc['b', 'y'] = 999
print(dat1)
this will print
x y
a 1 3
b 2 999
c 4 10