天天看点

Julia ---- DataFrame 快速清洗数据的一些方式

在整理离线数据的时候,随便整理下快速处理数据的一些方式,这里单独摘出来。不得不说,Julia 的包更新速度还是比较快的,提供的函数效率也越来越高了。

using DataFrames
using CSV

# 批量处理dataframe中的数据,应该都是按照列来处理的。
df = DataFrame(rand(5, 10))

names(df)


#返回多维数组 每个维度的size
axes(df)
#(Base.OneTo(5), Base.OneTo(1000))

for i in axes(df, 2)
    df[i] .+= 1
end

for i in names(df)
    df[i] .+= 1
end
a=1
for col in eachcol(df, false)
    a=+1
    col .+= 1
    show(a)
end
foreach(x -> x .+= 1, eachcol(df, false))



# 替换指定的值
for col in eachcol(df, false)
    replace!(col, Inf=>NaN)
end

#这种方式会更快点, 需要注意的地方就是只有在确定数据边界的情况下才能使用 @inbounds,如果不确定,可能会引起越界崩溃。
function inf2nan(x)
    for i in eachindex(x)
        @inbounds x[i] = ifelse(isinf(x[i]), NaN, x[i])
    end
end
for col in eachcol(df, false)
    inf2nan(col)
end

names(df)

#只取部分列,
df[[2, 1]]
permutecols!(df, [:x1, :x3])  #效率更高的方法


#矩阵转换成数组的方式
input = [1 2 3; 4 5 6; 7 8 9]
#转成数组
mapslices(x->[x], input,dims = [2])
DataFrame(transpose(input))
#
df[1]
#Vector 转成 array,array 定义的时候必须定义数组的元素个数;而vector 不需要
reshape(df[1],(1,5))


#使用Iterators.filter 更快速的过滤数据
function h(a ::AbstractArray)
    for x in Iterators.filter(==(10^9), 1:10^9)
        println(x)
    end
end
for col in eachcol(df, false)
    h(col)
end


#数据写入到CSV中
CSV.write("FileName.csv",  DataFrame(A), writeheader=false)
           

继续阅读