Python 基于行条件的轴1上的子集数据帧
编辑1: 如何使用在该行中包含“1”的串联列名映射每一行 预期产出:Python 基于行条件的轴1上的子集数据帧,python,pandas,dataframe,Python,Pandas,Dataframe,编辑1: 如何使用在该行中包含“1”的串联列名映射每一行 预期产出: df = DataFrame({'A':['Cat had a nap','Dog had puppies','Did you see a Donkey','kitten got angry','puppy was cute'],'Cat':[1,0,0,1,0],'Dog':[0,1,0,0,1]}) A Cat Dog 0 Cat had a nap 1
df = DataFrame({'A':['Cat had a nap','Dog had puppies','Did you see a Donkey','kitten got angry','puppy was cute'],'Cat':[1,0,0,1,0],'Dog':[0,1,0,0,1]})
A Cat Dog
0 Cat had a nap 1 0
1 Dog had puppies 0 1
2 Did you see a Donkey 0 0
3 kitten got angry 1 0
4 puppy was cute 0 1
按DataFrame的所有值进行比较,并通过以下方式检查每行列中至少一个True
:
对于筛选器行:
A Cat Dog Category
0 Cat had a nap 1 0 Cat, Dog
1 Dog had puppies 0 1 Dog
2 Did you see a Donkey 0 0 NaN
3 kitten got angry 1 0 Cat, Dog
4 puppy was cute 0 1 Dog
对于过滤列:
df = df[df.eq(1).any(axis=1)]
print (df)
A Cat Dog
0 Cat had a nap 1 0
1 Dog had puppies 0 1
3 kitten got angry 1 0
4 puppy was cute 0 1
对于筛选器列和行:
df = df.loc[:, df.eq(1).any()]
print (df)
Cat Dog
0 1 0
1 0 1
2 0 0
3 1 0
4 0 1
编辑:
如果我必须对每一行这样做,那么你认为第一种解决方案是什么?对不起。我将编辑我的问题。我需要将每一行映射为一个链接的列名,其中的值为1@SharvariGc-不确定是否理解,预期输出是什么?
m = df.eq(1)
df = df.loc[m.any(axis=1), m.any()]
print (df)
Cat Dog
0 1 0
1 0 1
3 1 0
4 0 1
df['Category'] = df.eq(1).dot(df.columns + ',').str[:-1]
print (df)
A Cat Dog Category
0 Cat had a nap 1 0 Cat
1 Dog had puppies 0 1 Dog
2 Did you see a Donkey 0 0
3 kitten got angry 1 0 Cat
4 puppy was cute 0 1 Dog