TransWikia.com

Проблемы с выводом данных DataFrame в QtabelWidget!

Stack Overflow на русском Asked by iskakdar on January 27, 2021

Когда я пытаюсь вывести датафрейм, предварительно удалив NaN, таблица формируется но ячейки пустые!

    train_data = pd.read_csv('contest_train_df.csv', parse_dates=['Date', 'Start_date']).dropna()
    train_data = train_data.head()
    print(train_data)
    self.ui.tableWidget.setColumnCount(len(train_data.columns))
    self.ui.tableWidget.setRowCount(len(train_data.index))
    self.ui.tableWidget.setHorizontalHeaderLabels(list(train_data.columns.values))

    for i, row in train_data.iterrows():
        
        for j in range(self.ui.tableWidget.columnCount()):
            self.ui.tableWidget.setItem(i, j, QTableWidgetItem(str(row[j])))

введите сюда описание изображения

Но когда пробую без удаления пропусков данных все работает нормально!

    train_data = pd.read_csv('contest_train_df.csv', parse_dates=['Date', 'Start_date'])
    train_data = train_data.head()
    print(train_data)
    self.ui.tableWidget.setColumnCount(len(train_data.columns))
    self.ui.tableWidget.setRowCount(len(train_data.index))
    self.ui.tableWidget.setHorizontalHeaderLabels(list(train_data.columns.values))

    for i, row in train_data.iterrows():
        
        for j in range(self.ui.tableWidget.columnCount()):
            self.ui.tableWidget.setItem(i, j, QTableWidgetItem(str(row[j])))

введите сюда описание изображения

После удаления строк с пропусками данных в датафрейме еще данные остаются, то есть не вcе строки содержат NaN!

from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import pandas as pd
from PyQt5.QtWidgets import *
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1063, 750)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton_1 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_1.setGeometry(QtCore.QRect(810, 40, 181, 51))
        self.pushButton_1.setObjectName("pushButton_1")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(810, 120, 181, 51))
        self.pushButton_2.setObjectName("pushButton_2")
        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(30, 30, 671, 661))
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(0)
        self.tableWidget.setRowCount(0)
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(810, 190, 181, 51))
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_4.setGeometry(QtCore.QRect(810, 270, 181, 51))
        self.pushButton_4.setObjectName("pushButton_4")
        self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_5.setGeometry(QtCore.QRect(810, 350, 181, 51))
        self.pushButton_5.setObjectName("pushButton_5")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1063, 26))
        self.menubar.setObjectName("menubar")
        self.menu = QtWidgets.QMenu(self.menubar)
        self.menu.setObjectName("menu")
        self.menu_2 = QtWidgets.QMenu(self.menubar)
        self.menu_2.setObjectName("menu_2")
        self.menu_3 = QtWidgets.QMenu(self.menubar)
        self.menu_3.setObjectName("menu_3")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.action = QtWidgets.QAction(MainWindow)
        self.action.setObjectName("action")
        self.action_2 = QtWidgets.QAction(MainWindow)
        self.action_2.setObjectName("action_2")
        self.action_3 = QtWidgets.QAction(MainWindow)
        self.action_3.setObjectName("action_3")
        self.action_4 = QtWidgets.QAction(MainWindow)
        self.action_4.setObjectName("action_4")
        self.action_5 = QtWidgets.QAction(MainWindow)
        self.action_5.setObjectName("action_5")
        self.menu.addAction(self.action)
        self.menu.addAction(self.action_2)
        self.menu.addAction(self.action_3)
        self.menu_2.addAction(self.action_4)
        self.menu_3.addAction(self.action_5)
        self.menubar.addAction(self.menu.menuAction())
        self.menubar.addAction(self.menu_2.menuAction())
        self.menubar.addAction(self.menu_3.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton_1.setText(_translate("MainWindow", "Загрузить данные"))
        self.pushButton_2.setText(_translate("MainWindow", "Обработать данные"))
        self.pushButton_3.setText(_translate("MainWindow", "Обучить модель"))
        self.pushButton_4.setText(_translate("MainWindow", "Спрогнозировать"))
        self.pushButton_5.setText(_translate("MainWindow", "Сохранить"))
        self.menu.setTitle(_translate("MainWindow", "Файл"))
        self.menu_2.setTitle(_translate("MainWindow", "Правка"))
        self.menu_3.setTitle(_translate("MainWindow", "Справка"))
        self.action.setText(_translate("MainWindow", "Печать"))
        self.action_2.setText(_translate("MainWindow", "Сохранить"))
        self.action_3.setText(_translate("MainWindow", "Выйти"))
        self.action_4.setText(_translate("MainWindow", "Очистить окно"))
        self.action_5.setText(_translate("MainWindow", "О программе"))


class Main_Window(QtWidgets.QMainWindow):

    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton_1.clicked.connect(self.data_load)

    def data_load(self):
        fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Open File", "", "CSV Files (*.csv)");
        train_data = pd.read_csv(fileName, parse_dates=['Date', 'Start_date']).dropna()
        train_data = train_data.head()
        print(train_data)
        self.ui.tableWidget.setColumnCount(len(train_data.columns))
        self.ui.tableWidget.setRowCount(len(train_data.index))
        self.ui.tableWidget.setHorizontalHeaderLabels(list(train_data.columns.values))

        for i, row in train_data.iterrows():
            # Добавление строки
            for j in range(self.ui.tableWidget.columnCount()):
                self.ui.tableWidget.setItem(i, j, QTableWidgetItem(str(row[j])))


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    myapp = Main_Window()
    myapp.show()
    sys.exit(app.exec_())

One Answer

Из документации)

DataFrame.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)[source] Remove missing values.

See the User Guide for more on which values are considered missing, and how to work with missing data.

Parameters axis{0 or ‘index’, 1 or ‘columns’}, default 0 Determine if rows or columns which contain missing values are removed.

0, or ‘index’ : Drop rows which contain missing values.

1, or ‘columns’ : Drop columns which contain missing value.

Changed in version 1.0.0: Pass tuple or list to drop on multiple axes. Only a single axis is allowed.

how{‘any’, ‘all’}, default ‘any’ Determine if row or column is removed from DataFrame, when we have at least one NA or all NA.

‘any’ : If any NA values are present, drop that row or column.

‘all’ : If all values are NA, drop that row or column.

Внимательнее надо читать документацию)

смотрим:

train_data = pd.read_csv('contest_train_df.csv', parse_dates=['Date', 'Start_date']).dropna()

аналогично вызову:

DataFrame.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)
axis=0: Determine if rows or columns which contain missing values are removed.
how='any' : If any NA values are present, drop that row or column.

как только в строке или в колонке появляется NA , она удалятся. Удаление происходит не по самим ячейкам, а по строкам или колонкам в целом.

Answered by Valvea on January 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP