将几个2D数组转换为数据框,然后合并它们

时间:2020-07-08 16:14:01

标签: python pandas

假设我有许多“地图”,它们是2D数组(map0, map1, ...),其中行(axis=0)对应于经度值,列(axis=1)对应于纬度值。 / p>

我想以这种形式的pandas DataFrame结尾:

     lat    lon    values_map0    values_map1     ....
0
1
.
.
.

除了以下以外,是否有更简单的方法来实现这一目标:

from functools import reduce

nlon = 360
nlat = 180
map0 = np.random.rand(nlon, nlat)
map1 = np.random.rand(nlon, nlat)
map2  = np.random.rand(nlon, nlat)
lats = np.arange(nlat)
lons = np.arange(nlon)

def mapToDf(lons, lats, array, varName):
    """Convert 2D array of map to stacked dataframe."""
    df = pd.DataFrame(array, index=lons, columns=lats)
    dfStack = df.stack().reset_index()
    dfStack.columns = ['lon', 'lat', varName]
    return dfStack

listMaps = [map0, map1, map2]
listDfs = [mapToDf(lons, lats, map, 'values_map{}'.format(i)) for i, map in enumerate(listMaps)]

reduce(lambda x, y: pd.merge(x, y, on = ['lat', 'lon']), listDfs )


0 个答案:

没有答案