我有一个 pandas 系列,每个单元格包含一串整数(每个字符串中的整数数量相同,用空格分隔),例如
s = pd.Series(['1 17 -3 ... n'],['100 -27 344 ... n'],...,['0 14 2 ... n'])
我知道如何将单个单元格转换为 numpy 向量:
arr = np.asarray(s[0].split(' '), dtype = np.float32)
我还知道如何将整个系列转换为矩阵,这是我的最终目标:
X = np.zeros((len(s), number_of_ints_in_string))
for i, cell in enumerate(s):
X[i,:] = np.asarray(cell.split(' '), dtype = np.float32)
问题是,对于一个很长的系列(这是我的情况),这很慢。有没有更快的方法来做到这一点?
最佳答案
使用Series.str.split
将 expand=True
转换为 DataFrame,然后通过 DataFrame.to_numpy
将其转换为 numpy 数组
:
s = pd.Series(['1 17 -3','100 -27 344','0 14 2'])
print (s)
0 1 17 -3
1 100 -27 344
2 0 14 2
dtype: object
arr = s.str.split(expand=True).to_numpy().astype(np.float32)
print (arr)
[[ 1. 17. -3.]
[100. -27. 344.]
[ 0. 14. 2.]]
另一个想法是使用列表理解:
arr = np.asarray([x.split() for x in s], dtype = np.float32)
print (arr)
[[ 1. 17. -3.]
[100. -27. 344.]
[ 0. 14. 2.]]
第二个解决方案速度更快,为 300k 行:
s = pd.Series(['1 17 -3','100 -27 344','0 14 2'])
s = pd.concat([s] * 100000, ignore_index=True)
In [52]: %timeit np.asarray([x.split() for x in s], dtype = np.float32)
521 ms ± 10.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [53]: %timeit s.str.split(expand=True).to_numpy().astype(np.float32)
939 ms ± 6.08 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
关于python - 将 pandas 系列字符串整数转换为 numpy 矩阵 - 高效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59745959/