对CSV应用一个简单函数并保存多个CSV文件

2024-06-16 13:45:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过将每个值与一系列值相乘来复制数据,并将结果保存为CSV。你知道吗

我创建了一个函数“Replicate\ u Data”,它接受输入numpy数组,并与一个范围之间的随机值相乘。创建100个文件并另存为P3D1、P4D1等的最佳方法是什么。你知道吗

def Replicate_Data(data: np.ndarray) -> np.ndarray:
    Rep_factor= random.uniform(-3,7)
    data1 = data * Rep_factor
    return data1

P2D1 = Replicate_Data(P1D1)
np.savetxt("P2D1.csv", P2D1, delimiter="," , dtype = complex)

Tags: 文件csv数据函数numpydatanp数组
1条回答
网友
1楼 · 发布于 2024-06-16 13:45:10

这是一个你可以参考的例子。你知道吗

我生成名为toy的玩具数据,然后使用np.random.uniform生成n随机值并称之为randos,然后使用numpy广播将这两个对象相乘形成out。你也可以在一个循环中做这个乘法(实际上就是你保存的那个):根据你的输入数组的大小,它可能会像我写的那样占用大量内存。更完整的答案可能取决于输入数据的形状。你知道吗

import numpy as np
toy = np.random.random(size=(2,2)) # a toy input array
n = 100 # number of random values
randos = np.random.uniform(-3,7,size=n) # generate 100 uniform randoms
# now multiply all elements in toy by the randoms in randos
out = toy[None,...]*randos[...,None,None] # this depends on the shape.
# this will work only if toy has two dimensions. Otherwise requires modification
# it will take a lot of memory... 100*toy.nbytes worth

# now save in the loop.. 
for i,o in enumerate(out):
    name = 'P{}D1'.format(str(i+1))
    np.savetxt(name,o,delimiter=",")


# a second way without the broadcasting (slow, better on memory)
# more like 2*toy.nbytes
#for i,r in enumerate(randos):
#    name = 'P{}D1'.format(str(i+1))
#    np.savetxt(name,r*toy,delimiter=",")

相关问题 更多 >