在 Python pandas 中,您可以傳遞一個字典 df.replace,以便將每個匹配的鍵替換為其對應的值。我經常使用此功能來替換西班牙語中弄亂句子標記器的單詞縮寫。
朱莉婭有類似的東西嗎?或者甚至更好,以便我(和未來的用戶)可以從經驗中學習,關于如何在 Julia 的優美和高性能語法中實作這樣一個功能的任何想法?
謝謝!
編輯:根據要求添加示例
輸入:
julia> DataFrames.DataFrame(Dict("A" => ["This is an ex.", "This is a samp.", "This is a samp. of an ex."]))
3×1 DataFrame
Row │ A
│ String
─────┼────────────────────
1 │ This is an ex.
2 │ This is a samp.
3 │ This is a samp. of an ex.
期望的輸出:
3×1 DataFrame
Row │ A
│ String
─────┼────────────────────
1 │ This is an example
2 │ This is a sample
3 │ This is a sample of an example
uj5u.com熱心網友回復:
在 Julia 中,此功能也是replace. 它需要一個集合并替換其中的元素。最簡單的形式是:
julia> x = ["a", "ab", "ac", "b", "bc", "bd"]
6-element Vector{String}:
"a"
"ab"
"ac"
"b"
"bc"
"bd"
julia> replace(x, "a" => "aa", "b" => "bb")
6-element Vector{String}:
"aa"
"ab"
"ac"
"bb"
"bc"
"bd"
如果您有更復雜的替換模式,您可以傳遞一個執行替換的函式:
julia> replace(x) do s
length(s) == 1 ? s^2 : s
end
6-element Vector{String}:
"aa"
"ab"
"ac"
"bb"
"bc"
"bd"
也有replace!在原地做同樣的事情。
這是你想要的嗎?
編輯
替換字串向量中的子字串:
julia> df = DataFrame("A" => ["This is an ex.", "This is a samp.", "This is a samp. of an ex."])
3×1 DataFrame
Row │ A
│ String
─────┼───────────────────────────
1 │ This is an ex.
2 │ This is a samp.
3 │ This is a samp. of an ex.
julia> df.A .= replace.(df.A, "ex." => "example", "samp." => "sample")
3-element Vector{String}:
"This is an example"
"This is a sample"
"This is a sample of an example"
注意兩點:
- 您不需要傳遞
Dict給DataFrame建構式。傳遞對就足夠了。 - 在分配中,我使用了
.=not=,它對現有向量中的更新值進行就地替換(我將其顯示為與@Sundar R 在評論中提出的內容進行比較,這是分配新向量的替代方法;差異可能在您的情況下并不重要,但我只是想向您展示兩種語法)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516502.html
