search
Search
Unlock 100+ guides
search toc
close
Outline
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to

# Unstacking certain columns only in Pandas DataFrame

schedule Aug 10, 2023
Last updated
local_offer
PythonPandas
Tags
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

Pandas' `unstack(~)` method does not allow you to select specific columns to unstack. To unstack certain columns only, use the Pandas `melt(~)` method.

# Example

Consider the following DataFrame:

``` import pandas as pddf = pd.DataFrame({'A':['a','b','a','b'], 'B':[None,'c','c',None], 'C':[5,5,6,6]})df A B C0 a None 51 b c 52 a c 63 b None 6 ```

## Solution

To unstack columns `A` and `B` only and keep column `C`:

``` pd.melt(df, id_vars='C', value_vars=['A','B']).drop(columns=['variable']).query('value == value') C value0 5 a1 5 b2 6 a3 6 b5 5 c6 6 c ```

## Explanation

We first use the `melt(~)` method to elongate (please refer to our documentation on `melt(~)` to understand what this means) the DataFrame based on columns `A` and `B`:

``` pd.melt(df, id_vars='C', value_vars=['A','B']) C variable value0 5 A a1 5 A b2 6 A a3 6 A b4 5 B None5 5 B c6 6 B c7 6 B None ```

By default, `melt(~)` creates a new column `variable` that indicate the field that the `value` column refers to (e.g. the first row tells us that the value for column `A` is `a`).

For the purpose of unstacking, we don't need this `variable` column, so we can use the `drop(~)` method to remove this column:

``` pd.melt(df, id_vars='C', value_vars=['A','B']).drop(columns=['variable']) C value0 5 a1 5 b2 6 a3 6 b4 5 None5 5 c6 6 c7 6 None ```

Finally, if we want to remove rows where value is `None`, we can use the `query(~)` method:

``` pd.melt(df, id_vars='C', value_vars=['A','B']).drop(columns=['variable']).query('value == value') C value0 5 a1 5 b2 6 a3 6 b5 5 c6 6 c ```

Here, the `query('value == value')` fetches rows where the value for the `value` column is not missing - this works because of the special property `NaN != NaN`.

Edited by 0 others
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
2
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!