Python 如何在dataframe中查找非零元素的行和列
我有一个熊猫数据框,看起来像这样:Python 如何在dataframe中查找非零元素的行和列,python,pandas,Python,Pandas,我有一个熊猫数据框,看起来像这样: Type All Fail Pass A 0 0 0 B 1 0 0 C 0 0 0 现在,我想得到非零元素的列名以及Type列中相应的值。因此,在本例中,我想返回B和All。我知道如何使用此compare\u severity返回真/假矩阵。选择\u数据类型(include=['number'])!=0。但是我不知道如
Type All Fail Pass
A 0 0 0
B 1 0 0
C 0 0 0
现在,我想得到非零元素的列名以及
Type
列中相应的值。因此,在本例中,我想返回B
和All
。我知道如何使用此compare\u severity返回真/假矩阵。选择\u数据类型(include=['number'])!=0
。但是我不知道如何获得True
元素的列名和行索引。有人知道怎么做吗?解决这个问题的一种方法是找到数据帧等于1的行,以及数据帧等于1的列。您必须将类型设置为索引,以确保相等性检查仅关注数字列
df = df.set_index("Type")
df.loc[df.eq(1).any(axis=1),df.eq(1).any()]
All
Type
B 1
解决此问题的一种方法是查找dataframe等于1的行以及dataframe等于1的列。您必须将类型设置为索引,以确保相等性检查仅关注数字列
df = df.set_index("Type")
df.loc[df.eq(1).any(axis=1),df.eq(1).any()]
All
Type
B 1
看看这是否有帮助
df = df.set_index("Type")
result = df.where(df.select_dtypes(include="number") > 0) \
.fillna("") \
.to_dict(orient='index')
print({k:i for k, v in result.items() for i, j in v.items() if j})
产出
{'B': 'All'}
看看这是否有帮助
df = df.set_index("Type")
result = df.where(df.select_dtypes(include="number") > 0) \
.fillna("") \
.to_dict(orient='index')
print({k:i for k, v in result.items() for i, j in v.items() if j})
产出
{'B': 'All'}
我们可以在这里使用
idxmax
和dropna
:
num = df.select_dtypes('number')
num.where(num.ne(0)).idxmax().dropna()
All 1.0
dtype: float64
或者我们可以使用np。其中
也给出了索引:
df.columns[np.where(num)[0]].tolist()
['All']
我们可以在这里使用
idxmax
和dropna
:
num = df.select_dtypes('number')
num.where(num.ne(0)).idxmax().dropna()
All 1.0
dtype: float64
或者我们可以使用np。其中
也给出了索引:
df.columns[np.where(num)[0]].tolist()
['All']
尝试一下dropna()trygivedropna()