【问题标题】:Python: which is a fast way to find index in pandas dataframe?Python:在 pandas 数据框中找到索引的快速方法是什么?
【发布时间】:2016-01-30 22:52:41
【问题描述】:

我有一个如下的数据框

df = 
    a   ID1         ID2         Proximity
0   0   900000498   NaN         0.000000
1   1   900000498   900004585   3.900000
2   2   900000498   900005562   3.900000
3   3   900000498   900008613   0.000000
4   4   900000498   900012333   0.000000
5   5   900000498   900019524   3.900000
6   6   900000498   900019877   0.000000
7   7   900000498   900020141   3.900000
8   8   900000498   900022133   3.900000
9   9   900000498   900022919   0.000000

我想为给定的一对ID1-ID2 找到相应的Proximity 值。 例如给定输入 [900000498, 900022133] 我想作为输出 3.900000

【问题讨论】:

    标签: python pandas find dataframe


    【解决方案1】:

    如果这是一个常见操作,那么我会为这些列设置索引,然后您可以使用 loc 执行索引查找并传递一个 col 值的元组:

    In [60]:
    df1 = df.set_index(['ID1','ID2'])
    
    In [61]:
    %timeit df1.loc[(900000498,900022133), 'Proximity']
    %timeit df.loc[(df['ID1']==900000498)&(df['ID2']==900022133), 'Proximity']
    1000 loops, best of 3: 565 µs per loop
    100 loops, best of 3: 1.69 ms per loop
    

    您可以看到,一旦 cols 形成索引,则查找比过滤操作快 3 倍。

    输出几乎相同:

    In [63]:
    print(df1.loc[(900000498,900022133), 'Proximity'])
    print(df.loc[(df['ID1']==900000498)&(df['ID2']==900022133), 'Proximity'])
    
    3.9
    8    3.9
    Name: Proximity, dtype: float64
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      相关资源
      最近更新 更多