Вы можете использовать isin
:
import pandas as pd
allFeatures = [101, 179, 181, 183, 185, 843, 845, 847, 849, 851, 853, 855]
allReadings = [0.03, 0.01, 0.01, 0.03, 0.03, 0.01, 0.03, 0.02, 0.07, 0.06, 0.01, 0.04]
aoiFeatures = [183, 845, 853]
df = pd.DataFrame({'features':allFeatures, 'readings':allReadings})
result = df.loc[df['features'].isin(aoiFeatures)]
print(result)
доходность
features readings
3 183 0.03
6 845 0.03
10 853 0.01
Если вы планируете часто выбирать строки на основе значений feature
, и если features
можетбыть преобразован в уникальный индекс, и если DataFrame, по крайней мере, умеренно большой (скажем, ~ 10 тыс. строк), то может быть лучше (для производительности) сделать features
индекс:
import pandas as pd
allFeatures = [101, 179, 181, 183, 185, 843, 845, 847, 849, 851, 853, 855]
allReadings = [0.03, 0.01, 0.01, 0.03, 0.03, 0.01, 0.03, 0.02, 0.07, 0.06, 0.01, 0.04]
aoiFeatures = [183, 845, 853]
df = pd.DataFrame({'readings':allReadings}, index=allFeatures)
result = df.loc[aoiFeatures]
print(result)
выход
readings
183 0.03
845 0.03
853 0.01
Вот настройка, которую я использовал для выполнения IPython% timeit тестов:
import pandas as pd
N = 10000
allFeatures = np.repeat(np.arange(N), 1)
allReadings = np.random.random(N)
aoiFeatures = np.random.choice(allFeatures, N//10, replace=False)
def using_isin():
df = pd.DataFrame({'features':allFeatures, 'readings':allReadings})
for i in range(1000):
result = df.loc[df['features'].isin(aoiFeatures)]
return result
def using_index():
df = pd.DataFrame({'readings':allReadings}, index=allFeatures)
for i in range(1000):
result = df.loc[aoiFeatures]
return result
Это показывает, что using_index
может быть немного быстрее:
In [108]: %timeit using_isin()
1 loop, best of 3: 697 ms per loop
In [109]: %timeit using_index()
1 loop, best of 3: 432 ms per loop
Обратите внимание, однако, что если allFeatures
содержит дубликаты, то сделать его индексом НЕ выгодно.Например, если вы измените настройку выше, чтобы использовать:
allFeatures = np.repeat(np.arange(N//2), 2) # repeat every value twice
, то
In [114]: %timeit using_isin()
1 loop, best of 3: 667 ms per loop
In [115]: %timeit using_index()
1 loop, best of 3: 3.47 s per loop