kdb+: 将 table 保存到 csv 文件中

kdb+: Save table into a csv file

我有下面的 table "dates" ,它有一个带有符号的 sym 列和一个带有字符串列表的 d 列,我想将它保存到一个常规的 CSV 文件中。找不到一个好的方法来做到这一点。有什么建议吗?

q)dates
sym  d
----------------------------------------------------------------------------
6AH0 "1970.03.16" "1980.03.17" "1990.03.19" "2010.03.15" 
6AH6 "1976.03.15" "1986.03.17" "1996.03.18" "2016.03.14" 
6AH7 "1977.03.14" "1987.03.16" "1997.03.17" "2017.03.13" 
6AH8 "1978.03.13" "1988.03.14" "1998.03.16" "2018.03.19" 
6AH9 "1979.03.19" "1989.03.13" "1999.03.15" "2019.03.18" 

当我尝试进行常规保存时,出现以下错误:

q)save `:dates.csv
k){$[t&77>t:@y;$y;x;-14!'y;y]}
'type
q))

Kdb+ 中的内部 table->csv 转换函数无法处理列中的嵌套列表。 table 中的 d 列是一个字符列表。但是,转换函数能够处理简单的嵌套列(深度为 1)。

因此,您可以将 d 列转换为字符列表,然后使用内部函数保存为 CSV:

/ generate a table of dummy data
q)show dates:flip `sym`d!(`6AH0`6AH6`6AH7;string (3;0N)#12?.z.d)
    sym  d
    --------------------------------------------------------
    6AH0 "2008.02.04" "2015.01.02" "2003.07.05" "2005.02.25"
    6AH6 "2012.10.25" "2008.08.28" "2017.01.25" "2007.12.27"
    6AH7 "2004.02.01" "2005.06.06" "2013.02.11" "2010.12.20"

/ convert 'd' column to simple list - the (" " sv') is the conversion func here
q)@[`dates;`d;" " sv']
    `dates

/ review what was done
q)show dates
    sym  d
    --------------------------------------------------
    6AH0 "2008.02.04 2015.01.02 2003.07.05 2005.02.25"
    6AH6 "2012.10.25 2008.08.28 2017.01.25 2007.12.27"
    6AH7 "2004.02.01 2005.06.06 2013.02.11 2010.12.20"

/ save to csv
q)save `:dates.csv
    `:dates.csv

/ review saved csv 
q)\cat dates.csv
    "sym,d"
    "6AH0,2008.02.04 2015.01.02 2003.07.05 2005.02.25"
    "6AH6,2012.10.25 2008.08.28 2017.01.25 2007.12.27"
    "6AH7,2004.02.01 2005.06.06 2013.02.11 2010.12.20"

根据 csv 规范,您需要将列表展平并用逗号分隔每个列表并用双引号将列表加引号。

'save' 限制在于文件名必须与您保存的全局变量相同。

如果让我回答你的问题,我会这样做;

    `:myFileNamedWhatever.csv 0: csv 0: select sym,csv sv'd from dates

说明;

    csv 0: table /csv is a variable, literally defined as "," - its good for readability. csv 0: table converts the table to a comma separated list of strings
    `:file 0: listOfStrings /this takes a LIST of strings and pushes them to the file handle. Each element of the list is a new line in the file

我更喜欢这种方法,因为它是通用的并且允许保存各种类型。您可以在函数等中使用它。

后来我决定将它保存为竖线(或任何东西)分隔的文件;

    `:myNewFile.psv 0: "|" 0: select sym,"|"sv'd from table