puhuk
puhuk

Reputation: 484

Make pair from row/column data of Python DataFrame

I want to make pairs from below like dataframe from python What I'd like to do is make pairs with row and column like: (1,a), (4,c), (6,c), (3,d), (2,f), (4,f), (6,f), (6,g)

Is there any way to do this. Thanks in advance.

Example

Upvotes: 3

Views: 2562

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150735

Data:

     a   b   c    d   e    f   g
1  1.0 NaN NaN  NaN NaN  NaN NaN
2  NaN NaN NaN  NaN NaN  1.0 NaN
3  NaN NaN NaN  1.0 NaN  NaN NaN
4  NaN NaN NaN  1.0 NaN  1.0 NaN

Option 1: You can use np.where:

rows, cols = np.where(df.eq(1))
[*zip(df.index[rows], df.columns[cols])]

Output:

[(1, 'a'), (2, 'f'), (3, 'd'), (4, 'd'), (4, 'f')]

Option 2:

df.stack().index.values

Output:

array([(1, 'a'), (2, 'f'), (3, 'd'), (4, 'd'), (4, 'f')], dtype=object)

Upvotes: 2

rafaelc
rafaelc

Reputation: 59274

If you have a data frame like this:

     a   b   c    d   e    f    g
1  1.0 NaN NaN  NaN NaN  NaN  NaN
2  NaN NaN NaN  NaN NaN  1.0  NaN
3  NaN NaN NaN  1.0 NaN  NaN  1.0

You can use stack against axis 1 to get

s = df.stack()

1  a    1.0
2  f    1.0
3  d    1.0
   g    1.0
dtype: float64

And a simple to_list() gives

>>> s.index.to_list()

[(1, 'a'), (2, 'f'), (3, 'd'), (3, 'g')]

Upvotes: 1

Related Questions