gpt4 book ai didi

ruby - 使用 Ruby 将数组写入多列 CSV 格式

转载 作者:数据小太阳 更新时间:2023-10-29 08:35:39 26 4
gpt4 key购买 nike

我在 Ruby 中有一个数组,我试图将其输出到 CSV 文件(或文本)。然后我可以轻松地将其转移到另一个 XML 文件进行绘图。

我似乎无法像这样获得输出(文本格式)。相反,我得到一行数据,它只是一个大数组。

0,2
0,3
0,4
0,5

我最初尝试过类似的东西

File.open('02.3.gyro_trends.text' , 'w') { |file| trend_array.each { |x,y| file.puts(x,y)}}

然后输出

0.2
46558
0
46560
0
....etc etc.

任何人都可以指出我的“写”方向以获得:

(i) .text 文件,可以像这样放置我的数据。

trend_array[0][0], trend_array[0][1] 
trend_array[1][0], trend_array[1][1]
trend_array[2][0], trend_array[2][1]
trend_array[3][0], trend_array[3][1]

(ii) .csv 文件,将此数据放在单独的列中。
编辑 我最近在我的数组中添加了两个以上的值,请结合 Cameck 的解决方案查看我的答案。

这就是我目前所拥有的。

trend_array=[]
j=1

# cycle through array and find change in gyro data.

while j < gyro_array.length-2

if gyro_array[j+1][1] < 0.025 && gyro_array[j+1][1] > -0.025
trend_array << [0, gyro_array[j][0]]
j+=1
elsif gyro_array[j+1][1] > -0.025 # if the next value is increasing by x1.2 the value of the previous amount. Log it as +1
trend_array << [0.2, gyro_array[j][0]]
j+=1
elsif gyro_array[j+1][1] < 0.025 # if the next value is decreasing by x1.2 the value of the previous amount. Log it as -1
trend_array << [-0.2, gyro_array[j][0]]
j+=1
end
end

#for graphing and analysis purposes (wanted to print it all as a csv in two columns)

File.open('02.3test.gyro_trends.text' , 'w') { |file| trend_array.each { |x,y| file.puts(x,y)}}

File.open('02.3test.gyro_trends_count.text' , 'w') { |file| trend_array.each {|x,y| file.puts(y)}}

我知道这真的很简单,但出于某种原因我错过了。有连接的东西,但我发现如果我尝试在我的最后一行代码中连接一个 \\n ,它不会将它输出到文件中。它以我想要的方式在我的控制台中输出它,但不是在我将它写入文件时。

感谢您花时间阅读所有内容。

最佳答案

File.open('02.3test.gyro_trends.text' , 'w') { |file| trend_array.each { |a| file.puts(a.join(","))}}

关于ruby - 使用 Ruby 将数组写入多列 CSV 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44616995/

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