programing

Python / Pandas-데이터 프레임 또는 매트릭스를보기위한 GUI

firstcheck 2021. 1. 18. 08:05
반응형

Python / Pandas-데이터 프레임 또는 매트릭스를보기위한 GUI


저는 Pandas 패키지를 사용하고 있으며 기본적으로 레이블이 지정된 행렬 인 DataFrame 개체를 만듭니다. 종종 긴 문자열 필드가있는 열이나 많은 열이있는 데이터 프레임이 있으므로 간단한 인쇄 명령이 제대로 작동하지 않습니다. 몇 가지 텍스트 출력 함수를 작성했지만 훌륭하지 않습니다.

내가 정말 좋아하는 것은 데이터 프레임 / 행렬 / 테이블과 상호 작용할 수있는 간단한 GUI입니다. SQL 도구에서 찾을 수있는 것과 같습니다. 기본적으로 데이터보기와 같은 읽기 전용 스프레드 시트가있는 창입니다. 긴 테이블 등을 통해 열, 페이지 위아래로 확장 할 수 있습니다.

나는 이와 같은 것이 존재한다고 의심하지만 잘못된 용어로 인터넷 검색을해야합니다. 판다 전용이라면 좋겠지 만 매트릭스 수용 도구를 사용할 수 있다고 생각합니다. (BTW-저는 Windows에 있습니다.)

포인터가 있습니까?

또는 반대로 누군가가이 공간을 잘 알고 있고 이것이 존재하지 않는다는 것을 알고 있다면 간단한 GUI 프레임 워크 / 위젯이 있는지에 대한 제안이 있습니까? (하지만 내 요구가 제한되어 있기 때문에 큰 GUI 프레임 워크를 배우고이 한 조각에 대해 많은 코딩을해야하는 것을 꺼려합니다.)


나는 QTableWidgetPyQt에서 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에서 데이터 프레임을 볼 수있는 많은 옵션이 있습니다.

  1. 다른 사람들이 지적했듯이 Spyder와 같은 Python IDE에는 데이터 프레임 뷰어가 함께 제공됩니다.
  2. qgrid 는 노트북 내에서 데이터 프레임을 렌더링하는 jupyter 노트북 위젯의 또 다른 옵션입니다.

누군가가 여전히 Jupyter 내에서 데이터 프레임을보기 위해 간단한 GUI를 코딩하고 싶다면 다음은 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()

여기에 이미지 설명 입력


2019 업데이트 : 현재 후속 작업중tabloo 작업 입니다.


다른 GUI에 완전히 만족하지 않았기 때문에 직접 만든 GUI 를 Github에서 유지 관리 하고 있습니다. 예:

여기에 이미지 설명 입력

기본 테이블 + 플롯 기능 외에도 데이터를 필터링하는 특정 방법이 필요했습니다.

  • 콤보 상자에서 필터링 할 열 선택
  • 임의의 Python 코드를 사용하여 해당 열을 필터링하려면 "밑줄 표현식"을 작성하십시오. 예 : _ > 0양수 값만 필터링하거나 (_ >= date(2016, 1, 1)) & (_ <= date(2016, 1, 31))datetime 열과 같은 더 복잡한 표현식을 필터링합니다 .

질문은 2012 년에 게시되었으며 다른 답변은 적용하기에 너무 오래되었을 수 있습니다.

2016 년의 대답은 Pycharm을 사용해야하며 DataFrame뷰어 와 함께 제공된다는 것 입니다.

여기에 이미지 설명 입력

여기에 이미지 설명 입력


Pandas 0.13은 실험적 기능으로 제공합니다.

qtpandas에 대한 PySide 지원 DataFrameModelDataFrameWidget

참조 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 방향으로 스크롤되는 테이블을 표시하는 데 사용하는 자바 스크립트입니다.

$('.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에 대한 광고가 아닙니다. :)이 질문에 대해 어떤 논쟁도 일으키고 싶지 않습니다.


있다 tkintertable python2.7 및 pandastable python3합니다.


내가 찾은 가장 좋은 해결책은 사용하는 것입니다 qgrid( 여기를 참조 하고 pandas 문서 에서도 언급했습니다 ). 다음 방법으로 설치할 수 있습니다.

pip install qgrid

그런 다음 IPython노트북 에 추가로 (한 번만) 설치해야합니다.

qgrid.nbinstall()

그 후, 그것은 당신을 가지고 pandas df뛰는 것만 큼 ​​쉽습니다

qgrid.show_grid(df)

또 다른 좋은 점은 그것이 렌더링된다는 것입니다 nbviewer. 여기 에서 실제로 확인 하세요


쉬운 해결책이없는 것 같습니다. 따라서 아래는 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

나는 pandas DataFrame에 대한 PyQt GUI에서 작업하고 있습니다. 여기에는 복사, 필터링 및 정렬이 포함됩니다.

https://gist.github.com/jsexauer/f2bb0cc876828b54f2ed


QTableWidget이 아닌 QTableView 를 사용하는 것이 좋습니다 . 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_()

You can easily change the model to edit or show the elements nicely based on your need. For more information refer to modelview

여기에 이미지 설명 입력


I tested many of the suggestions here and none of them seem to run or install easily, especially for Python 3, but now I've written a function which is basically accomplishing what I wanted. Need to have these dataframes full-screen, and scrollable sometimes.

So in a Linux environment using Libreoffice Calc, inspired by this answer from Unix and Linux StackExchange, here's what you can do in 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*'))

Use it like this:

viewDF(df1, df2, df3)

I learned something there, which is the Python 3 substitution syntax {}".format The opened files are read-only, in any case they are files which are later deleted, so it's effectively a GUI for dataframes. It will spawn multiple instances of Libreoffice Calc for each dataframe you give it, which you can view fullscreen on separate screens, and then once you close Calc, it cleans up after itself.


The dataframe's to_clipboard() method can be used to quickly copy, and then paste the dataframe into a spreadsheet:

df.to_clipboard()

I use ipython notebooks to drive pandas -- notebooks provide a nice clean way of incrementally building and interacting with pandas data structures, including HTML-ized display of dataframes: http://ipython.org/notebook.html


I'm not a Pandas user myself, but a quick search for "pandas gui" turns up the Pandas project's GSOC 2012 proposal:

Currently the only way to interact with these objects is through the API. This project proposes to add a simple Qt or Tk GUI with which to view and manipulate these objects.

So, there's no GUI, but if you'd write one using Qt or Tk, the project might be interested in your code.


You can use GitHub Atom with Hydrogen plugin. In Mac you can use Cmd+Shift keys to execute line by line. Even you can select only the variable and see inside. DataFrames are nicely display and you can even copy. I wrote a blog to show the way to configure these. http://ojitha.blogspot.com.au/2016/08/atom-as-spark-editor.html


나는 또한 매우 간단한 GUI를 검색했습니다. 아무도 언급하지 않은 것에 놀랐습니다 gtabview. 설치가 쉽고 (pip3 install gtabview), 데이터로드 속도가 엄청나게 빠릅니다. spyder 또는 Pycharm을 사용하지 않는 경우 gtabview를 사용하는 것이 좋습니다.

참조 URL : https://stackoverflow.com/questions/10636024/python-pandas-gui-for-viewing-a-dataframe-or-matrix

반응형