Чтобы выбрать строки, значение столбца которых равно скаляру, some_value
, используйте ==
:
df.loc[df['column_name'] == some_value]
Чтобы выбрать строки, значение столбца которых в итерабельном, some_values
, используйте isin
:
df.loc[df['column_name'].isin(some_values)]
Объединить несколько условий с &
:
df.loc[(df['column_name'] == some_value) & df['other_column'].isin(some_values)]
Выбрать строки, значение столбца не равно some_value
, используйте !=
:
df.loc[df['column_name'] != some_value]
isin
возвращает булевскую серию, поэтому для выбора строк, значение которых не в some_values
, отмените булевскую серию используя ~
:
df.loc[~df['column_name'].isin(some_values)]
Например,
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
# A B C D
# 0 foo one 0 0
# 1 bar one 1 2
# 2 foo two 2 4
# 3 bar three 3 6
# 4 foo two 4 8
# 5 bar two 5 10
# 6 foo one 6 12
# 7 foo three 7 14
print(df.loc[df['A'] == 'foo'])
дает
A B C D
0 foo one 0 0
2 foo two 2 4
4 foo two 4 8
6 foo one 6 12
7 foo three 7 14
Если у вас несколько значений вы хотите включить, поместить их в список (или, в более общем плане, любой итерабельный) и использовать isin
:
print(df.loc[df['B'].isin(['one','three'])])
дает
A B C D
0 foo one 0 0
1 bar one 1 2
3 bar three 3 6
6 foo one 6 12
7 foo three 7 14
Примечание, однако, если вы хотите сделать это много раз, более эффективно сначала сделать индекс, а затем использовать df.loc
:
df = df.set_index(['B'])
print(df.loc['one'])
дает
A C D
B
one foo 0 0
one bar 1 2
one foo 6 12
или, чтобы включить несколько значений из использования индекса df.index.isin
:
df.loc[df.index.isin(['one','two'])]
дает
A C D
B
one foo 0 0
one bar 1 2
two foo 2 4
two foo 4 8
two bar 5 10
one foo 6 12
Вы слишком усложняете задачу проверки того, что должен делать делегат, вместо использования создания логики пост-проверки с помощью QTableWidgetItems.
import random
from PyQt4 import QtCore, QtGui
class LimistDelegate(QtGui.QStyledItemDelegate):
def createEditor(self, parent, option, index):
editor = super(LimistDelegate, self).createEditor(parent, option, index)
if index.column() in (1, 2):
editor = QtGui.QSpinBox(parent)
return editor
def setEditorData(self, editor, index):
if index.column() in (1, 2):
m = 0 if index.column() == 1 else index.sibling(index.row(), 1).data()
M = index.sibling(index.row(), 2).data() if index.column() == 1 else 360
if hasattr(m, 'toPyObject'):
m = m.toPyObject()
if hasattr(M, 'toPyObject'):
M = M.toPyObject()
editor.setMinimum(m)
editor.setMaximum(M)
super(LimistDelegate, self).setEditorData(editor, index)
def create_table():
nrows, ncols = random.randrange(3, 6), 3
table = QtGui.QTableWidget(nrows, ncols)
for r in range(nrows):
text = "description {}".format(r)
a = random.randrange(0, 180)
b = random.randrange(a, 360)
for c, val in enumerate([text, a, b]):
it = QtGui.QTableWidgetItem()
it.setData(QtCore.Qt.DisplayRole, val) # set data on item
table.setItem(r, c, it)
return table
class Widget(QtGui.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
vlay = QtGui.QVBoxLayout(self)
for _ in range(4):
table = create_table()
delegate = LimistDelegate(table) # create delegate
table.setItemDelegate(delegate) # set delegate
vlay.addWidget(table)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())