我有一个数据帧(1000,1000)
,它在行label_y1, label_y2
和列label_x1, label_x2
中有多个索引。我想遍历所有的行和列,除了所选的行和列匹配的地方之外,将所有内容设置为零。理想情况下,这适用于单个列和行(都具有多索引),但也可以用于多个列和行。在
数据帧看起来像:
label_columns1 = ['testing','done']
label_columns2 = ['A', 'B']
label_rows1 = ['testing','done']
label_rows2 = ['A', 'B']
local = pd.DataFrame([[1,2,3,4]], index=pd.MultiIndex.from_product([label_rows1,label_rows2]), columns=pd.MultiIndex.from_product([label_columns1, label_columns2 ]))
print(local)
testing done
A B A B
row1 A 1 2 3 4
B 1 2 3 4
row2 A 1 2 3 4
B 1 2 3 4
对于列,我用以下代码解决了问题:
^{pr2}$这就产生了:
print(local)
testing done
A B A B
row1 A 0 0 3 0
B 0 0 3 0
row2 A 0 0 3 0
B 0 0 3 0
我也在做同样的行。我也尝试过使用local.iterrrows()
和loc
行,但它不起作用。你知道我该怎么做吗?我需要的是:
print (local)
testing done
A B A B
row1 A 0 0 0 0
B 0 0 0 0
row2 A 0 0 3 0
B 0 0 0 0
您可以应用类似的逻辑(尽管将其组合起来效率低下)
附加条件将使用或/类似于元组的列表来实现。在
另一种方法是使用pandas中的location函数来设置非标签的值。附加的标签条件在传递到isin函数的列表中实现。在
^{pr2}$相关问题 更多 >
编程相关推荐