假设我有一个Pandas DataFrame,我想获得格式[(index1,column1),(index2,column2)......]的元组列表,描述DataFrame中某些条件为真的所有元素的位置.例如:
x = pd.DataFrame(np.random.normal(0, 1, (4,4)), index=['a', 'b', 'c', 'd'],
columns=['e', 'f', 'g', 'h'])
x
e f g h
a -1.342571 -0.274879 -0.903354 -1.458702
b -1.521502 -1.135800 -1.147913 1.829485
c -1.199857 0.458135 -1.993701 -0.878301
d 0.485599 0.286608 -0.436289 -0.390755
y = x > 0
Run Code Online (Sandbox Code Playgroud)
有没有办法获得:
x.loc[y]
Run Code Online (Sandbox Code Playgroud)
回来:
[(b, h), (c,f), (d, e), (d,f)]
Run Code Online (Sandbox Code Playgroud)
还是一些等价的?显然,我可以这样做:
postup = []
for i in x.index:
for j in x.columns:
if x.loc[i, j] > 0:
postup.append((i, j))
Run Code Online (Sandbox Code Playgroud)
但我认为可能/已经实施的更好的东西.在matlab中,函数find与sub2ind结合起来完成工作.