[英]Fast way to convert strings into lists of ints in a Pandas column?
我正在尝试计算大型数据帧中列中所有字符串之间的汉明距离。 我在此列中有超过100,000行,因此所有成对组合都是10x10 ^ 9比较。 这些串是短DNA序列。 我想快速将列中的每个字符串转换为整数列表,其中唯一的整数表示字符串中的每个字符。 例如
"ACGTACA" -> [0, 1, 2, 3, 1, 2, 1]
然后我使用scipy.spatial.distance.pdist
快速有效地计算所有这些之间的汉明距离。 在熊猫中有快速的方法吗?
我尝试过使用apply
但速度很慢:
mapping = {"A":0, "C":1, "G":2, "T":3}
df.apply(lambda x: np.array([mapping[char] for char in x]))
get_dummies
和其他分类操作不适用,因为它们在每行级别上运行。 不在行内。
由于汉明距离并不关心幅度差异,因此我可以用df.apply(lambda x: np.array([mapping[char] for char in x]))
替换df.apply(lambda x: np.array([mapping[char] for char in x]))
来获得大约40-60%的加速df.apply(lambda x: map(ord, x))
在虚构数据集上。
我没有测试它的性能,但你也可以尝试类似的东西
atest = "ACGTACA"
alist = atest.replace('A', '3.').replace('C', '2.').replace('G', '1.').replace('T', '0.').split('.')
anumlist = [int(x) for x in alist if x.isdigit()]
结果是:
[3, 2, 1, 0, 3, 2, 3]
编辑:好的,所以用atest =“ACTACA”测试它* 100000需要一段时间:/也许不是最好的主意......
编辑5:另一项改进:
import datetime
import numpy as np
class Test(object):
def __init__(self):
self.mapping = {'A' : 0, 'C' : 1, 'G' : 2, 'T' : 3}
def char2num(self, astring):
return [self.mapping[c] for c in astring]
def main():
now = datetime.datetime.now()
atest = "AGTCAGTCATG"*10000000
t = Test()
alist = t.char2num(atest)
testme = np.array(alist)
print testme, len(testme)
print datetime.datetime.now() - now
if __name__ == "__main__":
main()
对于110.000.000个字符大约需要16秒,并且让处理器忙碌而不是你的ram:
[0 2 3 ..., 0 3 2] 110000000
0:00:16.866659
创建测试数据
In [39]: pd.options.display.max_rows=12
In [40]: N = 100000
In [41]: chars = np.array(list('ABCDEF'))
In [42]: s = pd.Series(np.random.choice(chars, size=4 * np.prod(N)).view('S4'))
In [45]: s
Out[45]:
0 BEBC
1 BEEC
2 FEFA
3 BBDA
4 CCBB
5 CABE
...
99994 EEBC
99995 FFBD
99996 ACFB
99997 FDBE
99998 BDAB
99999 CCFD
dtype: object
这些实际上不必与我们这样做的长度相同。
In [43]: maxlen = s.str.len().max()
In [44]: result = pd.concat([ s.str[i].astype('category',categories=chars).cat.codes for i in range(maxlen) ], axis=1)
In [47]: result
Out[47]:
0 1 2 3
0 1 4 1 2
1 1 4 4 2
2 5 4 5 0
3 1 1 3 0
4 2 2 1 1
5 2 0 1 4
... .. .. .. ..
99994 4 4 1 2
99995 5 5 1 3
99996 0 2 5 1
99997 5 3 1 4
99998 1 3 0 1
99999 2 2 5 3
[100000 rows x 4 columns]
因此,您可以根据相同的类别进行分解(例如,代码是有意义的)
并且非常快
In [46]: %timeit pd.concat([ s.str[i].astype('category',categories=chars).cat.codes for i in range(maxlen) ], axis=1)
10 loops, best of 3: 118 ms per loop
使用ord
或基于字典的查找确切地映射A-> 0,C-> 1等似乎没有太大区别:
import pandas as pd
import numpy as np
bases = ['A', 'C', 'T', 'G']
rowlen = 4
nrows = 1000000
dna = pd.Series(np.random.choice(bases, nrows * rowlen).view('S%i' % rowlen))
lookup = dict(zip(bases, range(4)))
%timeit dna.apply(lambda row: map(lookup.get, row))
# 1 loops, best of 3: 785 ms per loop
%timeit dna.apply(lambda row: map(ord, row))
# 1 loops, best of 3: 713 ms per loop
Jeff的解决方案在性能方面也差不多:
%timeit pd.concat([dna.str[i].astype('category', categories=bases).cat.codes for i in range(rowlen)], axis=1)
# 1 loops, best of 3: 1.03 s per loop
这种方法相对于将行映射到整数列表的一个主要优点是,可以通过.values
属性将类别视为单个(nrows, rowlen)
uint8数组,然后可以将其直接传递给pdist
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.