Renee D
Renee D

Reputation: 21

How can I group different rows based on its value?

I have a data frame in pandas like this:

Attributes1 Attributes value1 Attributes2 Attributes value2
a 1 b 4
b 2 a 5

Does anyone know how can I get a new data frame like below?

a b
1 2
5 4

Thank you!

Upvotes: 2

Views: 283

Answers (3)

Andrej Kesely
Andrej Kesely

Reputation: 195438

Try:

x = pd.DataFrame(
    df.apply(
        lambda x: dict(
            zip(x.filter(regex=r"Attributes\d+$"), x.filter(like="value"))
        ),
        axis=1,
    ).to_list()
)

print(x)

Prints:

   a  b
0  1  4
1  5  2

Upvotes: 1

BENY
BENY

Reputation: 323226

We can do wide_to_long then pivot

s = pd.wide_to_long(df.reset_index(),
                    ['Attributes','Attributes value'], 
                    i = 'index',
                    j = 'a').reset_index().drop(['a'],axis=1)
s = s.pivot(*s)
Out[22]: 
Attributes  a  b
index           
0           1  4
1           5  2

Upvotes: 0

Yash Laddha
Yash Laddha

Reputation: 152

Use the transpose() function to transpose the rows to columns, then use the groupby() function to group the columns with the same name.

Also, in the future, please add what you've tried to do to solve the problem as well.

Upvotes: 0

Related Questions