【问题标题】:How to print pandas DataFrame without index如何打印没有索引的熊猫数据框
【发布时间】:2014-08-29 22:42:33
【问题描述】:

我想打印整个数据框,但我不想打印索引

另外,一列是日期时间类型,我只想打印时间,而不是日期。

数据框如下所示:

   User ID           Enter Time   Activity Number
0      123  2014-07-08 00:09:00              1411
1      123  2014-07-08 00:18:00               893
2      123  2014-07-08 00:49:00              1041

我希望它打印为

User ID   Enter Time   Activity Number
123         00:09:00              1411
123         00:18:00               893
123         00:49:00              1041

【问题讨论】:

  • 您使用的术语(“数据框”、“索引”)让我认为您实际上是在使用 R,而不是 Python。请说清楚。无论如何,我们需要查看打印此“数据框”的现有代码,以便有机会提供帮助。请阅读并遵循stackoverflow.com/help/mcve 的说明
  • ... 我会说,如果这实际上是 Python 并且那些是第二列中的 datetime.datetime 对象,那么您可以使用 strftime 方法以适当的格式打印时间字符串(可能是"%H:%M:%S")。
  • @Zack:DataFrame是流行的Python数据分析库pandas中二维数据结构的名称。

标签: python datetime pandas dataframe


【解决方案1】:

取自kingmakerking的回答:

当你将单元格更改为markdown时,Jupyter notebook可以将GFM Markdown表格语法转换为表格。

因此,将 tablefmt 更改为 'github' 而不是 'psql' 并复制和粘贴。

    print(tabulate(dframe, headers='keys', tablefmt='github', showindex=False))

(Python 3)

【讨论】:

    【解决方案2】:

    在 Jupyter Notebook 上工作以打印没有索引列的 DataFrame,这对我有用:

    display(table.hide_index())
    

    【讨论】:

      【解决方案3】:

      python 2.7

      print df.to_string(index=False)
      

      python 3

      print(df.to_string(index=False))
      

      【讨论】:

      • 这很好,但是它不再包含 tab-sep,这在复制到 excel 时是个障碍
      • @Rockbar 如果你想复制/导出到excel,你应该使用df.to_csv
      • 对我来说,列标签出来的数据不符合数据(开头缺少空格)。可能是因为我的数据占用的字符多于列标签。添加参数 justify='left' 可以修复它,但显然会改变列标签的对齐方式。
      • 您也可以使用df.to_clipboard(),然后粘贴到Excel中。对于处理 Windows 的愚蠢的“你不能编辑打开的文档”BS 很有用。
      • df.to_excel('filename.xlsx', index=False)
      【解决方案4】:

      打印时下面的行会隐藏DataFrame的索引列

      df.style.hide_index()
      

      更新:使用 Python 3.7 测试

      【讨论】:

      • 需要 jinja2 包,并且在 Python 3.7 中不会产生所需的输出
      • 我发现这个答案在做报告时复制/粘贴到表格中最有效,谢谢!
      • 我最喜欢这个答案 - 使用 Python 3.8 产生正确的输出并且无需打印数据框即可工作(对 Jupyter 笔记本/实验室应用程序有用)
      • 在 Python 3.9.5 中,这不起作用:运行它然后打印 df 仍然在左侧显示行索引号。 (从 bash shell 在常规终端/控制台中运行时。)
      • 小数位加零
      【解决方案5】:

      为了保留“漂亮的打印”使用

      from IPython.display import HTML
      HTML(df.to_html(index=False))
      

      【讨论】:

      • 这是完美的谢谢。笔记本中仍然显示一个干净的 DataFrame,只是没有索引列。正是我想要的。
      • fyi,HTML 不会显示在输出 的 REPL 中
      【解决方案6】:

      与上面许多使用 df.to_string(index=False) 的答案类似,我经常发现有必要提取单列值,在这种情况下,您可以使用以下命令指定带有 .to_string 的单个列:

      data = pd.DataFrame({'col1': np.random.randint(0, 100, 10), 
          'col2': np.random.randint(50, 100, 10), 
          'col3': np.random.randint(10, 10000, 10)})
      
      print(data.to_string(columns=['col1'], index=False)
      
      print(data.to_string(columns=['col1', 'col2'], index=False))
      

      它提供了易于复制(且无索引)的输出,以便在其他地方粘贴使用 (Excel)。示例输出:

      col1  col2    
      49    62    
      97    97    
      87    94    
      85    61    
      18    55
      

      【讨论】:

        【解决方案7】:

        如果你想漂亮地打印数据帧,那么你可以使用tabulate 包。

        import pandas as pd
        import numpy as np
        from tabulate import tabulate
        
        def pprint_df(dframe):
            print tabulate(dframe, headers='keys', tablefmt='psql', showindex=False)
        
        df = pd.DataFrame({'col1': np.random.randint(0, 100, 10), 
            'col2': np.random.randint(50, 100, 10), 
            'col3': np.random.randint(10, 10000, 10)})
        
        pprint_df(df)
        

        具体来说,showindex=False,顾名思义,允许您不显示索引。输出如下所示:

        +--------+--------+--------+
        |   col1 |   col2 |   col3 |
        |--------+--------+--------|
        |     15 |     76 |   5175 |
        |     30 |     97 |   3331 |
        |     34 |     56 |   3513 |
        |     50 |     65 |    203 |
        |     84 |     75 |   7559 |
        |     41 |     82 |    939 |
        |     78 |     59 |   4971 |
        |     98 |     99 |    167 |
        |     81 |     99 |   6527 |
        |     17 |     94 |   4267 |
        +--------+--------+--------+
        

        【讨论】:

          【解决方案8】:

          要回答“如何打印没有索引的数据帧”问题,您可以将索引设置为空字符串数组(数据帧中的每一行一个),如下所示:

          blankIndex=[''] * len(df)
          df.index=blankIndex
          

          如果我们使用您帖子中的数据:

          row1 = (123, '2014-07-08 00:09:00', 1411)
          row2 = (123, '2014-07-08 00:49:00', 1041)
          row3 = (123, '2014-07-08 00:09:00', 1411)
          data = [row1, row2, row3]
          #set up dataframe
          df = pd.DataFrame(data, columns=('User ID', 'Enter Time', 'Activity Number'))
          print(df)
          

          通常会打印为:

             User ID           Enter Time  Activity Number
          0      123  2014-07-08 00:09:00             1411
          1      123  2014-07-08 00:49:00             1041
          2      123  2014-07-08 00:09:00             1411
          

          通过创建一个包含与数据框中的行数一样多的空字符串的数组:

          blankIndex=[''] * len(df)
          df.index=blankIndex
          print(df)
          

          它将从输出中删除索引:

            User ID           Enter Time  Activity Number
                123  2014-07-08 00:09:00             1411
                123  2014-07-08 00:49:00             1041
                123  2014-07-08 00:09:00             1411
          

          并且在 Jupyter Notebooks 中将按照此屏幕截图进行渲染: Juptyer Notebooks dataframe with no index column

          【讨论】:

          • 尽管有点奇怪,但这是 IMO 的最佳解决方案。
          • 这真的是最好的现代解决方案吗?
          【解决方案9】:

          如果您只想打印一个字符串/json,可以通过以下方式解决:

          print(df.to_string(index=False))

          Buf 如果你也想序列化数据甚至发送到 MongoDB,最好这样做:

          document = df.to_dict(orient='list')

          目前有 6 种方式来定位数据,更多信息请查看panda docs,哪种方式更适合您。

          【讨论】:

            【解决方案10】:
            print(df.to_csv(sep='\t', index=False))
            

            或者可能:

            print(df.to_csv(columns=['A', 'B', 'C'], sep='\t', index=False))
            

            【讨论】:

            • 这怎么可能,因为 DataFrame.to_csv 没有返回值?我只打印了无。
            • 确实,OP 要求打印。此注释不打印数据框,而是将其保存为 CSV。
            猜你喜欢
            • 2019-02-23
            • 2020-03-19
            • 2023-01-26
            • 2015-04-19
            • 2021-02-26
            • 2018-01-15
            • 1970-01-01
            相关资源
            最近更新 更多