Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing cell values of a pandas dataframe

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>> 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading