How do I export strings to CSV file?

using CSV,DataFrames
data1=DataFrame(CSV.File(“D:\\documemt\\julia\\aaa.csv”))
a=[1,1,2,2,1,2]
index=findall(in(1),a)
Data=data1.colum1[index]
CSV.write(“BBBB.csv”,Data)

The contents of the aaa. CSV file are as follows
colum1
2018/12/30 0:00
2018/12/30 1:00
2018/12/30 2:00
2018/12/30 3:00
2018/12/30 4:00
2018/12/30 5:00
2018/12/30 6:00
2018/12/30 7:00
2018/12/30 8:00
2018/12/30 9:00

The last line of the code reports an error, as follows:
LoadError: ArgumentError: ‘Array{String,1}’ iterates ‘String’ values, which doesn’t satisfy the Tables.jl AbstractRow interface

How do I export the Data’s elements to a CSV file?

As the error says, CSV.write expects you to provide an object that is a Tables.jl Table (in the sense of Tables.istable(obj) == true).

The simplest object that satisfies this requirement is probably a named tuple, so you could do:

CSV.write("BBBB.csv", (column1 = Data))

where (column1 = Data) constructs the named tuple.

1 Like

I did the operation according to your advice, no error was reported, but I could not find the BBBB file. Is the last code invalid?

Apologies, it was indeed slightly wrong - you want either (column1 = Data, ) (note the trailing comma) or (; column1 = Data) (note the leading semicolon) to construct the NamedTuple.

2 Likes

I still couldn’t find the BBBB file after running

using CSV,DataFrames
data1=DataFrame(CSV.File("D:\\documemt\\julia\\aaa.csv"))
a=[1,1,2,2,1,2]
index=findall(in(1),a)
Data=data1.colum1[index]
CSV.write("BBBB.csv";column1=Data)

Can you find this file?
How can I solve it?

No sorry you misunderstood what I was trying to say: the leading semicolon (or trailing comma) are just in the creation of the NamedTuple, so:

(; column1 = Data)

which should then be passed as the second argument to CSV.write:

CSV.write("BBBB.csv", (; column1 = Data))
1 Like

Ok I‘ve got it. Thank you very much~

Glad you got it to work! A couple of other general hints if I may:

  • The CSV.jl package has brought back the CSV.read function, so you can do CSV.read("myfile.csv", DataFrame) to read a file into a DataFrame

  • If you know you want to write a table back out to csv, it’s probably easier to continue operating on a DataFrame rather than pulling out a Vector and creating a NamedTuple from that - I would probably do data1[index, [:column1]]. Note the column index is passed in [] brackets, making it an Array{Symbol ,1} (rather than just a Symbol). Doing so means the indexing operation returns a DataFrame.

2 Likes

Nice! Your proposed code is much better than mine. Thanks again~

1 Like