将 Julia Dataframe 列中的特定值替换为随机值

Mac*_*der 13 dataframe julia dataframes.jl

我正在寻找一种用随机数替换 Dataframe 列中的值的方法。它们在执行替换的每一行中都应该不同。

\n

例如,用"X"从中抽取的随机数替换100:120从范围

\n
julia> df = DataFrame(:a=>[1,2,"X","X",5,"X"],)\n6\xc3\x971 DataFrame\n\xe2\x94\x82 Row \xe2\x94\x82 a   \xe2\x94\x82\n\xe2\x94\x82     \xe2\x94\x82 Any \xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xa4\n\xe2\x94\x82 1   \xe2\x94\x82 1   \xe2\x94\x82\n\xe2\x94\x82 2   \xe2\x94\x82 2   \xe2\x94\x82\n\xe2\x94\x82 3   \xe2\x94\x82 X   \xe2\x94\x82\n\xe2\x94\x82 4   \xe2\x94\x82 X   \xe2\x94\x82\n\xe2\x94\x82 5   \xe2\x94\x82 5   \xe2\x94\x82\n\xe2\x94\x82 6   \xe2\x94\x82 X   \xe2\x94\x82\n\n* Replacing X with random values in 100:120 *\n\njulia> df\n6\xc3\x971 DataFrame\n\xe2\x94\x82 Row \xe2\x94\x82 a   \xe2\x94\x82\n\xe2\x94\x82     \xe2\x94\x82 Any \xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xa4\n\xe2\x94\x82 1   \xe2\x94\x82 1   \xe2\x94\x82\n\xe2\x94\x82 2   \xe2\x94\x82 2   \xe2\x94\x82\n\xe2\x94\x82 3   \xe2\x94\x82 103 \xe2\x94\x82\n\xe2\x94\x82 4   \xe2\x94\x82 110 \xe2\x94\x82\n\xe2\x94\x82 5   \xe2\x94\x82 5   \xe2\x94\x82\n\xe2\x94\x82 6   \xe2\x94\x82 116 \xe2\x94\x82\n\n
Run Code Online (Sandbox Code Playgroud)\n

我尝试过使用replacerand之前已评估过replace

\n
julia> replace!(df.a,"X"=> rand(100:120))\njulia> df\n6\xc3\x971 DataFrame\n\xe2\x94\x82 Row \xe2\x94\x82 a   \xe2\x94\x82\n\xe2\x94\x82     \xe2\x94\x82 Any \xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xa4\n\xe2\x94\x82 1   \xe2\x94\x82 1   \xe2\x94\x82\n\xe2\x94\x82 2   \xe2\x94\x82 2   \xe2\x94\x82\n\xe2\x94\x82 3   \xe2\x94\x82 115 \xe2\x94\x82\n\xe2\x94\x82 4   \xe2\x94\x82 115 \xe2\x94\x82\n\xe2\x94\x82 5   \xe2\x94\x82 5   \xe2\x94\x82\n\xe2\x94\x82 6   \xe2\x94\x82 115 \xe2\x94\x82\n
Run Code Online (Sandbox Code Playgroud)\n

Prz*_*fel 12

单衬可以是:

replace!( x-> x=="X" ? rand() : x, df.a)
Run Code Online (Sandbox Code Playgroud)


Bog*_*ski 6

或者使用操作规范语法:

transform!(df, :a => ByRow(a -> a == "X" ? rand() : a)=> :a)
Run Code Online (Sandbox Code Playgroud)

或者你可以这样做:

rand!(view(df.a, df.a .== "X"), Float64)
Run Code Online (Sandbox Code Playgroud)

另一种就地方法(但replace!可能会更有效)