1

I am using php-ml and taking in a .csv file with 6 columns and thousands of lines, i want every 5th element (column) of each array to be saved in $samples. I have tried the following which gives me the first element of each array.

$dataset = new CsvDataset('myNewCsvFile.csv', 1);     
$samples = [];

        foreach ($dataset->getSamples() as $sample) {
            $samples[] = $sample[0];
        }

I don't understand why this isn't reading in my .csv fully, if i change the indext of sample[0] to any other index i get the following error:

Notice: Undefined offset: 1 in C:\xampp\htdocs\test\index.php on line 19

This suggests to me that it's only reading the first column in each row, which is proved if i print out the array Samples i get what i would expect which is as follows:

    Array
(
    [0] => 1157
    [1] => 1157
    [2] => 1157
    [3] => 1157
    [4] => 1157
    [5] => 1157
    [6] => 1157
    [7] => 1157
    [8] => 1157
    [9] => 1157
    [10] => 1157
    [11] => 1157
    [12] => 1157
    [13] => 1157
    [14] => 1157
    [15] => 1157
    [16] => 1157
    [17] => 1157
    [18] => 1157
    [19] => 1157
    [20] => 1157
    [21] => 1157
    [22] => 1157

And so on which is correct. Can anyone explain why this isn't reading in my full .csv file?

neubert
  • 15,947
  • 24
  • 120
  • 212
johnfish92
  • 157
  • 2
  • 12

1 Answers1

0

As the reference document shows, you should pass the constructor a number of columns to read as a second argument and you are only asking it for one column. In the following snippet I put another number to get more columns.

use Phpml\Dataset\CsvDataset;

// the third argument makes it ignore the heading row
$dataset = new CsvDataset('myNewCsvFile.csv',4,true);     

foreach ($dataset->getSamples() as $sample) {
    print_r($sample);
}

Outputs:

Array
(
    [0] => 101
    [1] => 201
    [2] => 301
    [3] => 401
)
Array
(
    [0] => 102
    [1] => 202
    [2] => 302
    [3] => 402
)

And the myNewCsvFile.csv is;

┌─────┬─────┬─────┬─────┬─────┬─────┐
│  1  │  2  │  3  │  4  │  5  │  6  │
├─────┼─────┼─────┼─────┼─────┼─────┤
│ 101 │ 201 │ 301 │ 401 │ 501 │ 601 │
│ 102 │ 202 │ 302 │ 402 │ 502 │ 602 │
└─────┴─────┴─────┴─────┴─────┴─────┘
David Lemon
  • 1,560
  • 10
  • 21