How to Reshape Data from Wide to Long Format in Pandas?

DDD
Release: 2024-11-16 14:57:03
Original
104 people have browsed it

How to Reshape Data from Wide to Long Format in Pandas?

Reshaping Data from Wide to Long in Pandas

In pandas, dataframes can be transformed from a wide format to a long format. This is useful when wanting to merge the dataframe with another one based on shared columns and dates.

Consider the following dataframe:

        AA  BB  CC
date
05/03     1   2   3
06/03     4   5   6
07/03     7   8   9
08/03     5   7   1
Copy after login

To transform this dataframe into a long format, use either pandas.melt or pandas.DataFrame.melt.

df = pd.DataFrame({
    'date' : ['05/03', '06/03', '07/03', '08/03'],
    'AA' : [1, 4, 7, 5],
    'BB' : [2, 5, 8, 7],
    'CC' : [3, 6, 9, 1]
}).set_index('date')
Copy after login
To convert, reset the index and then melt:
Copy after login
df = df.reset_index()
pd.melt(df, id_vars='date', value_vars=['AA', 'BB', 'CC'])
Copy after login

Alternatively, use .reset_index after .melt to remove the need to specify value_vars.

dfm = df.melt(ignore_index=False).reset_index()
Copy after login

The resulting dataframe would look like:

     date variable  value
0   05/03       AA      1
1   06/03       AA      4
2   07/03       AA      7
3   08/03       AA      5
4   05/03       BB      2
5   06/03       BB      5
6   07/03       BB      8
7   08/03       BB      7
8   05/03       CC      3
9   06/03       CC      6
10  07/03       CC      9
11  08/03       CC      1
Copy after login

The above is the detailed content of How to Reshape Data from Wide to Long Format in Pandas?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template