【问题标题】:Pandas retrieve data with a specific order FASTPandas 以特定顺序快速检索数据
【发布时间】:2019-04-17 03:33:53
【问题描述】:

我想按 ID 列值的特定顺序一次获取多个条目。为了让事情变得更复杂,作为输入,我有 ID1 和 ID2 的行,并且对于每一行,ID1 或 ID2 都在表中,但不是两者都在。

ID 都是唯一的。

import pandas as pd
import numpy as np

print('Generating table and matchTable...')

N = 10000
# General unique IDs list to draw from
ids = np.random.choice(a=list(range(N*100)), replace=False, size=N*10)

# First N ids go into MAIN_IDS
mainIDs = ids[:N]
data = np.random.randint(low=0, high=25, size=N)

table = pd.DataFrame({'MAIN_IDS': mainIDs, 'DATA':data})

# These ids exist in the table as MAIN_IDS
tableIdsList = np.random.choice(mainIDs, replace=False, size=int(N/10))
notInTableIdsList = ids[N:N+int(N/10)]

idsA = np.zeros(shape=(int(N/10)), dtype=np.int)
idsB = np.zeros(shape=(int(N/10)), dtype=np.int)
for i in range(len(idsA)):
    if np.random.random()>0.4:
        idsA[i] = tableIdsList[i]
        idsB[i] = notInTableIdsList[i]
    else:
        idsA[i] = notInTableIdsList[i]
        idsB[i] = tableIdsList[i]

matchTable = pd.DataFrame({'ID1': idsA, 'ID2':idsB})
print('   Done!')

print('Generating the correct result...')
correctResult = []
for i in range(len(tableIdsList)):
    correctResult.append(data[np.where(mainIDs==tableIdsList[i])[0][0]])
correctResult = np.array(correctResult)
print('   Done!')

我想获取 DATA,其中 MAIN_ID==ID1 或 ID2,但按 matchTable 的顺序。

【问题讨论】:

  • 你在匹配表中有两列,应该先出现哪一列?
  • 没关系,表中只有两个列值(ID1 或 ID2)之一(作为 MAIN_IDS)。存在哪一个因行而异。
  • 例如,id1 = [1,2] id2 =[3,4],那么你要过滤掉[1,2,3,4]?
  • 它看起来像:for each row either ID1 or ID2 is in the table but not both 会起作用。
  • @Wen-Ben 我明白你的意思,不,它必须按行的顺序排列。因此,如果 id1=[1,2] 和 id2 =[3,4] 但 [1,4] 存在于 MAIN_IDS 中,则 [1,4] 是过滤器。

标签: python pandas


【解决方案1】:

首先通过 Id from table 过滤您的匹配表,然后我们使用 reindex

idx=matchTable.where(matchTable.isin(table.MAIN_IDS.tolist())).stack()

table=table.set_index('MAIN_IDS').reindex(idx).reset_index()

【讨论】:

  • 当我做 matchTable.ID1.isin(table.MAIN_IDS).head(5) 时找到了 ID,但是当我做 matchTable.isin(table.MAIN_IDS).head(5) 时错误。
  • @user1581390 matchTable.isin(table.MAIN_IDS.tolist()).
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-30
  • 2020-08-04
  • 1970-01-01
  • 2011-02-09
  • 1970-01-01
相关资源
最近更新 更多