如何为 pandas 交叉表设置值?
我刚刚学习 pandas,我什至不知道可以为交叉表设置值。 例如: 我的数据框是:
data = [['Alice', 1, 2], ['Bob', 2, 5], ['Cameron', 3, 1],['Alice', 2, 5],['Bob', 3, 1]]
df = pd.DataFrame(data, columns = ['Name', 'Music_id', 'Music_type'])
现在在 df 上应用交叉表:
ct = pd.crosstab([df.Name,df.Music_id],df.Music_type)
我得到: 交叉表的输出
但是,这不是我所期望的。
我希望它以某种方式显示如下:
Music_id | 1 | 2 | 3 |
---|---|---|---|
Name | |||
Alice | 2 | 5 | 0 |
Bob | 0 | 5 | 0 |
Cameron | 0 | 0 | 1 |
基本上,我想要它而不是计算名称与 Music_id 匹配的次数,它给出第三列的相对值(音乐类型)。我是否使用了正确的函数来做到这一点?任何建议表示赞赏!
I am just learning pandas, I do not know even possible to set values to a crosstab.
For example:
My data frame is:
data = [['Alice', 1, 2], ['Bob', 2, 5], ['Cameron', 3, 1],['Alice', 2, 5],['Bob', 3, 1]]
df = pd.DataFrame(data, columns = ['Name', 'Music_id', 'Music_type'])
Now apply crosstab on df:
ct = pd.crosstab([df.Name,df.Music_id],df.Music_type)
I got:
The output of crosstab
However, that is not what I expected.
I want it shows somehow like this:
Music_id | 1 | 2 | 3 |
---|---|---|---|
Name | |||
Alice | 2 | 5 | 0 |
Bob | 0 | 5 | 0 |
Cameron | 0 | 0 | 1 |
Basically, I want it instead of counting how many times the Name matches Music_id, it gives the relative value from the third column (Music_type). Did I use the right function to do that? Any advice is appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试以下解决方案来解决:
pd.crosstab
df.pivot
You can try this solutions to resolve :
pd.crosstab
df.pivot