在DataFrames中使用可写文件将字符串写入文件的默认方法是,它们被引号包围:
using DataFrames
df = DataFrame(letters=["A","B","C"],numbers=[1,2,3])
writetable("df_file", df, separator='\t')生成以下文件:
"letters" "numbers"
"A" 1
"B" 2
"C" 3有一个选项可以更改商语字符:
writetable("df_file", df, separator='\t', quotemark='.')
.letters. .numbers.
.A. 1
.B. 2
.C. 3但如果没有指定字符,则此操作不起作用
writetable("df_file", df, separator='\t', quotemark='')
ERROR: syntax: invalid character literal我的问题是:在没有引号字符的情况下,我怎么写字符串?这将是我需要的输出:
letters numbers
A 1
B 2
C 3我目前使用的是JuliaVersion0.4.1,DataFrames包版本0.6.10。
发布于 2016-08-03 13:05:56
根据这个GitHub讨论,DataFrames包的创建者不相信用户有这种能力来控制他们的输出。
我个人的建议是,只需转换为Array,然后使用朱莉娅的writedlm(),它可以信任用户知道他们想要写什么文件:
writedlm(FileName, convert(Array,df), '\t')若要包含标题,可以使用以下内容:
open(FileName, "w") do f
writedlm(f, names(df)', '\t')
writedlm(f, convert(Array,df), '\t')
end也请参阅这个具有类似答案的相关问题:是否有一种方法可以将字符串用作可写()- Julia中的分隔符
发布于 2016-08-03 12:31:04
我很想像这样快速地写一篇:
julia> n, p = size(df)
(3,2)
julia> open("/tmp/df_file.txt", "w") do f
for i in 1:n
for j in 1:p
write(f, string(df[i, j]))
write(f, "\t")
end
write(f, "\n")
end
end或者,如果我有更多的时间,我可能会开始写这样的东西( writetable函数的源代码的一个修改版本):
julia> function myprinttable(io::IO,
df::AbstractDataFrame;
header::Bool = true,
separator::Char = ',',
quotemark::AbstractString = "\"",
nastring::AbstractString = "NA")
n, p = size(df)
etypes = eltypes(df)
if header
cnames = DataFrames._names(df)
for j in 1:p
print(io, quotemark)
print(io, cnames[j])
print(io, quotemark)
if j < p
print(io, separator)
else
print(io, '\n')
end
end
end
quotestr = quotemark
for i in 1:n
for j in 1:p
if ! (isna(df[j],i))
if ! (etypes[j] <: Real)
print(io, quotemark)
DataFrames.escapedprint(io, df[i, j], quotestr)
print(io, quotemark)
else
print(io, df[i, j])
end
else
print(io, nastring)
end
if j < p
print(io, separator)
else
print(io, '\n')
end
end
end
return
end
julia> open("/tmp/df_file.txt", "w") do f
myprinttable(f, df, header=true, separator='\t', quotemark="")
end(大部分是未经测试的)
它只是将quotemark从Char改为String。(我仍然习惯了朱莉娅在某些地方使用查尔而不是单字串。
https://stackoverflow.com/questions/38736893
复制相似问题