Ask Your Question
2

Does Pandas have a comparable feature to uncount in tidyr?

asked 2023-06-01 20:56:27 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-01 21:18:02 +0000

bukephalos gravatar image

Yes, Pandas has a comparable feature to uncount in tidyr, which is the melt function. The melt function can transform a wide DataFrame into a long DataFrame by unpivoting.

For example, consider a DataFrame where the columns are different subjects, and each row contains the scores of a student for those subjects:

import pandas as pd

df = pd.DataFrame({"Name":["John","Sally","Bob"],
                   "Math":[80,90,70],
                   "Science":[75,85,80],
                   "History":[85,75,90]})
    Name  Math  Science  History
0   John    80       75       85
1  Sally    90       85       75
2    Bob    70       80       90



md5-4305cf7a71d9d43854d6d0b98bd39351



df_melted = df.melt(id_vars=["Name"],
                    value_vars=["Math","Science","History"],
                    var_name="Subject",
                    value_name="Score")



md5-1aa6c8dbdcece396d25683060ea82f2b



    Name  Subject  Score
0   John     Math     80
1  Sally     Math     90
2    Bob     Math     70
3   John  Science     75
4  Sally  Science     85
5    Bob  Science     80
6   John  History     85
7  Sally  History     75
8    Bob  History     90

Now the DataFrame is in long format, with separate rows for each subject and score of each student.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-01 20:56:27 +0000

Seen: 18 times

Last updated: Jun 01 '23