How can I insert a row in a dataframe in Julia at a specific index ? (Julia version 1.1)
I have found this related question. However, the code given in the answer isn't working anymore in Julia 1.1
I know how to push! a row into a dataframe or concatenate two dataframes, but what about inserting at a specific index ?
It also doesn't seem to be explained in Julia DataFrames documentation.
This is a non-standard operation. The recommendation given there is still valid, so:
df = DataFrame(x = [1,2,3], y = ["a", "b", "c"])
foreach((v,n) -> insert!(df[n], 2, v), [4, "d"], names(df))
works. A shorter version to write it under Julia 1.0 would be:
insert!.(eachcol(df, false), 2, [4, "d"])
(the need to add false as a second argument will not be needed in the future as we are in the deprecation period now)
The difference is that getproperty method can be overloaded since Julia 1.0 so df.columns does not work.
I have also updated the other answer, so you can close this question if you prefer.
EDIT
The instructions above are no longer valid (unless you use very old DataFrames.jl version).
In DataFrames.jl 1.4 use insert!, push!, or pushfirst! functions depending on where you want to add the row:
julia> using DataFrames
julia> df = DataFrame(x = [1,2,3], y = ["a", "b", "c"])
3×2 DataFrame
Row │ x y
│ Int64 String
─────┼───────────────
1 │ 1 a
2 │ 2 b
3 │ 3 c
julia> insert!(df, 2, (100, "new line"))
4×2 DataFrame
Row │ x y
│ Int64 String
─────┼─────────────────
1 │ 1 a
2 │ 100 new line
3 │ 2 b
4 │ 3 c
julia> push!(df, (200, "last line"))
5×2 DataFrame
Row │ x y
│ Int64 String
─────┼──────────────────
1 │ 1 a
2 │ 100 new line
3 │ 2 b
4 │ 3 c
5 │ 200 last line
julia> pushfirst!(df, (300, "first line"))
6×2 DataFrame
Row │ x y
│ Int64 String
─────┼───────────────────
1 │ 300 first line
2 │ 1 a
3 │ 100 new line
4 │ 2 b
5 │ 3 c
6 │ 200 last line
Related
I would like to count the number of missing values per column in a dataframe like df:
Pkg.add("DataFrames")
using DataFrames
df = DataFrame(i=1:5,
x=[missing, 4, missing, 2, 1],
y=[missing, missing, "c", "d", "e"])
5×3 DataFrame
Row │ i x y
│ Int64 Int64? String?
─────┼─────────────────────────
1 │ 1 missing missing
2 │ 2 4 missing
3 │ 3 missing c
4 │ 4 2 d
5 │ 5 1 e
This should return 0 for i, 2 for x and 2 for y column. So I was wondering if anyone knows how to count the number of missing values per column in Julia?
When writing the question I found an answer by using describe with :nmissing like this:
describe(df, :nmissing)
3×2 DataFrame
Row │ variable nmissing
│ Symbol Int64
─────┼────────────────────
1 │ i 0
2 │ x 2
3 │ y 2
If you wanted the output in columnar format you can write:
julia> mapcols(x -> count(ismissing, x), df)
1×3 DataFrame
Row │ i x y
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 0 2 2
I have the following dataframe called df:
df = DataFrame(i=1:5,
x=[missing, missing, missing, missing, missing],
y=[missing, missing, 1, 3, 6])
5×3 DataFrame
Row │ i x y
│ Int64 Missing Int64?
─────┼─────────────────────────
1 │ 1 missing missing
2 │ 2 missing missing
3 │ 3 missing 1
4 │ 4 missing 3
5 │ 5 missing 6
I would like to remove the columns where all values are missing. In this case it should remove column x because it has only all missing values. with dropmissing it removes all rows, but that's not what I want. So I was wondering if anyone knows how to remove only columns where all values are missing in a dataframe Julia?
A mediocre answer would be:
df1 = DataFrame()
foreach(
x->all(ismissing, df[!, x]) ? nothing : df1[!, x] = df[!, x],
propertynames(df)
)
df
# 5×2 DataFrame
# Row │ i y
# │ Int64 Int64?
# ─────┼────────────────
# 1 │ 1 missing
# 2 │ 2 missing
# 3 │ 3 1
# 4 │ 4 3
# 5 │ 5 6
But a slightly better one would be using the slicing approach:
df[:, map(x->!all(ismissing, df[!, x]), propertynames(df))]
# 5×2 DataFrame
# Row │ i y
# │ Int64 Int64?
# ─────┼────────────────
# 1 │ 1 missing
# 2 │ 2 missing
# 3 │ 3 1
# 4 │ 4 3
# 5 │ 5 6
# OR
df[!, map(x->!all(ismissing, x), eachcol(df))]
# 5×2 DataFrame
# Row │ i y
# │ Int64 Int64?
# ─────┼────────────────
# 1 │ 1 missing
# 2 │ 2 missing
# 3 │ 3 1
# 4 │ 4 3
# 5 │ 5 6
#Or
df[!, Not(names(df, all.(ismissing, eachcol(df))))]
# I omitted the result to prevent this answer from becoming extensively lengthy.
#Or
df[!, Not(all.(ismissing, eachcol(df)))]
I almost forgot the deleteat! function:
deleteat!(permutedims(df), all.(ismissing, eachcol(df))) |> permutedims
# 5×2 DataFrame
# Row │ i y
# │ Int64 Int64?
# ─────┼────────────────
# 1 │ 1 missing
# 2 │ 2 missing
# 3 │ 3 1
# 4 │ 4 3
# 5 │ 5 6
You can use the select! function, as Dan noted:
select!(df, [k for (k,v) in pairs(eachcol(df)) if !all(ismissing, v)])
# 5×2 DataFrame
# Row │ i y
# │ Int64 Int64?
# ─────┼────────────────
# 1 │ 1 missing
# 2 │ 2 missing
# 3 │ 3 1
# 4 │ 4 3
# 5 │ 5 6
The names functions accepts a type as an input to select columns of a specific type, so I would do:
julia> select(df, Not(names(df, Missing)))
5×2 DataFrame
Row │ i y
│ Int64 Int64?
─────┼────────────────
1 │ 1 missing
2 │ 2 missing
3 │ 3 1
4 │ 4 3
5 │ 5 6
Without benchmarking this I would guess that it is also significantly faster, as it doesn't have to check each element of each column but as far as I know simply queries the type information for each column readily available in the DataFrame:
julia> dump(df)
DataFrame
columns: Array{AbstractVector}((3,))
1: Array{Int64}((5,)) [1, 2, 3, 4, 5]
2: Array{Missing}((5,))
1: Missing missing
2: Missing missing
3: Missing missing
4: Missing missing
5: Missing missing
3: Array{Union{Missing, Int64}}((5,))
The downside of this approach is that it relies on the type information to be correct, which might not be the case after a transformation:
julia> df2 = df[1:2, :]
2×3 DataFrame
Row │ i x y
│ Int64 Missing Int64?
─────┼─────────────────────────
1 │ 1 missing missing
2 │ 2 missing missing
This can be fixed by calling identity to narrow column types, but this is again potentially expensive:
julia> identity.(df2)
2×3 DataFrame
Row │ i x y
│ Int64 Missing Missing
─────┼─────────────────────────
1 │ 1 missing missing
2 │ 2 missing missing
So I'd say if you're creating a DataFrame from scratch, such as reading it in via XLSX.jl (as people loooove putting empty columns in their Excel sheet) or are creating whole columns in your workflow, names(df, Not(Missing)) is the way to go, while for analysis on subsets of DataFrames it's only guaranteed to work when using identity so that the other approaches mentioned which check every cell are viable alternatives.
Another simple option is to use
df[!, any.(!ismissing, eachcol(df))]
5×2 DataFrame
Row │ i y
│ Int64 Int64?
─────┼────────────────
1 │ 1 missing
2 │ 2 missing
3 │ 3 1
4 │ 4 3
5 │ 5 6
and if the DataFrame is created from scratch, there is another fast option using the column type. Since any column with all missing entries isa Vector{Missing}, we can use this Type information to skip these columns. The drawback of this fast method as #NilsGudat pointed out, is that it fails if the DataFrame column types have changed by some transformation.
df[!, (!isa).(eachcol(df), Vector{Missing})]
5×2 DataFrame
Row │ i y
│ Int64 Int64?
─────┼────────────────
1 │ 1 missing
2 │ 2 missing
3 │ 3 1
4 │ 4 3
5 │ 5 6
How can I get the column types of a Julia DataFrame?
using DataFrames
df = DataFrame(a = 1:4, b = ["a", "b", "c", "d"])
4×2 DataFrame
Row │ a b
│ Int64 String
─────┼───────────────
1 │ 1 a
2 │ 2 b
3 │ 3 c
4 │ 4 d
Some additional options (keeping the result in a data frame):
julia> mapcols(eltype, df)
1×2 DataFrame
Row │ a b
│ DataType DataType
─────┼────────────────────
1 │ Int64 String
julia> mapcols(typeof, df)
1×2 DataFrame
Row │ a b
│ DataType DataType
─────┼───────────────────────────────
1 │ Vector{Int64} Vector{String}
julia> describe(df, :eltype)
2×2 DataFrame
Row │ variable eltype
│ Symbol DataType
─────┼────────────────────
1 │ a Int64
2 │ b String
EDIT: in describe you get the element type of a column with stripped Missing - I have forgotten to add this comment earlier.
For each column I can get the element type like this:
eltype.(eachcol(df))
The same can be achieved (and I like this even better) with
df |> eachcol .|> eltype
2-element Vector{DataType}:
Int64
String
The actual type of the column can be retrieved with
df |> eachcol .|> typeof
2-element Vector{DataType}:
Vector{Int64} (alias for Array{Int64, 1})
Vector{String} (alias for Array{String, 1})
I have a DataFrame in Julia and I want to create a new column that represents the difference between consecutive rows in a specific column. In python pandas, I would simply use df.series.diff(). Is there a Julia equivelant?
For example:
data
1
2
4
6
7
# in pandas
df['diff_data'] = df.data.diff()
data diff_data
1 NaN
2 1
4 2
6 2
7 1
You can use ShiftedArrays.jl like this.
Declarative style:
julia> using DataFrames, ShiftedArrays
julia> df = DataFrame(data=[1, 2, 4, 6, 7])
5×1 DataFrame
Row │ data
│ Int64
─────┼───────
1 │ 1
2 │ 2
3 │ 4
4 │ 6
5 │ 7
julia> transform(df, :data => (x -> x - lag(x)) => :data_diff)
5×2 DataFrame
Row │ data data_diff
│ Int64 Int64?
─────┼──────────────────
1 │ 1 missing
2 │ 2 1
3 │ 4 2
4 │ 6 2
5 │ 7 1
Imperative style (in place):
julia> df = DataFrame(data=[1, 2, 4, 6, 7])
5×1 DataFrame
Row │ data
│ Int64
─────┼───────
1 │ 1
2 │ 2
3 │ 4
4 │ 6
5 │ 7
julia> df.data_diff = df.data - lag(df.data)
5-element Vector{Union{Missing, Int64}}:
missing
1
2
2
1
julia> df
5×2 DataFrame
Row │ data data_diff
│ Int64 Int64?
─────┼──────────────────
1 │ 1 missing
2 │ 2 1
3 │ 4 2
4 │ 6 2
5 │ 7 1
with diff you do not need extra packages and can do similarly the following:
julia> df.data_diff = [missing; diff(df.data)]
5-element Vector{Union{Missing, Int64}}:
missing
1
2
2
1
(the issue is that diff is a general purpose function that does change the length of vector from n to n-1 so you have to add missing manually in front)
Pandas df.diff() does it to the whole data frame at once and allows you to specify row-wise or column-wise. There might be a better way but this is what I used before (I like chaining or piping like in dplyr):
# using chain.jl
#chain df begin
eachcol()
diff.()
DataFrame(:auto)
rename!(names(df))
end
# OR base pipe
df |>
x -> eachcol(x) |>
x -> diff.(x) |>
x -> DataFrame(x, :auto) |>
x -> rename!(x, names(df)[2:end])
# OR without piping
rename!(DataFrame(diff.(eachcol(df)), :auto), names(df))
You might need to insert the starting row, which will now have missing values.
I'd like to know how I can permanently delete multiple rows from a dataframe in Julia.
Here is the dataframe example:
Group Variable1 Variable2
String Float64 Float64
1 B -0.661256 0.265538
2 B 0.111651 0.837895
3 A 0.197754 0.987195
4 A 1.35057 0.696815
5 A -1.20899 0.496407
6 B 0.813047 0.324904
I'd like to delete rows 2, 4, and 6 from my dataframe. There is an easy function to do that?
If you want to delete inplace:
delete!(df, [2, 4, 6])
In case you want a new df without the selected rows:
df[Not([2, 4, 6]), :]
As of DataFrames.jl version 1.3, delete! has been deprecated and replaced with deleteat!. This change was made to more correctly reflect the difference between Base.delete! and Base.deleteat!. You can compare the docstring for Base.deleteat! to the docstring for Base.delete!. In fact, the DataFrames deleteat! function is a method extension of Base.deleteat!.
Here's an example of using deleteat! on a data frame:
julia> using DataFrames
julia> df = DataFrame(a=1:4, b=5:8)
4×2 DataFrame
Row │ a b
│ Int64 Int64
─────┼──────────────
1 │ 1 5
2 │ 2 6
3 │ 3 7
4 │ 4 8
julia> deleteat!(df, [2, 3])
2×2 DataFrame
Row │ a b
│ Int64 Int64
─────┼──────────────
1 │ 1 5
2 │ 4 8
Here's the DataFrames documentation for deleteat!:
https://dataframes.juliadata.org/stable/lib/functions/#Base.deleteat!