考虑下面的代码块(在Jupyter笔记本中开发),AssertionError由于UserWarning没有触发,因此需要引发一个代码:
%%writefile Game/tests/tests.py
import unittest
import pandas as pd
class TestGame(unittest.TestCase):
def test_getters(self):
print('Just before the critical line.')
with self.assertWarns(UserWarning):
print('Just testing...')
suite = unittest.TestLoader().loadTestsFromTestCase(TestGame)
unittest.TextTestRunner().run(suite)
Run Code Online (Sandbox Code Playgroud)
对于那些不熟悉jupyter笔记本的人,第一行只是将所有后续行导出到指定的文件中.
现在,如果我执行命令:
python3 tests.py
Run Code Online (Sandbox Code Playgroud)
从终端(我在Ubuntu 14.04上使用Python 3.5.1),我得到一个Runtime Error- 堆栈跟踪如下:
Just before the critical line:
E
======================================================================
ERROR: test_getters (__main__.TestGame)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests.py", line 8, in test_getters
with self.assertWarns(UserWarning):
File "/opt/anaconda3/lib/python3.5/unittest/case.py", line 225, in __enter__
for v in sys.modules.values():
RuntimeError: dictionary changed size during …Run Code Online (Sandbox Code Playgroud) 我希望能够使用多个级别条件(通过逻辑AND连接条件)从多索引数据帧对象中删除行。
考虑以下给出的pandas数据框对象:
import pandas as pd
df = pd.DataFrame(data = [[1,'x'],[2,'x'],[1,'y'],[2,'y']],
index=pd.MultiIndex(levels=[['A','B'],['a','b']],
labels=[[0,1,0,1],[0,1,1,0]],
names=['idx0','idx1']))
Run Code Online (Sandbox Code Playgroud)
print(df) 输出:
0 1
idx0 idx1
A a 1 x
B b 2 x
A b 1 y
B a 2 y
Run Code Online (Sandbox Code Playgroud)
我希望消除其中'idx0'=='A' 和 的行'idx1'=='a',因此最终结果是:
0 1
idx0 idx1
B b 2 x
a 2 y
A b 1 y
Run Code Online (Sandbox Code Playgroud)
在我看来,这似乎无法用该df.drop()方法完成。给出正确结果的“回旋”方式是:
df = pd.concat([df.drop(labels='A',level=0),df.drop(labels='a',level=1)])
df = df.drop_duplicates()
Run Code Online (Sandbox Code Playgroud)
但我认为必须有更好的方法...