Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing columns to rows on python pandas

I have a data frame like this

 id  a  b  c
101  0  3  0
102  2  0  5
103  0  1  4

and I want something like this

 id  letter  num
101     a     0
101     b     3
101     c     0
102     a     2
102     b     0
102     c     5
103     a     0
103     b     1
103     c     4

I want to pass the column names to values of a row with their corresponding id and the result of the df.

I was trying to make it in a loop, introducing each element according to its id, but it's horrible. Is there an easy way to do this?

like image 547
Rosa Alejandra Avatar asked Apr 18 '16 20:04

Rosa Alejandra


People also ask

How do I convert columns to rows in pandas?

Method #2: Using pivot() method. In order to convert a column to row name/index in dataframe, Pandas has a built-in function Pivot. Now, let's say we want Result to be the rows/index, and columns be name in our dataframe, to achieve this pandas has provided a method called Pivot.

How do you pass rows in pandas?

Use apply() function when you wanted to update every row in pandas DataFrame by calling a custom function. In order to apply a function to every row, you should use axis=1 param to apply(). By applying a function to each row, we can create a new column by using the values from the row, updating the row e.t.c.

How do you convert rows into columns and columns into rows in pandas?

Pandas DataFrame: transpose() function The transpose() function is used to transpose index and columns. Reflect the DataFrame over its main diagonal by writing rows as columns and vice-versa. If True, the underlying data is copied. Otherwise (default), no copy is made if possible.

How do I pass a specific column in pandas?

Selecting columns based on their name This is the most basic way to select a single column from a dataframe, just put the string name of the column in brackets. Returns a pandas series. Passing a list in the brackets lets you select multiple columns at the same time.


1 Answers

You could melt and then sort:

>>> pd.melt(df, id_vars='id', value_vars=['a','b','c'], 
            var_name='letter', value_name='num').sort_values('id')
    id letter  num
0  101      a    0
3  101      b    3
6  101      c    0
1  102      a    2
4  102      b    0
7  102      c    5
2  103      a    0
5  103      b    1
8  103      c    4

If you want to reset the index, you could always use .reset_index(drop=True) on the returned DataFrame.

like image 169
Alex Riley Avatar answered Nov 10 '22 13:11

Alex Riley