mat格式转csv格式

好消息:拿到了数据;坏消息:是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,是因为一直报格式的错误,其中原因我是初学者不是很了解,但最终能解决就好。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值