好消息:拿到了数据;坏消息:是mat格式的。所以参考了其他前辈的代码,尝试写了以下代码:
使用的库包是scipy,可以用conda进行安装。github和其他博文上有更为的详细介绍。
pip install scipy
以下为我的详细代码:
import pandas as pd
import os
import scipy
from scipy import io
year = 1982
month = 1
while year <= 2020:
while int(month) <= 12:
month_length = str(month)
if len(month_length)==1:
month = str(0) + str(month)
time_index = os.path.join(str(year) + str(month))
out_path = os.path.join("G:/NDVI_CSV/" + time_index + '.csv')
print('processing ' + time_index + ' !!!')
ndvi_mat = scipy.io.loadmat("G:/NDVI/"+time_index + '.mat')
features = list(ndvi_mat.values())[-1]
ndvi_csv = pd.DataFrame(features)
ndvi_csv.to_csv(out_path, index=False)
month += str(1)
year += 1
month = 1
看起来很复杂,因为我的数据比较多,是月数据,所以需要写while循环读取。但是文件格式为198201、198202...这样的格式在读取的时候就比较麻烦了。比如以下我定义time_index为年+月,这样的话就会产生19821、19822...就不会自动加0,导致报错文件不存在。
time_index = os.path.join(str(year) + str(month))
out_path = os.path.join("G:/NDVI_CSV/" + time_index + '.csv')
所以我增加了一个判断语句,如果month的长度为1,则在前面增加0
while int(month) <= 12:
month_length = str(month)
if len(month_length)==1:
month = str(0) + str(month)
代码中有很多str和int,是因为一直报格式的错误,其中原因我是初学者不是很了解,但最终能解决就好。