【发布时间】:2014-11-10 22:21:34
【问题描述】:
假设我有一个 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
有没有办法获得:
x.loc[y]
返回:
[(b, h), (c,f), (d, e), (d,f)]
或类似的?显然,我可以做到:
postup = []
for i in x.index:
for j in x.columns:
if x.loc[i, j] > 0:
postup.append((i, j))
但我想可能/已经实现了更好的东西。在 matlab 中,函数 find 与 sub2ind 结合使用。
【问题讨论】: