坚持将NetCDF文件导入Pandas DataFrame

时间:2013-02-01 08:40:20

标签: dataframe pandas netcdf

作为一名初学者,我一直在研究这个问题。总的来说,我想读取一个NetCDF文件,并将多个(~50)列(和17520个案例)导入Pandas DataFrame。目前我已将其设置为4个变量的列表,但我希望能够以某种方式扩展它。我开始了,但是如何通过50个变量来实现这一点的任何帮助都会很棒。它使用下面的代码为4个变量工作。我知道它不是很漂亮所以打招呼是受欢迎的,还在学习。

我有另外一个问题,当我尝试将numpy数组直接读入Pandas DataFrame时,它不起作用,而是创建一个17520列大的DataFrame。它应该是另一种方式(转置)。如果我创建一个系列,它工作正常。所以我不得不使用以下几行来解决这个问题。甚至不确定它为何起作用。有什么更好的方法吗?特别是当谈到50个变量时

d={vnames[0] :vartemp[0], vnames[1] :vartemp[1], vnames[2] :vartemp[2], vnames[3] :vartemp[3]}
hs = pd.DataFrame(d,index=times)

整个代码粘贴在

下面

非常感谢 杰森

import pandas as pd
import datetime as dt
import xlrd
import numpy as np
import netCDF4


def excel_to_pydate(exceldate):
    datemode=0           # datemode: 0 for 1900-based, 1 for 1904-based
    pyear, pmonth, pday, phour, pminute, psecond = xlrd.xldate_as_tuple(exceldate, datemode)
    py_date = dt.datetime(pyear, pmonth, pday, phour, pminute, psecond)
    return(py_date)

def main():
    filename='HowardSprings_2010_L4.nc'
#Define a list of variables names we want from the netcdf file
    vnames = ['xlDateTime', 'Fa', 'Fh' ,'Fg']

# Open the NetCDF file
    nc = netCDF4.Dataset(filename) 

#Create some lists of size equal to length of vnames list.
    temp=list(xrange(len(vnames)))
    vartemp=list(xrange(len(vnames)))

#Enumerate the list and assign each NetCDF variable to an element in the lists.  
# First get the netcdf variable object assign to temp
# Then strip the data  from that and add to temporary variable (vartemp)
    for index, variable in enumerate(vnames):               
        temp[index]= nc.variables[variable]
        vartemp[index] = temp[index][:]   

# Now call the function to convert to datetime from excel. Assume datemode: 0
    times = [excel_to_pydate(elem) for elem in vartemp[0]]

#Dont know why I cant just pass a list of variables i.e. [vartemp[0], vartemp[1], vartemp[2]]
#But this is only thing that worked
#Create Pandas dataframe using times as index
    d={vnames[0] :vartemp[0], vnames[1] :vartemp[1], vnames[2] :vartemp[2], vnames[3] :vartemp[3]}
    theDataFrame = pd.DataFrame(d,index=times)

#Define missing data value and apply to DataFrame
    missing=-9999
    theDataFrame1=theDataFrame.replace({vnames[0] :missing, vnames[1] :missing, vnames[2] :missing, vnames[3] :missing},'NaN')

main()

1 个答案:

答案 0 :(得分:1)

您可以替换:

d = {vnames[0] :vartemp[0], ..., vnames[3]: vartemp[3]}
hs = pd.DataFrame(d, index=times)

hs = pd.DataFrame(vartemp[0:4], columns=vnames[0:4], index=times)

说,大熊猫可以直接读HDF5,所以对于netCDF(基于HDF5)也许也是如此...