Python 查找pandas'中每行中非零值的列索引集;数据帧
在pandas的数据帧中,是否有一种很好的方法可以找到每行中非零值的列索引集?我必须逐行遍历数据帧吗 例如,数据帧是Python 查找pandas'中每行中非零值的列索引集;数据帧,python,pandas,Python,Pandas,在pandas的数据帧中,是否有一种很好的方法可以找到每行中非零值的列索引集?我必须逐行遍历数据帧吗 例如,数据帧是 c1 c2 c3 c4 c5 c6 c7 c8 c9 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
c1 c2 c3 c4 c5 c6 c7 c8 c9
1 1 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 2 1 1 1 1 1 0 2
1 5 5 0 0 1 0 4 6
4 3 0 1 1 1 1 5 10
3 5 2 4 1 2 2 1 3
6 4 0 1 0 0 0 0 0
3 9 1 0 1 0 2 1 0
预计产量将达到100%
['c1','c2']
['c1']
['c2']
...
可能更好的数据结构(而不是一系列列表)是堆栈:
In [11]: res = df[df!=0].stack()
In [12]: res
Out[12]:
0 c1 1
c2 1
1 c1 1
2 c2 1
3 c1 1
...
您可以迭代原始行:
In [13]: res.loc[0]
Out[13]:
c1 1
c2 1
dtype: float64
In [14]: res.loc[0].index
Out[14]: Index(['c1', 'c2'], dtype='object')
注意:我认为您过去可以在应用程序中返回列表(以创建具有列表元素的数据帧),但现在似乎不再是这种情况。您似乎必须逐行遍历数据帧
cols = df.columns
bt = df.apply(lambda x: x > 0)
bt.apply(lambda x: list(cols[x.values]), axis=1)
您将获得:
0 [c1, c2]
1 [c1]
2 [c2]
3 [c1]
4 [c2]
5 []
6 [c2, c3, c4, c5, c6, c7, c9]
7 [c1, c2, c3, c6, c8, c9]
8 [c1, c2, c4, c5, c6, c7, c8, c9]
9 [c1, c2, c3, c4, c5, c6, c7, c8, c9]
10 [c1, c2, c4]
11 [c1, c2, c3, c5, c7, c8]
dtype: object
如果性能很重要,请尝试将raw=True
传递给布尔数据帧创建,如下所示:
%timeit df.apply(lambda x: x > 0, raw=True).apply(lambda x: list(cols[x.values]), axis=1)
1000 loops, best of 3: 812 µs per loop
它为您带来了更好的性能增益。以下是raw=False
(默认)结果:
这种方法怎么样
#create a True / False data frame
df_boolean = df>0
#a little helper method that uses boolean slicing internally
def bar(x,columns):
return ','.join(list(columns[x]))
#use an apply along the column axis
df_boolean['result'] = df_boolean.apply(lambda x: bar(x,df_boolean.columns),axis=1)
# filter out the empty "rows" adn grab the result column
df_result = df_boolean[df_boolean['result'] != '']['result']
#append an axis, just so each line will will output a list
lst_result = df_result.values[:,np.newaxis]
print '\n'.join([ str(myelement) for myelement in lst_result])
这就产生了:
['c1,c2']
['c1']
['c2']
['c1']
['c2']
['c2,c3,c4,c5,c6,c7,c9']
['c1,c2,c3,c6,c8,c9']
['c1,c2,c4,c5,c6,c7,c8,c9']
['c1,c2,c3,c4,c5,c6,c7,c8,c9']
['c1,c2,c4']
['c1,c2,c3,c5,c7,c8']
Scari以更简洁的解决方案击败了我。我可以将我的答案留在网上,以演示如何写出输出,或者很乐意删除。
['c1,c2']
['c1']
['c2']
['c1']
['c2']
['c2,c3,c4,c5,c6,c7,c9']
['c1,c2,c3,c6,c8,c9']
['c1,c2,c4,c5,c6,c7,c8,c9']
['c1,c2,c3,c4,c5,c6,c7,c8,c9']
['c1,c2,c4']
['c1,c2,c3,c5,c7,c8']