Skip to main content
 首页 » 编程设计

python之numpy/ Pandas : How to convert a series of strings of zeros and ones into a matrix

2025年05月04日11del

我有一个以这种格式到达的数据:

[ 
  (1, "000010101001010101011101010101110101", "aaa", ... ), 
  (0, "111101010100101010101110101010111010", "bb", ... ), 
  (0, "100010110100010101001010101011101010", "ccc", ... ), 
  (1, "000010101001010101011101010101110101", "ddd", ... ), 
  (1, "110100010101001010101011101010111101", "eeee", ... ), 
  ... 
] 

在元组格式中,它看起来像这样:

(Y, X, other_info, ... ) 

归根结底,我需要使用 Y 和 X 训练分类器(例如 sklearn.linear_model.logistic.LogisticRegression)。

将 1 和 0 的字符串转换为类似 np.array 的东西的最直接方法是什么,以便我可以通过分类器运行它?似乎这里应该有一个简单的答案,但我一直想不出/谷歌一个。

一些注意事项:

  • 我已经在使用 numpy/pandas/sklearn,所以这些库中的任何东西都可以使用。
  • 对于我正在做的很多事情,将 other_info 列放在一个 DataFrame 中很方便
  • 字符串很长(约 20,000 列),但整个数据框不是很高(约 500 行)。

请您参考如下方法:

由于您主要询问的是将一串 1 和 0 转换为 numpy 数组的方法,因此我将提供如下解决方案:

d = '0101010000' * 2000 # create a 20,000 long string of 1s and 0s 
d_array = np.fromstring(d, 'int8') - 48 # 48 is ascii 0. ascii 1 is 49 

这比 @DSM's 更有利速度方面的解决方案:

In [21]: timeit numpy.fromstring(d, dtype='int8') - 48 
10000 loops, best of 3: 35.8 us per loop 
 
In [22]: timeit numpy.fromiter(d, dtype='int', count=20000) 
100 loops, best of 3: 8.57 ms per loop