旋转具有重复值的数据框

发布于 2025-02-01 21:23:33 字数 426 浏览 2 评论 0原文

我有一个类似的数据框:

df = pd.DataFrame({'id':{1,2,3,4,4},
'course':{'english', 'art', 'math', 'english', 'chem'},
'result':{'a','b','c','a','b'}})

我想旋转此功能:

course  English art math sci chem 
id
1         a      -    -   -    -   
2         -      b    -   -    -
3         -      -    c   -    -
4         a      -    -   -    b

注意:ID,resuct&课程。 由于重复的值,我无法透视它。

I have a dataframe like this:

df = pd.DataFrame({'id':{1,2,3,4,4},
'course':{'english', 'art', 'math', 'english', 'chem'},
'result':{'a','b','c','a','b'}})

I want to pivot this such that:

course  English art math sci chem 
id
1         a      -    -   -    -   
2         -      b    -   -    -
3         -      -    c   -    -
4         a      -    -   -    b

Note: There are repeated values in ID, results & Courses.
Due to the duplicate values, I am not able to pivot it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

櫻之舞 2025-02-08 21:23:33

Pivot正常工作。我认为问题是您的意见。您为每个键都有一组,因此重复项消失了。使用列表并有效。

# use a list for values
df = pd.DataFrame({'id':[1,2,3,4,4],
                   'course':['english', 'art', 'math', 'english', 'chem'],
                   'result':['a','b','c','a','b']})
# pivot and reindex
df.pivot(*df).reindex(columns=['english', 'art', 'math', 'sci', 'chem']).fillna('-')

pivot works just fine. I think the issue is with your input. You have a set for each key, so the duplicates disappear. Use a list and it works.

# use a list for values
df = pd.DataFrame({'id':[1,2,3,4,4],
                   'course':['english', 'art', 'math', 'english', 'chem'],
                   'result':['a','b','c','a','b']})
# pivot and reindex
df.pivot(*df).reindex(columns=['english', 'art', 'math', 'sci', 'chem']).fillna('-')

enter image description here

小…楫夜泊 2025-02-08 21:23:33

让我们使用set_indexunstack

df.set_index(['id','course'])['result'].unstack(fill_value='-')

输出:

course art chem english math
id                          
1        -    -       a    -
2        b    -       -    -
3        -    -       -    c
4        -    b       a    -

Let's use set_index and unstack:

df.set_index(['id','course'])['result'].unstack(fill_value='-')

Output:

course art chem english math
id                          
1        -    -       a    -
2        b    -       -    -
3        -    -       -    c
4        -    b       a    -
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文