我正在使用Pandas包,它创建了一个DataFrame对象,它基本上是一个带标签的矩阵。通常我的列具有长字符串字段,或者具有许多列的数据帧,因此简单的打印命令不能很好地工作。我写了一些文本输出函数,但它们并不好。
我真正喜欢的是一个简单的GUI,它允许我与数据帧/矩阵/表进行交互。就像你在SQL工具中找到的一样。基本上是一个窗口,它有一个只读电子表格,如查看数据。我可以通过长桌等扩展列,页面向上和向下翻页等。
我怀疑这样的事情存在,但我必须用错误的条款谷歌搜索。如果它是特定的熊猫会很棒,但我猜我可以使用任何矩阵接受工具。 (顺便说一句 - 我在Windows上。)
有什么指针吗?
或者,相反,如果有人知道这个空间并且知道这可能不存在,那么是否有一个简单的GUI框架/小部件的任何建议我都可以使用它自己滚动? (但由于我的需求有限,我不愿意学习一个大的GUI框架并为这一部分做一堆编码。)
我使用来自PyQt的QTableWidget
来显示DataFrame
。我创建了一个QTableWidgetObject
然后填充QTableWidgetItems
用DataFrame
值创建。以下是读取CSV文件,创建DataFrame
然后在GUI中显示的代码片段:
df = read_csv(filename, index_col = 0,header = 0)
self.datatable = QtGui.QTableWidget(parent=self)
self.datatable.setColumnCount(len(df.columns))
self.datatable.setRowCount(len(df.index))
for i in range(len(df.index)):
for j in range(len(df.columns)):
self.datatable.setItem(i,j,QtGui.QTableWidgetItem(str(df.iget_value(i, j))))
更新:
由于这个答案很老,所以值得更新。现在有很多选项可用于查看GUI中的数据帧。
如果有人仍想编写一个简单的GUI来查看Jupyter中的数据帧,以下是使用Pyqt5的完整,最小的示例。
%gui qt5
from PyQt5.QtWidgets import QWidget,QScrollArea, QTableWidget, QVBoxLayout,QTableWidgetItem
import pandas as pd
win = QWidget()
scroll = QScrollArea()
layout = QVBoxLayout()
table = QTableWidget()
scroll.setWidget(table)
layout.addWidget(table)
win.setLayout(layout)
df = pd.DataFrame({"a" : [4 ,5, 6],"b" : [7, 8, 9],"c" : [10, 11, 12]},index = [1, 2, 3])
table.setColumnCount(len(df.columns))
table.setRowCount(len(df.index))
for i in range(len(df.index)):
for j in range(len(df.columns)):
table.setItem(i,j,QTableWidgetItem(str(df.iloc[i, j])))
win.show()
我一直在为你可能觉得有用的pandas DataFrame开发PyQt GUI。它包括复制,过滤和排序。
我强烈建议你使用QTableView而不是QTableWidget。 QTableView基于模型视图编程。
这些小部件可以通过两种不同的方式访问其数据。传统方式涉及小部件,其中包括用于存储数据的内部容器。这种方法非常直观,但是,在许多非平凡的应用程序中,它会导致数据同步问题。第二种方法是模型/视图编程,其中小部件不维护内部数据容器
我为pandas dataframe写了一个模型。
# -*- coding: utf-8 -*-
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5 import QtGui
import matplotlib.pyplot as plt
class PandasModel(QtCore.QAbstractTableModel):
"""
Class to populate a table view with a pandas dataframe
"""
def __init__(self, data, parent=None):
QtCore.QAbstractTableModel.__init__(self, parent)
self._data = data
def rowCount(self, parent=None):
return len(self._data.values)
def columnCount(self, parent=None):
return self._data.columns.size
def data(self, index, role=QtCore.Qt.DisplayRole):
if index.isValid():
if role == QtCore.Qt.DisplayRole:
if(index.column() != 0):
return str('%.2f'%self._data.values[index.row()][index.column()])
else:
return str(self._data.values[index.row()][index.column()])
return None
def headerData(self, section, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self._data.columns[section]
elif orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole:
return str(self._data.index[section])
return None
def flags(self, index):
flags = super(self.__class__,self).flags(index)
flags |= QtCore.Qt.ItemIsSelectable
flags |= QtCore.Qt.ItemIsEnabled
return flags
if __name__=='__main__':
import pandas as pd
import numpy as np
df = pd.DataFrame()
df['Field1']=np.arange(0,10,.5)
df['Field2']=np.arange(0,10,.5)
app = QtWidgets.QApplication([])
table = QtWidgets.QTableView()
mymodel = PandasModel(df)
table.setModel(mymodel)
table.show()
app.exec_()
您可以根据需要轻松更改模型以进行编辑或显示元素。有关更多信息,请参阅modelview
我在这里测试了许多建议,但似乎没有一个能够轻松运行或安装,特别是对于Python 3,但现在我已经编写了一个基本上完成了我想要的功能。需要将这些数据帧全屏显示,并且有时可滚动。
所以在使用Libreoffice Calc的Linux环境中,灵感来自Unix和Linux StackExchange的this answer,这是你在Python 3中可以做的:
import pandas as pd
import os
def viewDF(*dfs):
filelist = ""
for c, df in enumerate(dfs):
filename = 'tmp_df' + str(c) + '.csv'
odsfile = 'tmp_df' + str(c) + '.ods'
df.to_csv(filename)
os.system("soffice --headless --convert-to ods {}".format(filename))
filelist += odsfile + " "
os.system("soffice --view {}".format(filelist))
os.system("rm {}".format('tmp_df*'))
像这样使用它:
viewDF(df1, df2, df3)
我在那里学到了一些东西,即Python 3替换语法{}".format
打开的文件是只读的,无论如何它们都是后来被删除的文件,所以它实际上是数据帧的GUI。它会为你给它的每个数据帧生成Libreoffice Calc的多个实例,你可以在不同的屏幕上查看全屏,然后一旦你关闭Calc,它就会自动清理。
数据框的to_clipboard()方法可用于快速复制,然后将数据框粘贴到电子表格中:
df.to_clipboard()
我使用ipython笔记本来驱动熊猫 - 笔记本提供了一种很好的清洁方式,可以逐步构建和与pandas数据结构交互,包括HTML-ized数据帧显示:http://ipython.org/notebook.html
我自己不是熊猫用户,但快速搜索“pandas gui”会出现Pandas项目的GSOC 2012 proposal:
目前,与这些对象交互的唯一方法是通过API。该项目建议添加一个简单的Qt或Tk GUI,用于查看和操作这些对象。
因此,没有GUI,但如果您使用Qt或Tk编写一个GUI,项目可能会对您的代码感兴趣。
你可以使用GitHub Atom和Hydrogen插件。在Mac中,您可以使用Cmd + Shift键逐行执行。即使您只能选择变量并查看内部。 DataFrames很好地显示,你甚至可以复制。我写了一篇博客来展示配置它们的方法。 http://ojitha.blogspot.com.au/2016/08/atom-as-spark-editor.html
我也一直在寻找非常简单的gui。我很惊讶,没有人提到gtabview
。它易于安装(pip3安装gtabview),并且它可以非常快速地加载数据。如果您不使用spyder或Pycharm,我建议使用gtabview。
Pandas 0.13提供了一个实验性功能:
PySide支持qtpandas DataFrameModel
和DataFrameWidget
见https://github.com/pydata/pandas/blob/master/doc/source/faq.rst
您可以使用添加此功能
from pandas.sandbox.qtpandas import DataFrameModel, DataFrameWidget
您可以使用to_html()数据框方法将数据框转换为html并在浏览器中显示它。假设您有一个名为df的数据帧,这是一个示例。您应该检查文档以查看to_html()方法中可用的其他选项。
# Format floating point numbers with 2 decimal places.
data_table = df.to_html(float_format=lambda x: '%6.2f' % x,
classes="table display")
# The to_html() method forces a html table border of 1 pixel.
# I use 0 in my table so I change the html, since there is no
# border argument in the to_html() method.
data_table = data_table.replace('border="1"','border="0"')
# I alson like to display blanks instead on nan.
data_table = data_table.replace('nan', '')
如果你想让表格格式化和可滚动,那么你可以使用jQuery www.datatables.net的datatables插件。这是我用来显示x和y directiions中滚动的表格的javascript。
$('.table').dataTable({
"bPaginate": true,
"bLengthChange": true,
"bSort": false,
"bStateSave": true,
"sScrollY": 900,
"sScrollX": 1000,
"aLengthMenu": [[50, 100, 250, 500, 1000, -1], [50, 100, 250, 500, 1000, "All"]],
"iDisplayLength": 100,
});
除了所有有价值的答案之外,我想提一下Spyder IDE(https://github.com/spyder-ide)有这个功能,你可以在下面的我的打印屏幕中看到:
这只是一个客观事实而不是任何IDE的广告:)我不想引发对这个问题的任何争论。
有python2.7的tkintertable和python3的pandastable。
我发现最好的解决方案是使用qgrid
(参见here,也在pandas docs中提到)。你可以安装
pip install qgrid
然后你需要在IPython
笔记本上进一步安装(只需一次)
qgrid.nbinstall()
之后,它就像拿你的pandas
df
和跑步一样容易
qgrid.show_grid(df)
另一个好处是它也在nbviewer
呈现。在行动here看到它
似乎没有简单的解决方案。因此,下面是在Excel中打开数据框的一个小功能。它可能不是生产质量代码,但它适用于我!
def open_in_excel(df, index=True, excel_path="excel.exe", tmp_path='.'):
"""Open dataframe df in excel.
excel_path - path to your copy of excel
index=True - export the index of the dataframe as the first columns
tmp_path - directory to save the file in
This creates a temporary file name, exports the dataframe to a csv of that file name,
and then tells excel to open the file (in read only mode). (It uses df.to_csv instead
of to_excel because if you don't have excel, you still get the csv.)
Note - this does NOT delete the file when you exit.
"""
f=tempfile.NamedTemporaryFile(delete=False, dir=tmp_path, suffix='.csv', prefix='tmp_')
tmp_name=f.name
f.close()
df.to_csv(tmp_name, index=index)
cmd=[excel_path, '/r', '/e', tmp_name]
try:
ret_val=subprocess.Popen(cmd).pid
except:
print "open_in_excel(): failed to open excel"
print "filename = ", tmp_name
print "command line = ", cmd
print "Unexpected error:", sys.exc_info()[0]
return