python - 根据特定的 col1 值查找 col2 值,如果不存在则使用 pandas 保持最近的值

标签 python pandas dataframe

我有一个这样的数据框:

df
col1      col2      
 1         10
 2         15
 4         12
 5         23
 6         11
 8         32
 9         12
 11        32
 2         23
 3         21
 4         12
 6         15
 9         12
 10        32

我想为 col1 的每 1、5 和 10 个值选择 col2 值。如果 col1 值不是 1、5 或 10,则保留 col1 值最接近 1,5 或 10 的 col2 值

例如,最终的 df 将如下所示:

df
col1      col2      
 1         10
 5         23
 11        32
 2         23
 6         15
 10        32

如何在不使用任何循环的情况下使用 pandas 做到这一点

最佳答案

  • df.col1.diff().lt(0).cumsum() 定义升序值组
  • set_index 与这些组 col1 但使用 drop= 将 col1 保留在数据框中假的
  • groupbypd.concat 使用 reindexmethod='nearest'

我留下了旧的 col1 索引,这样你就可以看到什么映射到了什么。

c = df.set_index([df.col1.diff().lt(0).cumsum().rename('grp'), 'col1'], drop=False)
pd.concat([c.xs(k).reindex([1, 5, 10], method='nearest') for k, c in c.groupby(level=0)])

      col1  col2
col1            
1        1    10
5        5    23
10      11    32
1        2    23
5        6    15
10      10    32

如果您不喜欢索引中多余的 col1,您可以重命名索引然后将其删除:

c = df.set_index([df.col1.diff().lt(0).cumsum().rename('grp'), 'col1'], drop=False)
pd.concat([c.xs(k).reindex([1, 5, 10], method='nearest') for k, c in c.groupby(level=0)]) \
    .rename_axis(None).reset_index(drop=True)

   col1  col2
0     1    10
1     5    23
2    11    32
3     2    23
4     6    15
5    10    32

关于python - 根据特定的 col1 值查找 col2 值,如果不存在则使用 pandas 保持最近的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56169407/

相关文章:

python - DATE 和 TIME 列上的简单索引

r - 为一个点上色并在ggplot2中添加注释?

python - 在 Django/Django Rest 中添加两因素身份验证

python - 多维Newton Raphson的同时优化/时间复杂度

python - 如何安装 Pandas 0.20.0

python - 对 groupby 对象中的每个组应用重采样

R 使用 lapply() 来填充和命名数据框列表中的一列

python - 在 python 中找到阶乘的最佳方法?

python - 查找现有位置 n 英里的位置

python - 将一个数据帧的值替换为另一个数据帧的值