Home >Backend Development >Python Tutorial >How Can Pandas\' `melt` Function Reshape a DataFrame with Additional Group and Name Columns?

How Can Pandas\' `melt` Function Reshape a DataFrame with Additional Group and Name Columns?

DDD
DDDOriginal
2024-11-28 00:04:111073browse

How Can Pandas' `melt` Function Reshape a DataFrame with Additional Group and Name Columns?

Pandas Melt Function: A Reshaping Tool

Problem

Consider a DataFrame df and a dictionary d. You aim to reshape df into a table with additional columns, namely Group and Name. The desired output should resemble:

    Group   Name  Year  Value
 0      A    Amy  2013      2
 1      A    Amy  2014      9
 2      B    Bob  2013      4
 3      B    Bob  2014      2
 4      B    Ben  2013      1
 5      B    Ben  2014      5
 6      C   Carl  2013      7
 7      C   Carl  2014      4
 8      C  Chris  2013      8
 9      C  Chris  2014      5
10  Other         2013      3
11  Other         2014      6

Solution

To achieve this reshape, we will utilize the Pandas melt function.

m = pd.melt(df, id_vars=['Year'], var_name='Name')

This will create a melted DataFrame m with the columns Year, Name, and value. To add the Group column, we reshape d as follows:

d2 = {}
for k, v in d.items():
  for item in v:
    d2[item] = k

We then map d2 to m['Name'] to populate the Group column.

m['Group'] = m['Name'].map(d2)

Finally, we move the 'Other' values from Name to Group:

mask = m['Name'] == 'Other'
m.loc[mask, 'Name'] = ''
m.loc[mask, 'Group'] = 'Other'

The resulting DataFrame m will match the desired output.

The above is the detailed content of How Can Pandas\' `melt` Function Reshape a DataFrame with Additional Group and Name Columns?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn