Python: использование панд для соединения одного массива с другим - PullRequest
0 голосов
/ 22 мая 2018

Как мне использовать pandas для создания объединенного результата aoiFeatures и allFeaturesReadings, который приводит к следующему:

183  0.03
845  0.03
853  0.01

С учетом следующего начального кода и данных:

import numpy
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]

allFeaturesReadings = zip(allFeatures, allReadings)
#
# Use pandas to create Series and Join here?
#
sAllFeaturesReadings = pd.Series(dict(allFeaturesReadings))
sAOIFeatures = pd.Series(numpy.ma.filled(aoiFeatures))
sIndexedAOIFeatures = sAOIFeatures.reindex(numpy.ma.filled(aoiFeatures))
result = pd.concat([sIndexedAOIFeatures,sAllFeaturesReadings], axis=1, join='inner')

Ответы [ 2 ]

0 голосов
/ 22 мая 2018

Вы можете использовать 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
0 голосов
/ 22 мая 2018

Без необходимости заархивировать вы можете сделать:

df = pd.DataFrame(data={"allFeatures":allFeatures, "allReadings":allReadings})
df[df["allFeatures"].isin(aoiFeatures)]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...