Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rowwise function #1459

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/DataFrames.jl
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export AbstractDataFrame,
head,
tail,
permutecols!,
rowwise,

# Remove after deprecation period
pool,
Expand Down
2 changes: 1 addition & 1 deletion src/dataframe/dataframe.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1105,4 +1105,4 @@ end

function permutecols!(df::DataFrame, p::AbstractVector{Symbol})
permutecols!(df, getindex.(index(df).lookup, p))
end
end
25 changes: 25 additions & 0 deletions src/dataframerow/utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -218,3 +218,28 @@ function Base.getindex(gd::RowGroupDict, dfr::DataFrameRow)
gix = gd.groups[g_row]
return view(gd.rperm, gd.starts[gix]:gd.stops[gix])
end

"""
rowwise(f::Function, df::DataFrame)

Performs a function alonw an array from each row in a DataFrame,
returning an array of length `nrow(df)`

```julia
julia> df = DataFrame(a = [2,200], b = [4,400])
2×2 DataFrames.DataFrame
│ Row │ a │ b │
├─────┼─────┼─────┤
│ 1 │ 2 │ 4 │
│ 2 │ 200 │ 400 │

julia> t = rowwise(mean, df)
2-element Array{Float64,1}:
3.0
300.0
```

"""
function rowwise(f::Function, df::DataFrame)
t = [f([x[2] for x in collect(row)]) for row in eachrow(df)]
end
2 changes: 1 addition & 1 deletion src/other/utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,4 @@ function _fnames(fs::Vector{T}) where T<:Function
name
end
names
end
end
4 changes: 4 additions & 0 deletions test/dataframerow.jl
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ module TestDataFrameRow
gd = DataFrames.group_rows(df5[1,:])
@test gd.ngroups == 1

# rowwise operator
df = DataFrame(a = [2,200], b = [4,400])
@test rowwise(Compat.mean, df) = [3.0, 300]

# getproperty, setproperty! and propertynames
if VERSION >= v"0.7.0-DEV.3067"
r = DataFrameRow(df, 1)
Expand Down