簡體   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