首页 > 解决方案 > 迭代多索引行和列DataFrame

问题描述

我有一个 DataFrame ,它在 rows和 columns(1000,1000)中有 Multi-Index 。我想遍历所有行和列并将所有内容设置为零,除了所选行和列匹配的位置。理想情况下,这适用于单个列和行 - 都具有多索引 - 但它也可以适用于多个列和行。label_y1, label_y2label_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

在列的情况下,我使用以下代码解决了问题:

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

这产生:

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

标签: pythonpython-3.xpandas

解决方案


您可以应用类似的逻辑(尽管将它们组合在一起效率低下)

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

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

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

local.loc[~local.index.isin([('done','A')]),:]=0
local.loc[:,~local.index.isin([('done','A')])]=0

推荐阅读