How to efficiently reorder pandas data as follows?

I need help with a concise and, above all, effective statement in pandas of the following operation:

Given the format data frame

id    a   b    c   d
1     0   -1   1   1
42    0    1   0   0
128   1   -1   0   1

Build data frame format:

id     one_entries
1      "c d"
42     "b"
128    "a d"

That is, the one_entries column contains the concatenated column names for which the entry in the original frame is 1.

+4
source share
2 answers

Here is one way to use the logical rule and apply the lambda function.

In [58]: df
Out[58]:
    id  a  b  c  d
0    1  0 -1  1  1
1   42  0  1  0  0
2  128  1 -1  0  1

In [59]: cols = list('abcd')

In [60]: (df[cols] > 0).apply(lambda x: ' '.join(x[x].index), axis=1)
Out[60]:
0    c d
1      b
2    a d
dtype: object

You can assign a result df['one_entries'] =

Application Details func.

Take the first line.

In [83]: x = df[cols].ix[0] > 0

In [84]: x
Out[84]:
a    False
b    False
c     True
d     True
Name: 0, dtype: bool

x , . x[x] True. .

In [85]: x[x]
Out[85]:
c    True
d    True
Name: 0, dtype: bool

x[x].index .

In [86]: x[x].index
Out[86]: Index([u'c', u'd'], dtype='object')
+5

, , , DataFrame dict.

pd.DataFrame({
    'one_entries': (test_df > 0).apply(lambda x: ' '.join(x[x].index), axis=1)
})

#       one_entries
#   1           c d
#  42             b
# 128           a d
+2

Source: https://habr.com/ru/post/1662062/


All Articles