Python:将3D数组中的值存储到csv [英] Python: Storing values in a 3D array to csv

查看:454
本文介绍了Python:将3D数组中的值存储到csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下问题.我有一个3D阵列 matrix = np.zeros((30,30,100)),其中每个条目都是一个坐标并获取一个值.因此matrix [0][0][0]是坐标x = 0,y0,z = 0且值为0.现在我想将所有值存储在这样的csv中,其中前3行是坐标,第4行是对应值:

I have the follwoing problem. I have a 3D array like matrix = np.zeros((30,30,100)) where every entry is a coordinate and gets a value. So matrix [0][0][0] is the coordinate x=0,y0,z=0 and has a value of 0. Now i want to store all the values in a csv like this where the first 3 rows are the coordinates and the 4th the corresponding value:

使用numpy是否有一种快速的方法来做到这一点?

Is there a fast way with numpy to do this?

推荐答案

您可以使用pandas,它既可以对数组进行整形,也可以将其另存为csv.

You could use pandas, it can both reshape the array and save it as csv.

import numpy as np
import pandas as pd
# create an example array
a = np.arange(24).reshape([2,3,4])
# convert it to stacked format using Pandas
stacked = pd.Panel(a.swapaxes(1,2)).to_frame().stack().reset_index()
stacked.columns = ['x', 'y', 'z', 'value']
# save to disk
stacked.to_csv('stacked.csv', index=False)

否则,您可以申请

np.ravel()

添加到您的数组中,然后使用该问题中的一种配方恢复索引.

to your array and then restore indices using one of the recipes in this question.

这篇关于Python:将3D数组中的值存储到csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆