简体   繁体   English

如何将具有 n 个值的 DataFrame 列转换为 n 个二进制列?

[英]How to convert column of DataFrame with n values to n binary columns?

I am prety sure that there is a pandas function to do so but I could not find it when I was looking at the documentation and googled it.我很确定有一个 Pandas 函数可以这样做,但是当我查看文档并用谷歌搜索时我找不到它。 Maybe you can help me.也许你可以帮助我。 Here is what I want to do:这是我想要做的:

import pandas as pd

data = {'col1': ['val1','val2','val3'],
        'col2': ['feat1','feat1','feat2']
       }
df = pd.DataFrame(data)
print (df)

>    col1   col2
> 0  val1  feat1
> 1  val2  feat1
> 2  val3  feat2

and I want to have the dataframe with this shape:我想要这个形状的数据框:

>    col1  feat1  feat2
> 0  val1      1      0
> 1  val2      1      0
> 2  val3      0      1

Best P最佳P

print(pd.get_dummies(df.set_index('col1'), prefix='', prefix_sep=''))

Prints:印刷:

      feat1  feat2
col1              
val1      1      0
val2      1      0
val3      0      1

您也可以使用crosstab

pd.crosstab(df.col1, df.col2)

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

相关问题 将 Pandas 数据框转换为 N 对 1 字典,其中 N 列是指向单个列作为值的键 - Convert a Pandas dataframe to a N-to-1 dictionary, where N columns are keys pointing to a single column as the values 将N x N数据帧转换为3列数据帧 - Convert N by N Dataframe to 3 Column Dataframe 如何将 pivot 一个具有 n 个类别的列转换为 n 个二进制值列? - How to pivot one colum with n categories into n binary values column? 将 pandas dataframe 从 m 行 n 列重塑为具有一列值的 mxn 行 - reshaping pandas dataframe from m rows n columns to m x n rows with one column of values 如何计算 pandas dataframe 的 n 列中存在值的人数 - How to count the number of persons with values present in n columns of a pandas dataframe 如何在单行数据框中获取与 n 个最大值对应的列? - How to get columns corresponding to n largest values in a single row dataframe? 如何将文本变量转换为python数据框列并按“ \\ n”拆分行? - How to convert a text variable to a python dataframe column and split rows by “\n”? 将Pandas Dataframe中的列拆分为n列 - Split column in a Pandas Dataframe into n number of columns 将 Dask Dataframe 中的列拆分为 n 列 - Split column in a Dask Dataframe into n number of columns DataFrame:N个最大索引值(从级别= 1)到n列 - DataFrame: N largest indexes values (from level=1) to n columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM