当索引值包含在单独的 numpy 数组中时访问 Pandas 数据帧值

Nic*_*gel 0 python numpy pandas

我有一个array超过 200 万int的numpy :

a = np.array([324, 986, 574 ... 986, 1232, 3943])
Run Code Online (Sandbox Code Playgroud)

中的每个元素a对应于df形状为 (1324, 4)的数据帧中的一个索引值:

index A     B C D
0     'foo' 2 3 2
1     'bar' 2 4 8
...
1323  'foo' 2 5 8
Run Code Online (Sandbox Code Playgroud)

我正在尝试访问df.A使用列表理解的值:

l = [df.A.loc[i] for i in a]
Run Code Online (Sandbox Code Playgroud)

但这需要很长时间才能运行。有没有更快的选择;也许我需要加入?谢谢你。

Psi*_*dom 6

如果 in 中的值a对应于数据框索引中的值,您应该可以使用.loc[a]; 如果中的值是a指职位,那么您需要.iloc[a];如果您需要 numpy 数组作为结果,如@Scott 所评论的,请使用df.A.loc[a].values

df.A.loc[a]
Run Code Online (Sandbox Code Playgroud)

示例

df = pd.DataFrame({
        "A": ["a", "c", "b", "d"]
    })

a = np.array([0,3,2,2,1,1,0])

df.A.loc[a]
#0    a
#3    d
#2    b
#2    b
#1    c
#1    c
#0    a
#Name: A, dtype: object

df.A.loc[a].values
# array(['a', 'd', 'b', 'b', 'c', 'c', 'a'], dtype=object)
Run Code Online (Sandbox Code Playgroud)

  • l = df.A[a].values +1 (2认同)