简体   繁体   English

如何制作 0 和 1 的 dataframe 使得每个唯一值都是一列?

[英]How to make a dataframe of 0 and 1 such that each unique value is a column?

I have the following df我有以下df

在此处输入图像描述

Then I would like to transform df into df1 whose column are unique values of df .然后我想将df转换为df1 ,其列是df的唯一值。 Take the first row of df as an example, its year is 2012 and its report is 4. then column year_2012 and column reports_4 take value 1. The other columns take value 0.df的第一行为例,它的year是2012,它的report是4,那么year_2012列和reports_4列取值为1,其他列取值为0。

在此处输入图像描述

import pandas as pd
data = {'year': [2012, 2012, 2013, 2014, 2014], 
        'reports': [4, 24, 31, 2, 3]}
df = pd.DataFrame(data)

Could you please elaborate how to obtain such result?您能否详细说明如何获得这样的结果?

This is pd.get_dummies :这是pd.get_dummies

cols = ['year', 'reports']

pd.concat([pd.get_dummies(df[col], prefix=col) for col in cols],
          axis=1)

Or even easier, credit goes to @ScottBoston :或者更简单,归功于@ScottBoston

pd.get_dummies(df, columns=df.columns)

Output: Output:

   year_2012  year_2013  year_2014  reports_2  reports_3  reports_4  reports_24  reports_31
0          1          0          0          0          0          1           0           0
1          1          0          0          0          0          0           1           0
2          0          1          0          0          0          0           0           1
3          0          0          1          1          0          0           0           0
4          0          0          1          0          1          0           0           0

暂无
暂无

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

相关问题 如何计算数据框中另一列中每个唯一值对应的值? - How to count the values corresponding to each unique value in another column in a dataframe? 如何使数据框中的每一行每一列都有一个值? - How to make each row in dataframe have one value for each column? 将 DataFrame 中的每个唯一值重塑为列 - Reshape each unique value in DataFrame to column 如何使用for循环将列值添加到数据框字典中,以便每个数据框都获得一个唯一的列? - How to add a column value into dataframe dictionary using a for loop so that each dataframe gets a unique column? 对于 pandas dataframe 列中的每个唯一值,制作一个 go.Figure 并散布 t - For each unique value in pandas dataframe column, make a go.Figure and scatter t 如何在python中使用另一个数据帧的列的唯一列值和值计数制作数据帧? - How to make a dataframe in python with unique column values and value counts of a column of another dataframe? 如何根据数据框中的日期时间列值查找列中每个唯一值的前一个值? - How to find previous of each unique value in a column based upon datetime column values in a dataframe? 如何使postgresql中的每一列分别唯一? - How to make separately unique each column in postgresql? 按每个唯一列值的最近日期过滤 Pandas 数据框 - Filter Pandas dataframe by most recent date for each unique column value 用i替换已排序的Pandas数据框列中的每个唯一值 - Replace each unique value in a sorted Pandas dataframe column with i
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM