Skip to content

Commit eaa0075

Browse files
Document DataFrame definition in code file using CSV.jl (#3501)
1 parent 900d016 commit eaa0075

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

docs/src/man/importing_and_exporting.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,58 @@ As you can see the code required to transform `iris` into a proper input to the
113113
format is not easy. Therefore CSV.jl is the preferred package to write CSV files
114114
for data stored in data frames.
115115

116+
### `DataFrame` Definition in Source Code
117+
Sometimes, you might want to define a `DataFrame` with data directly in the source
118+
code. For better readability you probably want to define it in a way which resembles
119+
a table. This can be done with `CSV.jl` like this:
120+
121+
```julia
122+
df = CSV.read("""
123+
name,age,children
124+
John,54.0,0
125+
Sally,34.0,2
126+
Roger,79.0,4
127+
""" |> IOBuffer, DataFrame)
128+
```
129+
130+
This will result in the following `DataFrame`:
131+
132+
```
133+
3×3 DataFrame
134+
Row │ name age children
135+
│ String7 Float64 Int64
136+
─────┼────────────────────────────
137+
1 │ John 54.0 0
138+
2 │ Sally 34.0 2
139+
3 │ Roger 79.0 4
140+
```
141+
142+
As the readability in the source code of the above format is not great, you can make
143+
use of [`CSV.jl`'s options](https://csv.juliadata.org/stable/examples.html#csv_string)
144+
to find a format which works for you, e.g. using
145+
[Unicode box drawing characters](https://en.wikipedia.org/wiki/Box-drawing_characters#Unicode)
146+
147+
```julia
148+
data = """
149+
┌───────┬──────┬──────────┐
150+
│ name │ age │ children │
151+
├───────┼──────┼──────────┤
152+
│ John │ 54.0 │ 0 │
153+
│ Sally │ 34.0 │ 2 │
154+
│ Roger │ 79.0 │ 4 │
155+
└───────┴──────┴──────────┘
156+
"""
157+
```
158+
159+
You can then create the above `DataFrame` object with
160+
161+
```julia
162+
df = CSV.read(data |> IOBuffer, DataFrame, normalizenames=true,
163+
header=2, skipto=4, footerskip=1, delim='',
164+
drop=(i, name) -> startswith(name |> String, "Column")
165+
) .|> x -> x isa AbstractString ? strip(x) : x
166+
```
167+
116168
## Other formats
117169

118170
Other data formats are supported for reading and writing in the following packages

0 commit comments

Comments
 (0)