【问题标题】:Select a column from an xarray从 xarray 中选择一列
【发布时间】:2019-06-25 22:16:52
【问题描述】:

请问如何从xarray.DataArray 中选择一列?这就是我做 xarray 的方式

import xarray as xr
import numpy as np
import pandas as pd

my_data = np.random.rand(5,2)
da = xr.DataArray(my_data, 
                  coords={'my_id':np.arange(my_data.shape[0]),
                         'columns': ['x', 'y']},
                  dims=['my_id', 'columns'])

我想选择column x。如果那是dataframe

df = pd.DataFrame(my_data, columns=['x','y'])

我正在寻找相当于df['x']

我是否以错误的方式定义DataArray

【问题讨论】:

    标签: python python-3.x python-xarray


    【解决方案1】:

    啊,好吧,我想我明白了:

    da.sel(columns='x')
    

    【讨论】:

      【解决方案2】:

      您可以按照docs 中的建议使用类似熊猫的.loc

      da.loc[:, ['x']]
      
      <xarray.DataArray (my_id: 5, columns: 1)>
      array([[ 0.534358],
             [ 0.113875],
             [ 0.905085],
             [ 0.96994 ],
             [ 0.548338]])
      Coordinates:
        * my_id    (my_id) int32 0 1 2 3 4
        * columns  (columns) <U1 'x'
      

      【讨论】:

        【解决方案3】:

        直接来自文档:http://xarray.pydata.org/en/stable/generated/xarray.DataArray.to_pandas.html

        import xarray as xr
        import numpy as np
        import pandas as pd
        
        my_data = np.random.rand(5,2)
        da = xr.DataArray(my_data, 
                          coords={'my_id':np.arange(my_data.shape[0]),
                                 'columns': ['x', 'y']},
                          dims=['my_id', 'columns'])
        
        df = da.to_pandas()
        
        df['x']
        

        结果

        df['x']

        Out[27]: 
        my_id
        0    0.752056
        1    0.048029
        2    0.145835
        3    0.083147
        4    0.618351
        Name: x, dtype: float64
        

        【讨论】:

          猜你喜欢
          • 2020-07-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多