Manolo Dominguez Becerra
Manolo Dominguez Becerra

Reputation: 1373

Changing the order of my columns to create a data frame suitable for barplot

I have this data frame (two first row, the real one is huge)

df

p__Actinobacteriota 25 555
p__Bacteroidota 31 752

I would like to transform this data frame to the next one:

dft

p__Actinobacteriota 25 A
p__Actinobacteriota 555 B
p__Bacteroidota 31 A
p__Bacteroidota 725 B

What is the most simple way to do that?

Upvotes: 0

Views: 18

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 149185

I will assume that your dataframe is:

pd.DataFrame([['p__Actinobacteriota', 25, 555], ['p__Bacteroidota', 31, 752]])

which prints as:

                     0   1    2
0  p__Actinobacteriota  25  555
1      p__Bacteroidota  31  752

It is easy to stack it:

df.rename(columns={1:'A', 2:'B'}).set_index([0]).stack().rename('val').reset_index()

which give:

                     0 level_1  val
0  p__Actinobacteriota       A   25
1  p__Actinobacteriota       B  555
2      p__Bacteroidota       A   31
3      p__Bacteroidota       B  752

Upvotes: 1

Related Questions