python - Pandas:根据行内容选择列
问题描述
假设您有以下数据框:
Col1 Col2 Col3 Col4 Col5
Index
Row1 Code1 Code2 Code3 Code4 Code5
Row2 1 0 1 1 0
Row3 10 0 10 0 10
Row4 7070 56746 87647 969 687876
Row5 98798 79657 6876 977 6678
有没有办法根据行(索引)的标准选择列?
例如,
for all columns with Row2==1:
do something with all the rows in those columns
同样地
for all columns with Row3==0:
do something with all the rows in those columns
等等
我在想类似的东西
for "Row3" in df.index:
if "Row3" == 0:
# Do certain calculation
解决方案
m2 = df.loc['Row2'].eq(1)
#m2 = df.loc['Row2'].eq('1') #if string type
cols_Row2 = df.columns[m2]
#Index(['Col1', 'Col3', 'Col4'], dtype='object')
#for col in cols_Rows2:
#.....
索引数据框
df.loc[:,m2]
# Col1 Col3 Col4
#Index
#Row1 Code1 Code3 Code4
#Row2 1 1 1
#Row3 10 10 0
#Row4 7070 87647 969
#Row5 98798 6876 977
推荐阅读
- swift - 如何解决此“必需条件为假:format.sampleRate == hwFormat.sampleRate”错误?
- winapi - OleLoadPicturePath 是否以非向后兼容的方式进行了更改?
- python - Python发送没有内容的电子邮件
- android - 无法在我的 android studio 3.2.1 中解析 ':app@debug/compileClasspath' 的依赖关系
- c++ - C++:将不可移动函子传递给 std::function
- asp.net - 如何使用 asp 标签助手创建简单的多行文本框编辑器(
只制作没有文本颜色和大小等) - asp.net - 带有 EF 6.2 的 ASP.NET MVC 5 的最佳模式?
- javascript - 如何合并三个数组并用':'加入它们
- java - Java 8 流修复中间流方法不应被闲置声纳问题
- .htaccess - .htaccess 重写 https:// 前标记子域的条件