Home > OS >  Read column of CSV file as array
Read column of CSV file as array

Time:09-29

I am trying to read a column from a CSV file into an array.

So far I have successfully read the file with the code below.

load 'csv'

data =: readcsv '/Users/max/Desktop/prices.csv'

Typing data in the interpreter brings the following table (which in what I expect)

┌────────────┬────────┬────────┐
│Date        │Price   │Open    │
├────────────┼────────┼────────┤
│Jun 01, 2022│29,798.5│31,793.1│
├────────────┼────────┼────────┤
│Jun 02, 2022│30,455.5│29,798.6│
├────────────┼────────┼────────┤
│Jun 03, 2022│29,700.9│30,455.7│
├────────────┼────────┼────────┤
│Jun 04, 2022│29,864.3│29,700.9│
├────────────┼────────┼────────┤
│Jun 05, 2022│29,913.0│29,865.1│
├────────────┼────────┼────────┤
│Jun 06, 2022│31,367.6│29,911.2│
├────────────┼────────┼────────┤
│Jun 07, 2022│31,128.8│31,370.3│
├────────────┼────────┼────────┤
│Jun 08, 2022│30,201.6│31,127.2│
├────────────┼────────┼────────┤

Now my question is, how do I extract a column like 'Open' and then transform it into a variable like "31,793.1" "29,798.6" "30,455.7" "29,700.9"

CodePudding user response:

You can use the data as you would use any other boxed array.

data
┌────┬────┬────┐
│col1│col2│col3│
├────┼────┼────┤
│a   │b   │c   │
├────┼────┼────┤
│d   │e   │f   │
├────┼────┼────┤
│g   │h   │i   │
└────┴────┴────┘

NB. Column 3
2{"1 data
┌────┬─┬─┬─┐
│col3│c│f│i│
└────┴─┴─┴─┘

NB. Column 3 without the header
}. 2{"1 data
┌─┬─┬─┐
│c│f│i│
└─┴─┴─┘

NB. Col3 data unboxed and joined
,> }. 2{"1 data
cfi

CodePudding user response:

In Dyalog APL:

      data ← ⎕CSV '\tmp\prices.csv'

Right-reduce to get the rightmost column, then drop the header:

      1 ↓ ⊢/data
┌────────┬────────┬────────┬────────┬────────┬────────┬────────┬────────┐
│31,793.1│29,798.6│30,455.7│29,700.9│29,865.1│29,911.2│31,370.3│31,127.2│
└────────┴────────┴────────┴────────┴────────┴────────┴────────┴────────┘

OR, indicate a single header row, then get the main data with etc.:

      ⊢/⊃⎕CSV '\tmp\prices.csv' ⍬ ⍬ 1
┌────────┬────────┬────────┬────────┬────────┬────────┬────────┬────────┐
│31,793.1│29,798.6│30,455.7│29,700.9│29,865.1│29,911.2│31,370.3│31,127.2│
└────────┴────────┴────────┴────────┴────────┴────────┴────────┴────────┘
  • Related