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

前端 未结 4 2221
深忆病人
深忆病人 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:10

    While I think there may be a better way to go about the whole thing this should do what you want.

    df = DataFrame()
    for (ind,s) in enumerate(Symbol.(dataMatrix[1,:])) # convert first row to symbols and iterate through them.
        # check all types the same else assign to Any
        T = typeof(dataMatrix[2,ind])
        T = all(typeof.(dataMatrix[2:end,ind]).==T) ? T : Any
        # convert to type of second element then add to data frame
        df[s] = T.(dataMatrix[2:end,ind])
    end
    

提交回复
热议问题