gpt4 book ai didi

Python CSV对字段中的数据求平方根

转载 作者:行者123 更新时间:2023-11-30 23:24:30 24 4
gpt4 key购买 nike

我有一个 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

我应该编辑什么脚本?

最佳答案

您正在计算 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)

关于Python CSV对字段中的数据求平方根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23394370/

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