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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With