简体   繁体   English

将pandas df列数据转置为行

[英]transpose pandas df column data to rows

I have a df as the following 我有以下df

email     | date | type
_________________________
xy@xy.com | 6/1  | order
xy@xy.com | 6/1  | return
cd@xy.com | 6/2  | return
ab@xy.com | 6/2  | return

I'm trying to individualize the type of column into each row keeping the data 我正在尝试将每一列的类型分别保持数据

email     | date | order | return
_________________________________
xy@xy.com | 6/1  | 1     |   0
xy@xy.com | 6/1  | 0     |   1
cd@xy.com | 6/2  | 0     |   0
ab@xy.com | 6/2  | 0     |   0

I've been trying to use pd.melt but the output doesn't seem to be what i'm looking for. 我一直在尝试使用pd.melt但输出似乎不是我想要的。 referenced from Pandas dataframe transpose with original row and column values Pandas数据框中引用的具有原始行和列值的转置

You should have a look at how to create dummy variables from categorical columns. 您应该看看如何从分类列中创建虚拟变量。

There is a nice Pandas function to achieve that named "get_dummies": 有一个很好的Pandas函数可以实现名为“ get_dummies”的函数:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html

Demonstration 示范

df.drop('type', 1).join(pd.get_dummies(df['type']))

       email date  order  return
0  xy@xy.com  6/1      1       0
1  xy@xy.com  6/1      0       1
2  cd@xy.com  6/2      0       1
3  ab@xy.com  6/2      0       1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM