导入以逗号作为小数分隔符的数字的 csv

Import csv which have numerics with comma as the decimal separator

我有一个 5 GB csv 文件,需要一个多小时才能导入到 stata。

除其他外,原因是它采用欧洲格式,即它是一个 ; 分隔文件,数字列以 , 作为小数点分隔符。例如:

V1  V2   V3
A   2,4  10,1
B   30   1,4

问题是 stata 假设数字列是字符串变量,因此试图以一种非常低效的方式导入它(试图将列声明为数字只会给我缺失值)。

是否有 command/option 我输入了不同的小数点分隔符,以便导入过程更快?

如果您的数据文件如下所示:

A; 2,4; 10,1  
B; 30; 1,4

您可以执行以下操作:

import delimited whatever_filename.txt, delimiters(";") varnames(nonames)
destring v2 v3, dpcomma replace

list

   +-----------------+
   | v1    v2     v3 |
   |-----------------|
1. |  A   2.4   10.1 |
2. |  B    30    1.4 |
   +-----------------+

从 Stata 版本 15 开始,没有一种方法可以一步完成。我认为唯一的其他解决方案是通过将逗号更改为句点来预处理数据文件。 Excel 可以轻松做到这一点。

我认为您正在寻找的功能已添加到 Stata 16。命令 import delimited 具有新选项 parselocale()groupseparator()decimalseparator()

请参阅下面 whatsnew15to16 中的 10/c

help whatsnew15to16
  1. import delimited is the existing command to import data from delimited text files. It has been enhanced.

    a. It is faster. It is 10% faster in general, and 2 to 4 times faster in some cases.

    b. It detects delimiters better. In addition to commas and tabs, it now detects pipes, colons, and semicolons.

    c. New options allow numeric parsing based on locale. The options are parselocale(), groupseparator(), and decimalseparator().

    d. Mismatched quotes in the imported file are reported so that you can fix them.

对于数据:

A; 2,4; 10,1  
B; 30; 1,4

您可以执行以下操作:

import delimited "D:\data.csv", varnames(nonames) parselocale(es_ES)

import delimited "D:\data.csv", varnames(nonames) groupseparator(.) decimalseparator(,) 
list

     +-----------------+
     | v1    v2     v3 |
     |-----------------|
  1. |  A   2.4   10.1 |
  2. |  B    30    1.4 |
     +-----------------+

describe

    Contains data
      obs:             2                          
     vars:             3                          
    --------------------------------------------------------------------------------
                  storage   display    value
    variable name   type    format     label      variable label
    --------------------------------------------------------------------------------
    v1              str1    %9s                   
    v2              float   %8.0g                 
    v3              float   %9.0g