更改简化矩阵大熊猫中的值

时间:2016-10-26 18:11:16

标签: python pandas matrix dataframe

我试图实现算法,其中给定矩阵(矩阵代表城市)应该按条件减少:

这里是矩阵(数据框矩阵):

          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 

然后通过条件我删除矩阵中的0行和2列,所以我得到了这个:

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

删除后我应该将(2,0)元素的数量更改为9999之类的大数字,我这样做:

reducedMatrix[2][0]=9999

但得到错误

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

保存cols和行名称是非常重要的,因为删除行i和col j之后我应该更改j中的值,我在新矩阵中的位置 预期产出:

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

如何避免它? THX

1 个答案:

答案 0 :(得分:1)

this你想要的是什么?

reducedMatrix.loc[2][0] = 9999

其中loc用于按标签索引。

如果您想要按新行/列位置进行索引,则需要:

reducedMatrix.iloc[2][0] = 9999

(见this