Python CSV在字段中采用数据的平方根

时间:2014-04-30 17:23:39

标签: python csv sqrt

我有一个包含字段中数字的CSV文件,

enter image description here

我编写了一个脚本,尝试在此CSV文件的每个字段中取平方根数字

import sys, os

import csv, math
import tempfile
import shutil

element = []
filename = 'test.csv'
with open(filename, 'rb') as f, tempfile.NamedTemporaryFile(mode='wb', delete=False) as g:
    writer = csv.writer(g, delimiter = ',')
    for row in csv.reader(f):
        element = element in row
        row = math.sqrt(element)
        writer.writerow([row])

shutil.move(g.name, filename)

但输出不是我想要的,

enter image description here

我应该如何编辑我的脚本?

3 个答案:

答案 0 :(得分:1)

我认为你过于复杂。尝试类似:

import numpy as np

data = np.loadtxt('input.csv', delimiter=',')
data = np.sqrt(data)
data = np.where(np.isnan(data), 0, data)
np.savetxt('output.csv', data, delimiter=',')

注意:这假设您没有阅读不规则结构化的数据。

答案 1 :(得分:1)

您正在计算False的平方根,这与平方根0

相同
>>> element = element in row
False
>>> row = math.sqrt(element)
0

像这样修改:

filename = 'test.csv'
with open(filename, 'rb') as f, tempfile.NamedTemporaryFile(mode='wb', delete=False) as g:
    writer = csv.writer(g, delimiter = ',')
    for row in csv.reader(f):
        row = [math.sqrt(float(num)) for num in row]
        writer.writerow(row)

答案 2 :(得分:1)

代码中的错误是因为这一行:

element = element in row

返回True或False。对真或假的平方根操作毫无意义。

这是代码的示例运行:

>>> element = []
>>> row = [1, 2, 3, 4]
>>> element = element in row
>>> element
False
>>> import math
>>> math.sqrt(element)
0.0

在代码中替换这些行:

    element = element in row
    row = math.sqrt(element)
    writer.writerow([row])

使用:

    sqrts = [math.sqrt(x) for x in row]
    writer.writerow(sqrts)

示例:

>>> sqrts = [math.sqrt(x) for x in row]
>>> sqrts
[1.0, 1.4142135623730951, 1.7320508075688772, 2.0]