How to convert a mixed-type Matrix to DataFrame in Julia recognising the column types

前端 未结 4 2207
深忆病人
深忆病人 2021-01-26 02:50

One nice feature of DataFrames is that it can store columns with different types and it can \"auto-recognise\" them, e.g.:

using DataFrames, DataStructures

df1          


        
4条回答
  •  心在旅途
    2021-01-26 03:09

    While I didn't find a complete solution, a partial one is to try to convert the individual columns ex-post:

    """
        convertDf!(df)
    
    Try to convert each column of the converted df from Any to In64, Float64 or String (in that order).    
    """
    function convertDf!(df)
        for c in names(df)
            try
              df[c] = convert(DataArrays.DataArray{Int64,1},df[c])
            catch
                try
                  df[c] = convert(DataArrays.DataArray{Float64,1},df[c])
                catch
                    try
                      df[c] = convert(DataArrays.DataArray{String,1},df[c])
                    catch
                    end
                end
            end
        end
    end 
    

    While surely incomplete, it is enough for my needs.

提交回复
热议问题