python-如果value = 1,pandas dataframe打印列

时间:2018-08-03 07:03:57

标签: python python-2.7 pandas

将此数据保存在熊猫数据框中:

animal      tall    swim        jump  
frog          0        1            1
toad          1        0            0
tadpole       0        0            1

想要这样的输出:

frog swim
frog jump
toad tall
tadpole jump

有任何内置函数吗?

1 个答案:

答案 0 :(得分:1)

set_indexstack一起使用,过滤1并由构造函数创建DataFrame

df1 = df.set_index('animal').stack()
s = df1[df1==1]

df2 = pd.DataFrame({'a':s.index.get_level_values(0),
                    'b':s.index.get_level_values(1)})
print (df2)
         a     b
0     frog  swim
1     frog  jump
2     toad  tall
3  tadpole  jump

另一种解决方案是使用MultiIndex.to_frame

df2 = s.index.to_frame(index=False)
df2.columns = ['a','b']
print (df2)
         a     b
0     frog  swim
1     frog  jump
2     toad  tall
3  tadpole  jump

使用melt和通过query进行过滤的不同解决方案:

df2 = (df.melt('animal', var_name='val')
         .query('value == 1')
         .sort_values('animal')
         .reset_index(drop=True)
         .drop('value', axis=1))
相关问题