Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:用if语句替换Dataframe中的单元格值_Python_Pandas - Fatal编程技术网

Python:用if语句替换Dataframe中的单元格值

Python:用if语句替换Dataframe中的单元格值,python,pandas,Python,Pandas,我有一个矩阵,看起来像这样: com 0 1 2 3 4 5 AAA 0 5 0 4 2 1 4 ABC 0 9 8 9 1 0 3 ADE 1 4 3 5 1 0 1 BCD 1 6 7 8 3 4 1 BCF 2 3 4 2 1 3 0 ... 其中AAA,ABC。。。是数据帧索引。数据帧列是com 01 3 4 5 6 当com的行值等于列“number”时,我想将数据帧中的单元格值设置为0。例如,上面的矩阵如下所示: com 0 1 2 3 4 5

我有一个矩阵,看起来像这样:

    com 0 1 2 3 4 5
AAA  0  5 0 4 2 1 4
ABC  0  9 8 9 1 0 3
ADE  1  4 3 5 1 0 1
BCD  1  6 7 8 3 4 1
BCF  2  3 4 2 1 3 0 ...
其中
AAA,ABC
。。。是数据帧索引。数据帧列是
com 01 3 4 5 6

com
的行值等于列“number”时,我想将数据帧中的单元格值设置为0。例如,上面的矩阵如下所示:

    com 0 1 2 3 4 5
AAA  0  0 0 4 2 1 4
ABC  0  0 8 9 1 0 3
ADE  1  4 0 5 1 0 1
BCD  1  6 0 8 3 4 1
BCF  2  3 4 0 1 3 0 ...

我尝试迭代行,并同时使用
.loc
.ix
,但没有成功。

我认为这应该有效

for line in range(len(matrix)):
    matrix[matrix[line][0]+1]=0
注意 根据矩阵设置,您可能不需要+1

基本上,它取矩阵中每行的第一位数字,并将其用作值的索引,以更改为0

i、 e.如果争吵是

    c 0 1 2 3 4 5
AAA 4 3 2 3 9 5 9, 
它会将数字4下面的5更改为0

    c 0 1 2 3 4 5
AAA 4 3 2 3 9 0 9

只需要一些
numpy
技巧

In [22]:

print df
   0  1  2  3  4  5
0  5  0  4  2  1  4
0  9  8  9  1  0  3
1  4  3  5  1  0  1
1  6  7  8  3  4  1
2  3  4  2  1  3  0

[5 rows x 6 columns]
In [23]:
#making a masking matrix, 0 where column and index values equal, 1 elsewhere, kind of the vectorized way of doing if TURE 0, else 1
print df*np.where(df.columns.values==df.index.values[..., np.newaxis], 0,1)
   0  1  2  3  4  5
0  0  0  4  2  1  4
0  0  8  9  1  0  3
1  4  0  5  1  0  1
1  6  0  8  3  4  1
2  3  4  0  1  3  0

[5 rows x 6 columns]

伟大的那很好。但是我不得不做一个小的改变:
print df*np.where(df.columns.values==df.com.values[…,np.newaxis],0,1)