Код: Выделить всё
import pandas as pd
series_source = pd.Series([1, 2, 3, 4], dtype=int)
normal_index = pd.Series([True, False, True, True], dtype=bool)
big_index = pd.Series([True, False, True, True, False, True], dtype=bool)
# Both indexes give back: pd.Series([1, 2, 3, 4], dtype=int)
# no warnings are raised!
assert (series_source[normal_index] == series_source[big_index]).all()
df_source = pd.DataFrame(
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
)
# no warning - works as expected: grabs rows 0, 2, and 3
df_normal_result = df_source[normal_index]
# UserWarning: Boolean Series key will be reindexed to match DataFrame index.
# (but still runs)
df_big_result = df_source[big_index]
# passes - they are equivalent
assert df_normal_result.equals(df_big_result)
print("Complete")
(Сравните это с индексацией df_source, где выдается явное предупреждение о том, что big_index необходимо переиндексировать, чтобы операция работала.)
В документации по индексированию утверждается, что:
Использование логического вектора для индексации серии работает точно так же, как в NumPy
ndarray
Однако, если я сделать
Код: Выделить всё
import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = np.array([True, False, True, True, False])
c = np.array([True, False, True, True, False, True, True])
# returns an ndarray of [1,3, 4] as expected
print(a[b])
# raises IndexError: boolean index did not match indexed array along axis 0;
# size of axis is 5 but size of corresponding boolean axis is 7
print(a[c])
(Мои версии — pandas==2.2.2 и numpy==2.0.0.)
Подробнее здесь: https://stackoverflow.com/questions/786 ... eries-that