python - Pandas:给定不均匀空间的索引列表对数据帧进行重新采样

标签 python pandas dataframe

给定一个数据帧 df: pd.Dataframedf.index 索引的子集 selected_indexes 我如何使用 df 重新采样code>max 运算符应用于每个区间 selected_indexes[i], selected_indexes[i+1] ?

例如,给定一个数据框:

   col
0    5
1    0
2    3
3    3
4    7
5    9
6    3
7    5
8    2
9    4

选择索引“selected_indexes = [0, 5, 6, 9]”,并在每个间隔之间的 col 列上应用最大值(假设我们保留终点并排除起始点)点),我们应该得到:

   col
0    5
5    9
6    3
9    5

例如,第 9 行是由第 7, 8, 9 行\in (6, 9] 中的 max(5, 2, 4) 组成的.

最佳答案

新的解释

selected_indexes = [0, 5, 6, 9]
group = (df.index.to_series().shift() # make groups
           .isin(selected_indexes)    # based on
           .cumsum()                  # previous indices
        )

# get max per group
out = df.groupby(group).max().set_axis(selected_indexes)

# or for many aggregations (see comments):
out = (df.groupby(group).agg({'col1': 'max', 'col2': 'min'})
         .set_axis(selected_indexes)
       )

输出:

   col
0    5
5    9
6    3
9    5

之前对问题的解释

您可能需要 rolling.max ,不重新采样:

out = df.loc[selected_indexes].rolling(3, center=True).max()

或者,如果您希望将 ±1 应用到选择之前的数据:

out = df.rolling(3, center=True).max().loc[selected_indexes]

示例:

np.random.seed(0)
df = pd.DataFrame({'col': np.random.randint(0, 10, 10)})
selected_indexes = [1, 2, 3, 5, 6, 8, 9]

print(df)

   col
0    5
1    0
2    3
3    3
4    7
5    9
6    3
7    5
8    2
9    4


out = df.loc[selected_indexes].rolling(3, center=True).max()
print(out)

   col
1  NaN
2  3.0
3  9.0
5  9.0
6  9.0
8  4.0
9  NaN

out2 = df.rolling(3, center=True).max().loc[selected_indexes]
print(out2)

   col
1  5.0
2  3.0
3  7.0
5  9.0
6  9.0
8  5.0
9  NaN

关于python - Pandas:给定不均匀空间的索引列表对数据帧进行重新采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74689284/

相关文章:

python - 2 groupby 在同一个数据框中,可能吗?

python - 向 Pandas 索引添加一个值

scala - 使用 Spark DataFrame 获取列上的不同值

python - 如何摆脱 GPT-2 警告消息?

python - Pandas 两行具有相同的索引,如何更改它们

python - 如何使用 python 找到最常见的集合?

python - 使用索引为 pandas DataFrame 中的特定单元格设置值

python - 如何为 Inkscape 扩展制作进度条?

python - 在 C++ 中嵌入 Cython

python - 为 python 安装 zeromq 时遇到问题