![](/img/trans.png)
[英]Pandas Dataframe: How to parse integers into string of 0s and 1s?
[英]How to convert a dataframe to ndarray of 0s and 1s?
我有一個 Pandas dataframe 看起來像這樣:
col_1 col_2
a 4
a 3
b 2
c 2
d 1
b 4
c 1
我需要將它轉換為 NumPy 二維數組數組,其中每個二維數組對應於其中一個字母。 例如,如果 'a' 沒有與 1 和 2 一起出現,而是與 3 和 4 一起出現,則對應的二維數組應該類似於[0, 0, 1, 1]
。 所以在這個例子中我需要:
[[0, 0, 1, 1], [0, 1, 0, 1], [0, 1, 0, 0], [1, 0, 0, 1]]
做這個的最好方式是什么?
這是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.