繁体   English   中英

迭代多索引行和列DataFrame

[英]Iterate multi-index rows and columns DataFrame

我有一个数据框(1000,1000)具有多指标行label_y1, label_y2和列label_x1, label_x2 我想遍历所有行和列, 并将所有内容都设置为零,除非选定的行和列匹配 理想情况下,这适用于单个列和行(均具有Multi-Index),但也可以适用于多个列和行。

DataFrame看起来像:

本地

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

您可以应用类似的逻辑(尽管效率不高,无法将它们组合在一起)

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

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

一种替代方法是使用熊猫中的定位功能来设置非标签的值。 其他标签条件在传递给isin函数的列表中实现。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM