gpt4 book ai didi

dataframe - 替换 Julia 中多种数据类型数组的子字符串

转载 作者:行者123 更新时间:2023-12-04 15:21:23 24 4
gpt4 key购买 nike

我有一个从多个数据类型的 csv 导入的数组。我想删除所有逗号 (,) 和美元符号 ($)。包含逗号和美元符号的三列。

在为带有逗号和美元符号的列创建新数组时,我可以使用以下方法成功完成。

using CSV, DataFrames
df = DataFrame!(CSV.File("F:SampleFile.csv"))
dfmo = Array(df[!,30])
dfmo = collect(skipmissing(dfmo))
dfmo = replace.(dfmo,"\$"=>"")
dfmo = replace.(dfmo,","=>"")

当尝试用下面的方法应用于整个向量时

df=replace.(df,","=>"")

我得到一个错误:

MethodError: no method matching similar(::Int64, ::Type{Any})
Closest candidates are:
similar(!Matched::ZMQ.Message, ::Type{T}, !Matched::Tuple{Vararg{Int64,N}} where N) where T at C:\Users\

然后我尝试使用下面的索引,但在索引到字符串时也出现错误。

for i in df
for j in df
if datatype(df[i,j]) == String
df=replace(df[i,j],","=>"")
end
end
end
MethodError: no method matching similar(::Int64, ::Type{Any})
Closest candidates are:
similar(!Matched::ZMQ.Message, ::Type{T}, !Matched::Tuple{Vararg{Int64,N}} where N) where T at C:\Users\

在多个数据类型的数组中替换子字符串的最有效方法是什么?

最佳答案

看到您的代码,我知道您想要就地操作(即更改原始数据框)。

在您的代码中使用循环方法,您可以这样做:

for col in axes(df,2)
for row in axes(df, 1)
cell = df[row, col]
if cell isa AbstractString
df[row, col] = replace(cell, "," => "")
end
end
end

使用广播你可以达到同样的目的:

helper_fun(cell) = cell isa AbstractString ? replace(cell, "," => "") : cell

df .= helper_fun.(df)

关于dataframe - 替换 Julia 中多种数据类型数组的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63206205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com