从过滤后的 pandas 数据框中获取整数索引值
Get integer index values from filtered pandas dataframe
有 pd.DataFrame
和 DateTimeIndex
,我在应用过滤器后寻找索引整数值。
这是 df
:
import numpy as np
import pandas as pd
df = pd.DataFrame(
data=np.random.randint(low=0, high=10, size=(5, 2)),
index=pd.date_range(start="2020-12-31", periods=5)
)
df
0 1
2020-12-31 7 6
2021-01-01 2 6
2021-01-02 5 2
2021-01-03 2 3
2021-01-04 4 7
让我们应用一些过滤器:
df_selection = df.loc[pd.date_range(start="2021-01-02", periods=2), :]
df_selection
0 1
2021-01-02 9 0
2021-01-03 9 5
最后,我正在寻找过滤数据框的整数索引值。那就是我需要得到 [2, 3]
.
假设df
按索引排序:
np.searchsorted(df.index, df_selection.index)
输出:
array([2, 3])
一般来说,你可以这样做:
np.where(df.index.isin(df_selection.index))
输出:
(array([2, 3]),)
有 pd.DataFrame
和 DateTimeIndex
,我在应用过滤器后寻找索引整数值。
这是 df
:
import numpy as np
import pandas as pd
df = pd.DataFrame(
data=np.random.randint(low=0, high=10, size=(5, 2)),
index=pd.date_range(start="2020-12-31", periods=5)
)
df
0 1
2020-12-31 7 6
2021-01-01 2 6
2021-01-02 5 2
2021-01-03 2 3
2021-01-04 4 7
让我们应用一些过滤器:
df_selection = df.loc[pd.date_range(start="2021-01-02", periods=2), :]
df_selection
0 1
2021-01-02 9 0
2021-01-03 9 5
最后,我正在寻找过滤数据框的整数索引值。那就是我需要得到 [2, 3]
.
假设df
按索引排序:
np.searchsorted(df.index, df_selection.index)
输出:
array([2, 3])
一般来说,你可以这样做:
np.where(df.index.isin(df_selection.index))
输出:
(array([2, 3]),)