迭代多索引行和列DataFram

2024-09-21 20:20:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧(1000,1000),它在行label_y1, label_y2和列label_x1, label_x2中有多个索引。我想遍历所有的行和列,除了所选的行和列匹配的地方之外,将所有内容设置为零。理想情况下,这适用于单个列和行(都具有多索引),但也可以用于多个列和行。在

数据帧看起来像:

local

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

Tags: 数据localtestinglabelpd行和列row1row2
1条回答
网友
1楼 · 发布于 2024-09-21 20:20:45

您可以应用类似的逻辑(尽管将其组合起来效率低下)

import pandas as pd    
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 ]))


for col in local.columns:
    for row in local.index:
        if col != ('done', 'A'):
            local.loc[:,col] = 0
        if row != ('done', 'A'):
            local.loc[row,:] = 0


print(local)



          testing    done   
                A  B    A  B
testing A       0  0    0  0
        B       0  0    0  0
done    A       0  0    3  0
        B       0  0    0  0

附加条件将使用或/类似于元组的列表来实现。在

另一种方法是使用pandas中的location函数来设置非标签的值。附加的标签条件在传递到isin函数的列表中实现。在

^{pr2}$

相关问题 更多 >