Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 964
puhuk Avatar asked Dec 20 '25 18:12

puhuk


1 Answers

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)
like image 184
Quang Hoang Avatar answered Dec 23 '25 07:12

Quang Hoang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!