在 Python 中将 .sav 文件转换为 .csv 文件

Mad*_*van 0 python csv numpy scipy

我想在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)
Run Code Online (Sandbox Code Playgroud)

以下是我运行上述代码行时的结果:

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'>]
--------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

谁能建议我如何将所有变量数据写入 .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
..... 
Run Code Online (Sandbox Code Playgroud)

“on2_grid”和“on2_grid_smooth”变量的形状相同,均为(101, 202)。两者都是“numpy.ndarray”类型。

小智 6

无论如何,您可以使用以下命令非常轻松地将 SPSS 文件导入到 Python 中pandas

import pandas as pd
df = pd.read_spss("input_file.sav")
Run Code Online (Sandbox Code Playgroud)

然后您可以使用以下.to_csv()方法导出数据:

df.to_csv("output_file.csv", index=False)
Run Code Online (Sandbox Code Playgroud)

如果您只需要导出某些列,您也可以指定:

df[["column_a", "column_b"]].to_csv("output_file.csv", index=False)
Run Code Online (Sandbox Code Playgroud)