英文:
Finding the percentage change in multiple columns
问题
如果我有一个包含两列的数据框,是否有一种方法可以一次性计算这两列的百分比变化?希望能使用transform
函数。
用于分别计算每列百分比变化的代码:
using DataFrames: DataFrame
using ShiftedArrays: lag
prices = DataFrame(
Dict(
:blue => Float32[8.70,8.91,8.71,8.43,8.73],
:orange => [10.66,11.08, 10.71, 11.59, 12.11]
)
)
prices[:,:pct_blue] = prices.blue ./ lag(prices.blue) .- 1 #5-element vector
prices[:,:pct_orange] = prices.orange ./ lag(prices.orange) .- 1 #5-element vector
而不是这样,是否有办法像这样做。当然,这是不正确的:
transform!(prices, [:blue, :orange] => x -> x ./ lag(x) .- 1 => [:pct_blue, :pct_orange])
英文:
If I have a dataframe with two columns, is there a way to compute the percentage change of both the columns in one go? hopefully using the transform
function
Code to compute percentage change for each column seperately
using DataFrames: DataFrame
using ShiftedArrays: lag
prices = DataFrame(
Dict(
:blue => Float32[8.70,8.91,8.71,8.43,8.73],
:orange => [10.66,11.08, 10.71, 11.59, 12.11]
)
)
prices[:,:pct_blue] = prices.blue ./ lag(prices.blue) .- 1 #5-element vector
prices[:,:pct_orange] = prices.orange ./ lag(prices.orange) .- 1 #5-element vector
Instead of this, isnt there a way to do something like this. ofcourse this is incorrect
transform!(prices, [:blue, :orange] => x -> x ./ lag(x) .- 1 => [:pct_blue, :pct_orange])
答案1
得分: 1
将=>
更改为.=>
,并将函数放在()
或[]
之间,您的代码将正常工作。
using DataFrames
transform!(prices, [:blue, :orange] .=> (x -> x ./ lag(x) .- 1) .=> [:pct_blue, :pct_orange])
#5×4 DataFrame
# Row │ blue orange pct_blue pct_orange
# │ Float32 Float64 Float32? Float64?
#─────┼────────────────────────────────────────────────────
# 1 │ 8.7 10.66 missing missing
# 2 │ 8.91 11.08 0.024138 0.0393996
# 3 │ 8.71 10.71 -0.0224467 -0.0333935
# 4 │ 8.43 11.59 -0.0321469 0.0821662
# 5 │ 8.73 12.11 0.0355871 0.0448663
英文:
Changing =>
to .=>
and placing the function between ()
or []
and your code will work.
using DataFrames
transform!(prices, [:blue, :orange] .=> (x -> x ./ lag(x) .- 1) .=> [:pct_blue, :pct_orange])
#5×4 DataFrame
# Row │ blue orange pct_blue pct_orange
# │ Float32 Float64 Float32? Float64?
#─────┼────────────────────────────────────────────────────
# 1 │ 8.7 10.66 missing missing
# 2 │ 8.91 11.08 0.024138 0.0393996
# 3 │ 8.71 10.71 -0.0224467 -0.0333935
# 4 │ 8.43 11.59 -0.0321469 0.0821662
# 5 │ 8.73 12.11 0.0355871 0.0448663
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论