我想在Python中将*.sav文件的内容转换为*.csv文件。我已经编写了以下几行代码来访问*.sav文件中变量的详细信息。现在,我不清楚如何将访问的变量数据写入带有头文件的.csv文件
import scipy.io as spio
on2file = 'ON2_2015_112m_220415.sav'
on2data = spio.readsav(on2file, python_dict=True, verbose=True)以下是我运行上述代码行时的结果:
IDL Save file is compressed
-> expanding to /var/folders/z4/r3844ql123jgkq1ztdr4jxrm0000gn/T/tmpVE_Iz6.sav
--------------------------------------------------
Date: Mon Feb 15 20:41:02 2016
User: zhangy1
Host: augur
--------------------------------------------------
Format: 9
Architecture: x86_64
Operating System: linux
IDL Version: 7.0
--------------------------------------------------
Successfully read 11 records of which:
- 7 are of type VARIABLE
- 1 are of type TIMESTAMP
- 1 are of type NOTICE
- 1 are of type VERSION
--------------------------------------------------
Available variables:
- saved_data [<class 'numpy.recarray'>]
- on2_grid_smooth [<type 'numpy.ndarray'>]
- d_lat [<type 'numpy.float32'>]
- on2_grid [<type 'numpy.ndarray'>]
- doy [<type 'str'>]
- year [<type 'str'>]
- d_lon [<type 'numpy.float32'>]
--------------------------------------------------有没有人能给我提个建议,告诉我如何把所有的变量数据写到一个.csv文件中?
我想要将变量(year,doy,d_lon,d_lat,on2_grid,on2_grid_smooth)写入CSV或ASCII文件,其格式如下:
longitude, latitude, on2_grid, on2_grid_smooth # header
0.0,0.0,0.0,0.0
0.0,0.0,0.0,0.0
0.0,0.0,0.0,0.0
0.0,0.0,0.0,0.0
..... "on2_grid“和"on2_grid_smooth”变量的形状是相同的,并且是(101,202)。两者都属于"numpy.ndarray“类型。
发布于 2017-03-03 16:08:33
我可以通过更改必要的输出格式来解决我的问题,下面是我的代码:
import scipy.io as spio
import numpy as np
import csv
on2file = 'ON2_2016_112m_220415.sav' # i/p file
outfile = 'ON2_2016_112m_220415.csv' # o/p file
# Read i/p file
s = spio.readsav(on2file, python_dict=True, verbose=True)
# Creating Grid
#d_lat = s["d_lat"]
#d_lon = s["d_lon"]
lat = np.arange(-90,90,1.78218) # (101,)
lon = np.arange(-180,180,1.78218) # (202,)
ylat,xlon = np.meshgrid(lat,lon)
on2grid = np.asarray(s["on2_grid"])
on2gridsmooth = np.asarray(s["on2_grid_smooth"])
nrows = len(on2grid)
ncols = len(on2grid[0])
xlon_grid = xlon.reshape(nrows*ncols,1)
ylat_grid = ylat.reshape(nrows*ncols,1)
on2grid_new = on2grid.reshape(nrows*ncols,1)
on2gridsmooth_new = on2gridsmooth.reshape(nrows*ncols,1)
# Concatenation
allgriddata = np.concatenate((xlon_grid, ylat_grid, on2grid_new, on2gridsmooth_new),axis=1)
# Writing o/p file
f_handle = file(outfile,'a')
np.savetxt(f_handle,allgriddata,delimiter=",",fmt='%0.3f',header="longitude, latitude, on2_grid, on2_grid_smooth")
f_handle.close()发布于 2021-08-26 19:46:47
无论如何,您可以使用pandas非常轻松地将SPSS文件导入到Python中
import pandas as pd
df = pd.read_spss("input_file.sav")然后您可以使用.to_csv()方法导出数据:
df.to_csv("output_file.csv", index=False)如果只需要导出某些列,也可以指定:
df[["column_a", "column_b"]].to_csv("output_file.csv", index=False)发布于 2017-03-18 12:32:06
使用您的代码提取的文件中的经纬度列看起来是互换的。此外,纬度范围从0到180 (不是+90 0 -90)) ...whether 0从顶部开始。Pl。评论。
https://stackoverflow.com/questions/42532250
复制相似问题