zelenov aleksey zelenov aleksey - 1 month ago 6
Python Question

change the value in reduced matrix pandas

I'm trying to implement algorithm, where given matrix(matrix represents cities) should be reduced by condition:

here the matrix(data frame matrix):

0 1 2 3 4
0 9992 1 0 2 0
1 2 99991 5 0 0
2 0 4 9992 0 1
3 3 0 1 9991 2
4 1 0 2 2 99989


then by a condition I delete 0-row and 2-column in the matrix , so i get this:

df = df.drop(2,axis=1)
df = df.drop(0,axis=0)
reducedMatrix=df
print reducedMatrix
0 1 3 4
1 2 99991 0 0
2 0 4 0 1
3 3 0 9991 2
4 1 0 2 99989


and after deletion I should change the number of (2,0) element to a large number like 9999, I do :

reducedMatrix[2][0]=9999


but get the error

File "", line 81, in <module>
reducedMatrix[2][0]=999
File "", line 1997, in __getitem__
return self._getitem_column(key)
File "", line 2004, in _getitem_column
return self._get_item_cache(key)
File "/", line 1350, in _get_item_cache
values = self._data.get(item)
File "/anaconda/lib/python2.7/site-packages/pandas/core/internals.py", line 3290, in get
loc = self.items.get_loc(item)
File "anaconda/lib/python2.7/site-packages/pandas/indexes/base.py", line 1947, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas/index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas/index.c:4154)
File "pandas/index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas/index.c:4018)
File "pandas/hashtable.pyx", line 303, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6610)
File "pandas/hashtable.pyx", line 309, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6554)
KeyError: 2


it's imortant to save cols and rows names, because after deletion row i and col j I should change value in j,i position in the new matrix
the expected output:

print reducedMatrix
0 1 3 4
1 2 99991 0 0
2 9999 4 0 1
3 3 0 9991 2
4 1 0 2 99989


how to avoid it?
thx

Answer

Is this what you want?

reducedMatrix.loc[2][0] = 9999

where loc is used to index by label.

If you instead want to index by the new row/col positions, you want:

reducedMatrix.iloc[2][0] = 9999

(see this)