Pandas 透视数据框并根据它们是否存在将新列设置为 True/False [英] Pandas pivot dataframe and setting the new columns as True/False based on if they existed or not

查看:74
本文介绍了Pandas 透视数据框并根据它们是否存在将新列设置为 True/False的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,我想旋转我的数据框(我认为它需要旋转?)

As the title states I want to pivot my dataframe (I believe it needs to be pivoted?)

假设我有一个看起来像这样的 df:

Let's say I have a df that looks like this:

df = pd.DataFrame({'ID' : [0, 0, 1, 1, 1], 
                   'REV' : [0, 0, 1, 1, 1],
                   'GROUP' : [1, 2, 1, 2, 3]})


+----+-----+-------+
| ID | REV | GROUP |
+----+-----+-------+
|  0 |   0 |     1 |
|  0 |   0 |     2 |
|  1 |   1 |     1 |
|  1 |   1 |     2 |
|  1 |   1 |     3 |
+----+-----+-------+

我想做某种透视,所以我的表格结果看起来像

I want to do some kind of pivot so my result of the table looks like

+----+-----+------+------+-------+
| ID | REV |  1   |  2   |   3   |
+----+-----+------+------+-------+
|  0 |   0 | True | True | False |
|  1 |   1 | True | True | True  |
+----+-----+------+------+-------+

现在来自 GROUP 列的值变成了自己的列.这些列中的每一列的值是基于原始 df 是否具有该组的 T/F.

Now the values from the GROUP column becomes there own column. The value of each of those columns is T/F based on if the original df had that group or not.

有什么推荐吗?这似乎是一个支点,但在使用支点时,我是个大菜鸟

Any recommendations? This seems like a pivot thing, but I am a big noob when it comes to working with pivots

推荐答案

尝试使用 crosstab

out = pd.crosstab([df.ID,df.REV],df.GROUP).ne(0).reset_index().rename_axis(None,axis=1)
out
   ID  REV     1     2      3
0   0    0  True  True  False
1   1    1  True  True   True

这篇关于Pandas 透视数据框并根据它们是否存在将新列设置为 True/False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆