Is there a diff() function in Julia DataFrames like pandas? - dataframe

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.

Related

Compare elements in Julia DataFrame and return value in new column

I need to compare elements by rows of c1 and c2 columns in the DataFrame and return higher value in new column.
Column "Result" should return [6,5,4,4,5]
df = DataFrame(c1=[1,2,3,4,5], c2=[6,5,4,3,2])
println(df)
if broadcast(.>, df.c1, df.c2)
df[:, "Result"] .= df.c1
else
df[:, "Result"] .= df.c2
end
println(df5)
ERROR: TypeError: non-boolean (BitVector) used in boolean context
An alternative is:
julia> df.Result = max.(df.c1, df.c2)
5-element Vector{Int64}:
6
5
4
4
5
(as some users prefer such code than higher order functions presented excellently by #Shayan)
Using eachrow
julia> maximum.(eachrow(df))
5-element Vector{Int64}:
6
5
4
4
5
or as DataFrame
julia> DataFrame(new = maximum.(eachrow(df)))
5×1 DataFrame
Row │ new
│ Int64
─────┼───────
1 │ 6
2 │ 5
3 │ 4
4 │ 4
5 │ 5
or as a new column the DataFrame
julia> df.Result = maximum.(eachrow(df))
julia> df
5×3 DataFrame
Row │ c1 c2 Result
│ Int64 Int64 Int64
─────┼──────────────────────
1 │ 1 6 6
2 │ 2 5 5
3 │ 3 4 4
4 │ 4 3 4
5 │ 5 2 5
You can use select:
julia> select(df, All() => ByRow(max) => :Result)
5×1 DataFrame
Row │ Result
│ Int64
─────┼────────
1 │ 6
2 │ 5
3 │ 4
4 │ 4
5 │ 5
Another alternative is using DataFramesMeta.jl:
julia> #select(df, :Result = max.(:c1, :c2))
5×1 DataFrame
Row │ Result
│ Int64
─────┼────────
1 │ 6
2 │ 5
3 │ 4
4 │ 4
5 │ 5
# Alternatively, you can use the following line to avoid mentioning the column names manually:
#select(df, :Result = $(max.(propertynames(df)...)))
# Gives the same result.
If you want to make the change in place, then use select! or #select!.
If you prefer the returned dataframe to contain c1 and c2 columns as well, then you can go for transform (its alternative in-place operator is transform!):
julia> transform(df, All() => ByRow(max) => :Result)
5×3 DataFrame
Row │ c1 c2 Result
│ Int64 Int64 Int64
─────┼──────────────────────
1 │ 1 6 6
2 │ 2 5 5
3 │ 3 4 4
4 │ 4 3 4
5 │ 5 2 5
# And the same thing using DataFramesMeta.jl:
julia> #transform(df, :Result = $(max.(propertynames(df)...)))
5×3 DataFrame
Row │ c1 c2 Result
│ Int64 Int64 Int64
─────┼──────────────────────
1 │ 1 6 6
2 │ 2 5 5
3 │ 3 4 4
4 │ 4 3 3
5 │ 5 2 2

Count missing values per column in dataframe Julia

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

Remove columns with all values missing in dataframe Julia

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

Julia DataFrame: shift a column by more rows

I am looking for a way how to shift DataFrame column by more rows.
Shifting by one row works fine:
df = DataFrame(A=[1,2,3,4], B=[9,8,7,6])
julia> transform(df, "A" => ShiftedArrays.lag => :A1)
4×3 DataFrame
Row │ A B A1
│ Int64 Int64 Int64?
─────┼───────────────────────
1 │ 1 9 missing
2 │ 2 8 1
3 │ 3 7 2
4 │ 4 6 3
But I am not able to find out how to transform the entire column with a function with more arguments, something like this (neither works):
transform(df, "A" => x -> ShiftedArrays.lag(x, 2) => :A1)
or
transform(df, ["A", 2] => f => :A1)
I hope there is a more suitable solution than using of for loop :-)
You need additional parentheses around the anonymous function:
transform(df, "A" => (x -> ShiftedArrays.lag(x, 2)) => :A1)
Result:
Row │ A B A1
│ Int64 Int64 Int64?
─────┼───────────────────────
1 │ 1 9 missing
2 │ 2 8 missing
3 │ 3 7 1
4 │ 4 6 2

Julia: How to create a new column in DataFrames.jl by adding two columns using `transform` or `#transform`?

using DataFrames
df = DataFrame(a=1:3, b=1:3)
How do I create a new column c such that c = a+b element wise?
Can't figure it out by reading the transform doc.
I know that
df[!, :c] = df.a .+ df.b
works but I want to use transform in a chain like this
#chain df begin
#transform(c = :a .+ :b)
#where(...)
groupby(...)
end
The above syntax doesn't work with DataFramesMeta.jl
This is an answer using DataFrames.jl.
To create a new data frame:
julia> transform(df, [:a,:b] => (+) => :c)
3×3 DataFrame
Row │ a b c
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 1 2
2 │ 2 2 4
3 │ 3 3 6
and for an in-place operation:
julia> transform!(df, [:a,:b] => (+) => :c)
3×3 DataFrame
Row │ a b c
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 1 2
2 │ 2 2 4
3 │ 3 3 6
or
julia> insertcols!(df, :c => df.a + df.b)
3×3 DataFrame
Row │ a b c
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 1 2
2 │ 2 2 4
3 │ 3 3 6
The difference between transform! and insertcols! is that insertcols! will error if :c column is present in the data frame, while transform! will overwrite it.