【问题标题】:How to pick a value from date column and store it in a matrix如何从日期列中选择一个值并将其存储在矩阵中
【发布时间】:2020-04-09 05:35:30
【问题描述】:

我有一个 8000 rows 和 10 columns 的 excel 文件和日期作为索引,如下所示

                col1 col2 col3 col4 col5  col6  col7  col8   col9   col10
    Date                                                                
    1996-03-01  0.0  6.3  3.6  9.4  86.0  34.0  34.3  17.5   NaN     NaN
    1996-03-02  0.0  5.3  1.1  8.5  95.0  48.0  34.5  20.8   NaN     NaN
            ...  ...  ...  ...   ...   ...   ...   ...   ...     ...
    2015-12-30  0.0  3.6  NaN  8.4  92.0  25.0  32.6  16.4   NaN     NaN
    2015-12-31  0.0  3.4  NaN  8.6  92.0  41.0  31.7  17.4   NaN     NaN

在上述数据集中,col9col10 存在缺失值。

现在我的任务是在col 9col 10 中存在值的地方,我想选择整行并将其保存在一个矩阵中,如下所示。

    col1 col2 col3 col4 col5 col6 col7 col8  col9   col10
    0.0  0.0  0.0  0.0  0.0  0.0  4.2  22.3  20.0  21.2  
    0.0  0.0  0.0  0.0  0.0  0.0  8.0  26.8  21.4  20.5 
    ...  ...  ...  ...   ...   ...   ...   ...   ...      
    0.0  0.0  6.0  3.5  8.9  9.8  7.5  25.6  22.4  27.6 

另一个挑战是我也想保留相应的日期。我该怎么做?
由于日期是时间戳,其余都是浮点类型。我无法将时间戳插入矩阵的特定行列。

【问题讨论】:

    标签: python-3.x pandas numpy dataframe


    【解决方案1】:

    当您在 python 中说矩阵时,我假设您的意思是 df。如果您不这样做,并且您的意思是numpy 数组的实际矩阵,您可以轻松地从df 派生一个。 不要从df 复制您的值,只需删除所需的行并将剩余的行存储在新的df 中。

    new_df = df.dropna(inplace=True,subset=["col9","col10"])  
    

    子集是您要在 drop na 中考虑的列。(您也可以在列表中传递列索引/编号) ^ 这将存储您的数据,包括删除行的新 df 中的日期。

    要将此 new_df 转换为 numpy 矩阵,您可以使用以下命令轻松将其加载到字典中:

    DataFrame.to_dict(self, orient='dict', into=<class 'dict'>)[source] 
    

    方法,然后从这里加载你的 numpy mat(参考链接:python dict to numpy structured array

    注意:如果日期给您带来额外的麻烦,则使用以下方法将它们转换为在 new_df 本身中浮动:

    def datetime_to_float(d):
        return d.timestamp()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      相关资源
      最近更新 更多