简体   繁体   English

如何将 dataframe 转换为 0 和 1 的 ndarray?

[英]How to convert a dataframe to ndarray of 0s and 1s?

I have a Pandas dataframe which looks like this:我有一个 Pandas dataframe 看起来像这样:

col_1 col_2
a     4
a     3
b     2
c     2
d     1
b     4
c     1

I need to transform it into a NumPy array of 2D-arrays where each 2D-array corresponds to one of the letters.我需要将它转换为 NumPy 二维数组数组,其中每个二维数组对应于其中一个字母。 For example, if 'a' doesn't occur together with 1 and 2, and occurs with 3 and 4, 2D array corresponding to it should look like [0, 0, 1, 1] .例如,如果 'a' 没有与 1 和 2 一起出现,而是与 3 和 4 一起出现,则对应的二维数组应该类似于[0, 0, 1, 1] So in this example I need:所以在这个例子中我需要:

[[0, 0, 1, 1], [0, 1, 0, 1], [0, 1, 0, 0], [1, 0, 0, 1]]

What is the best way to do this?做这个的最好方式是什么?

Here is one way crosstab这是crosstab的一种方式

l = pd.crosstab(df.col_1,df.col_2).values.tolist()
Out[23]: [[0, 0, 1, 1], [0, 1, 0, 1], [1, 1, 0, 0], [1, 0, 0, 0]]

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

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