gpt4 book ai didi

Python:元素明智除法运算符错误

转载 作者:行者123 更新时间:2023-12-01 04:05:56 25 4
gpt4 key购买 nike

我想知道是否有更好的方法在 python 中执行元素除法运算符。下面的代码假设用 B1 行执行除法 A1,用 B2 行执行除法 A2,因此我的预期输出只有两行。然而,划分部分是A1与B1、A1与B2、A2与B1、A2与B2。谁能帮我吗?

二进制文件使用 1000,0100,0010,0001 表示 A、C、G、T。 除法文件有四列,每列 A、C、G、T,因此获得的值 之前必须相应地划分。

代码

import numpy as np
from numpy import genfromtxt
import csv
csvfile = open('output.csv', 'wb')
writer = csv.writer(csvfile)

#open csv file into arrays
with open('binary.csv') as actg:
actg=actg.readlines()
with open('single.csv') as single:
single=single.readlines()
with open('division.csv') as division:
division=division.readlines()

# Converting binary line and single line into 3 rows and 4 columns
# binary values using reshape
for line in actg:
myarray = np.fromstring(line, dtype=float, sep=',')
myarray = myarray.reshape((-1, 3, 4))
for line2 in single:
single1 = np.fromstring(line2, dtype=float, sep=',')
single1 = single1.reshape((-1, 4))
# This division is in 2 rows and 4 column: first column
# represents 1000, 2nd-0100, 3rd-0010, 4th-0001 in the
# binary.csv. Therefore the division part where 1000's
# value should be divided by 1st column, 0010 should be
# divided by 3rd column value
for line1 in division:
division1 = np.fromstring(line1, dtype=float, sep=',')
m=np.asmatrix(division1)
m=np.array(m)
res2 = (single1[np.newaxis,:,:] / m[:,np.newaxis,:] * myarray).sum(axis=-1)
print(res2)
writer.writerow(res2)


csvfile.close()

二进制.csv

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.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

division.csv

0.4,0.5,0.7,0.1
0.2,0.8,0.9,0.3

预期输出

 0.44,0.3,6.5
0.26,0.6,2.2

实际输出

0.44,0.3,6.5
0.275,0.6,2.16666667
0.32857143,0.3,1.1
0.25555556,0.6,2.2

错误说明

让分割文件如下:

A,B,C,D
E,F,G,H

令单次和二进制计算结果如下:

1,3,4
2,2,1

让数字1,2,3,4分配给位置A,B,C,D和下一行E,F,G,H

1/A,3/C,4/D
2/F,2/F,1/E

其中 1 除以 A,3 除以 C,依此类推。基本上这就是代码可以做的事情。不幸的是,除法部分恰好像前面描述的那样。 221 与 BBC 一起运行,134 与 EGH 一起运行,因此输出有 4 行,这不是我想要的。

最佳答案

我不知道这是否是您正在寻找的东西,但这里有一个简短的方法来获得(我认为)您想要的东西:

import numpy as np

binary = np.genfromtxt('binary.csv', delimiter = ',').reshape((2, 3, 4))
single = np.genfromtxt('single.csv', delimiter = ',').reshape((1, 3, 4))
divisi = np.genfromtxt('division.csv', delimiter = ',').reshape((2, 1, 4))

print(np.sum(single / divisi * binary, axis = -1))

输出:

[[ 0.44        0.3         6.5       ]
[ 0.25555556 0.6 2.2 ]]

关于Python:元素明智除法运算符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35598337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com