python - 按行值过滤熊猫数据框
问题描述
我知道如何按列值过滤数据框:
import pandas as pd
import numpy as np
from numpy.random import randn
np.random.seed(101)
df = pd.DataFrame(randn(5,4),index='A B C D E'.split(),columns='W X Y Z'.split())
print(df)
# show only rows where 'W' is positive
# here, the row for 'C' will be deleted, since df['W']['C']<0
df[df['W']>0]
但是如何按行值过滤,例如'B'> 0?
由于 df['X']['B']<=0 和 df['Y']['B']<=0,我想删除列 X 和 Y。我尝试了以下代码,但它报告一个错误:
df.loc[df.loc['B']>0]
解决方案
您应该在列上使用过滤器
df.loc[:,df.loc['B',:]>0]
Out[67]:
W Z
A 2.706850 0.503826
B 0.651118 0.605965
C -2.018168 -0.589001
D 0.188695 0.955057
E 0.190794 0.683509
推荐阅读
- azure - 尝试使用 $expand(microsoft.graph.itemattachment/item) 读取 ItemAttachment 属性时,Microsoft Graph API“访问被拒绝”
- typescript - React.memo 和打字稿
- r - 如何将 covid19.analytics 中的 live.map 功能添加到闪亮的应用程序中?
- java - Leetcode #11 装水最多的容器:为什么要使用“else”
- kubernetes - 我在 gitlab 中的自动 devops 管道不起作用
- php - 通过维基数据获取比利时的城市列表
- mysql - 当使用触发器更改另一个字段时,从表中更改字段的值
- python - 确定每组的连续日期期间
- excel - 将所有 pdf 文件移动到新文件夹
- laravel - 在 laravel 上使用 like 无法显示日期搜索