Python:如何根据其表示执行除法?

时间:2016-02-23 05:29:32

标签: python csv elementwise-operations

我想对其字母进行分割。举个例子如下:

给出的二进制文件采用csv格式:

A=1000, C=0100, G=0010, T=0001

binary.csv:CAT,GAA

0,1,0,0,1,0,0,0,0,0,0,1
0,0,1,0,1,0,0,0,1,0,0,0

binary.csv需要与csv文件中的单行值相乘。

single.csv:

0.28,0.22,0.23,0.27,0.12,0.29,0.34,0.21,0.44,0.56,0.51,0.65

下面的代码对文件和输出中的值进行乘法运算:

0.22,0.12,0.65
0.23,0.12,0.44

代码

import csv

with open('single.csv', 'rb') as csvfile:
    for row in csv.reader(csvfile, delimiter=','):
        reals = row

with open('binary.csv', 'rb') as csvfile:
    pwreader = csv.reader(csvfile, delimiter=',')

    with open('output.csv','wb') as testfile:
        csv_writer=csv.writer(testfile)
        for row in pwreader:
            result = []            
            for i,b in enumerate(row):
                if b == '1' :
                    result.append(reals[i])
            csv_writer.writerow(result)

我有额外的csv文件,我想先前执行除法             输出和相对于其字母表划分的值:

 A   C   G   T
 0.4,0.5,0.7,0.1
 0.2,0.8,0.9,0.3

CAT的值除以0.5,0.4,0.1,GAA除以0.9,0.2,0.2,这样我就可以得到一个全新的输出如下:

 0.44,0.3,6.5
 0.26,0.6,2.2

在数组上使用numpy可能会解决这个问题,但是当使用超过几千个数据时,它可能不合适。当我尝试使用60,000 ++数据时发生内存不足。

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

import numpy as np

让我们假设您可以从文件中提取这些内容:

actg = np.array([
    [0,1,0,0,1,0,0,0,0,0,0,1],
    [0,0,1,0,1,0,0,0,1,0,0,0]
])

single = np.array([0.28,0.22,0.23,0.27,0.12,0.29,0.34,0.21,0.44,0.56,0.51,0.65])

division = np.array([
    [0.4,0.5,0.7,0.1],
    [0.2,0.8,0.9,0.3]
])

首先,让actg变为更有用的格式:

>>> actg = actg.reshape((-1, 3, 4))
array([[[0, 1, 0, 0],
        [1, 0, 0, 0],
        [0, 0, 0, 1]],

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

我们对单身做同样的事情:

>>> single = single.reshape((-1, 4))
array([[ 0.28,  0.22,  0.23,  0.27],
       [ 0.12,  0.29,  0.34,  0.21],
       [ 0.44,  0.56,  0.51,  0.65]])

所以现在我们的对象被索引为:

  • actg[row, col, symbol]
  • single[col, symbol]
  • division[row, symbol]

此时,我们只是乘以和和

>>> res_1 = (single * actg).sum(axis=-1)
array([[ 0.22,  0.12,  0.65],
       [ 0.23,  0.12,  0.44]])

对于除法,我们需要使用col

插入一个维度以匹配上面的np.newaxis
>>> divide_by = (division[:,np.newaxis,:] * actg).sum(axis=-1)
array([[ 0.5,  0.4,  0.1],
       [ 0.9,  0.2,  0.2]])

最后,我们只是进行分工

>>> res2 = res_1 / divide_by
array([[ 0.44      ,  0.3       ,  6.5       ],
       [ 0.25555556,  0.6       ,  2.2       ]])

奖励一个班轮:

res2 = (single[np.newaxis,:,:] / division[:,np.newaxis,:] * actg).sum(axis=-1)