doumindang2416 2017-04-29 11:16
浏览 97

读入.csv文件PHP-ML

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?

  • 写回答

1条回答 默认 最新

  • doucao1888 2018-05-29 09:02
    关注

    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 │
    └─────┴─────┴─────┴─────┴─────┴─────┘
    
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算