【问题标题】:np.savetxt style nicely tabulated output for pandas DataFrame.to_csvpandas DataFrame.to_csv 的 np.savetxt 样式很好地列出了输出
【发布时间】:2015-01-04 21:17:30
【问题描述】:

我剪掉了一些头发,但仍然无法获得漂亮的表格输出。

总之,我希望.to_csv()方法保存的文件是这样的:

               K0         V0     dK_dT         a             b
value  237.496942  82.845746 -0.037012  0.000006  1.359708e-08
std      2.094088   0.012948  0.004415  0.000001  1.550236e-09

但凭我的能力,print result.to_csv(float_format='%10.2g', sep=' ') 给了我:

 K0 V0 dK_dT a b
value "   2.4e+02" "        83" "    -0.037" "   5.8e-06" "   1.4e-08"
std "       2.1" "     0.013" "    0.0044" "     1e-06" "   1.6e-09"
  1. 标题不会自动对齐。
  2. 引号破坏了等宽流。

我尝试将quoting 设置为一些csv.QUOTE_MINIMAL,它们本质上是整数,但没有运气。据我所知,NumPy 可以通过savetxt(format='%10.2g') 轻松做到这一点。

我错过了什么?

【问题讨论】:

    标签: csv numpy pandas


    【解决方案1】:

    您可以使用to_string(),而不是to_csv()。例如,

    In [80]: df
    Out[80]: 
                A         B             C
    a  123.456789  0.702380  7.071752e-08
    b    1.230000  0.323674  6.075386e-08
    c    0.012300  0.621974  7.918532e-08
    d    0.000000  0.818291  5.480469e-08
    e   -9.876543  0.117978  9.831873e-08
    
    In [81]: txt = df.to_string()
    
    In [82]: print txt
                A         B             C
    a  123.456789  0.702380  7.071752e-08
    b    1.230000  0.323674  6.075386e-08
    c    0.012300  0.621974  7.918532e-08
    d    0.000000  0.818291  5.480469e-08
    e   -9.876543  0.117978  9.831873e-08
    

    然后您可以将txt 写入文件。

    【讨论】:

    • 太棒了!我知道应该有一个最直接的方法。但是为什么这个方法不接受float_format 的简单字符串,而必须是函数呢?就像 to_csv() 一样?
    • 我不知道。这也让我很困惑。在类似的函数中使用相同的参数名称会导致不同的行为是一种不幸的 API 设计选择。
    【解决方案2】:

    这是一个愚蠢的技巧:使用 ASCII BEL (bell) 作为引号字符。至少在我的系统上,这根本不打印引号:

    result.to_csv(float_format='%10.2g', sep=' ', index=False, quotechar='\a')
    

    或者使用一个虚拟字符并在最后替换它:

    ss = result.to_csv(float_format='%10.2g', sep=' ', index=False, quotechar='^')
    print ss.replace('^', '')
    

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 2021-07-16
      • 1970-01-01
      • 2011-04-13
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      • 2013-03-25
      相关资源
      最近更新 更多