python - 迭代多索引行和列DataFrame
问题描述
我有一个 DataFrame ,它在 rows和 columns(1000,1000)
中有 Multi-Index 。我想遍历所有行和列并将所有内容设置为零,除了所选行和列匹配的位置。理想情况下,这适用于单个列和行 - 都具有多索引 - 但它也可以适用于多个列和行。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
在列的情况下,我使用以下代码解决了问题:
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
附加条件将使用或 /a 类似列表的元组来实现。
另一种方法是使用 pandas 中的位置函数来设置非标签的值。附加标签条件在传递给 isin 函数的列表中实现。
local.loc[~local.index.isin([('done','A')]),:]=0
local.loc[:,~local.index.isin([('done','A')])]=0
推荐阅读
- javascript - 为什么 html 视频标签没有加载我的视频?
- java - 将 JavaFX jmods 添加到 java --list-modules
- c++ - Qtconcurrent - 从 gui 线程启动第二个线程的简单方法
- java - 添加此 servlet 代码服务器时停止
- c++ - 使用反向迭代器的中点
- tcl - 从 tcl 中的给定路径中删除大括号
- javascript - 尽管被捕获,但在生成器中抛出的错误完成了它
- java - FirebaseRecyclerAdapter DatabaseException:无法将 java.lang.String 类型的对象转换为 Posts 类型
- user-interface - 是否有现成的 UI 可以在 ASP.NET 中编辑数据库表?
- javascript - Simple React Native iOS App 未在 xcode 和命令行中运行