[英]Get indices in pandas dataframe selecting by specific column values
我有一个熊猫数据框,看起来像这样
ievt ch n_max t0
0 0 0 0.0 0.0
1 0 1 0.0 0.0
2 0 2 6.0 175.0
3 0 3 1.0 1253.0
4 0 4 0.0 0.0
... ... ... ... ...
999995 30302 29 0.0 0.0
999996 30302 30 0.0 NaN
999997 30302 31 0.0 NaN
999998 30302 32 0.0 0.0
999999 30303 0 0.0 0.0
1000000 rows × 4 columns
和列ievt
的值数组,如下所示
ievt_nbrs = array([0, 3, 7, 9, ..., 30292, 30293, 30299])
现在我想获取具有这些ievt
数字的数据帧的索引。 例如对于 ievt 编号 0,我将获得 33 个索引(因为我有 33 个通道),所以我的索引数组将从0,1,2,...,33, 33*3, 33*3+1,...
开始。 0,1,2,...,33, 33*3, 33*3+1,...
我希望很清楚我的目标是什么。 我目前为获取索引所做的是一个 for 循环,但这当然非常慢:
indices_accept = np.array([])
for i in ievt_nbrs:
indices_accept = np.append(indices_accept, df.index[df['ievt']==i])
indices_accept = indices_accept.astype('int')
如何使用熊猫索引或其他更快的方法来做到这一点?
您可以使用df["ievt"]
系列的isin
方法:
df.loc[df["ievt"].isin(ievt_nbrs), :]
如果您只需要索引,只需在结果数据帧上调用index
方法。
例子:
>>> df
ievt ch
0 0 1
1 0 2
2 0 3
3 0 4
4 0 5
5 1 1
6 1 2
7 1 3
8 1 4
9 1 5
10 2 1
11 2 2
12 2 3
13 2 4
14 2 5
>>> indices = [1, 2]
>>> df.loc[df["ievt"].isin(indices), :]
ievt ch
5 1 1
6 1 2
7 1 3
8 1 4
9 1 5
10 2 1
11 2 2
12 2 3
13 2 4
14 2 5
>>> df.loc[df["ievt"].isin(indices), :].index
Int64Index([5, 6, 7, 8, 9, 10, 11, 12, 13, 14], dtype='int64')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.