[英]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.