【问题标题】:How to get previous rows of a pandas GroupedBy Dataframe based on a condition on the current row?如何根据当前行的条件获取熊猫 GroupedBy Dataframe 的前几行?
【发布时间】:2019-01-28 04:47:30
【问题描述】:

我有一个这样的数据框:

StringCol Timestamp GroupID Flag
   xyz    20170101   123     yes
   abc    20170101   123     yes
   def    20170101   123     yes
   ghi    20170101   123     no
   abc    20170101   124     yes
   jkl    20170101   124     yes
   pqr    20170101   124     no
   klm    20170101   124     yes

我想按 GroupID 对它进行分组,对于每个组,我希望标记为“no”的行和之前的 X 行(数据帧已经按 GroupID 和 Timestamp 排序)。

所以,如果 X = 2,我希望结果类似于:

StringCol Timestamp GroupID Flag
   abc    20170101   123     yes
   def    20170101   123     yes
   ghi    20170101   123     no
   abc    20170101   124     yes
   jkl    20170101   124     yes
   pqr    20170101   124     no

我如何实现这一目标?谢谢。

【问题讨论】:

  • 每组是否只有一行“否”?
  • 不,可能有多个,但为了简单起见,我想选择该 groupID 中标记为“否”的最后一行

标签: python pandas dataframe time-series


【解决方案1】:

这将获取每组最后一个标志的前 X 个项目。

def prevK(x):
    i = x.reset_index(drop=True).Flag.eq('no').iloc[::-1].idxmax()
    return x.iloc[i - 2:i + 1, :]

df.groupby('GroupID', group_keys=False).apply(prevK)

  StringCol  Timestamp  GroupID Flag
1       abc   20170101      123  yes
2       def   20170101      123  yes
3       ghi   20170101      123   no
4       abc   20170101      124  yes
5       jkl   20170101      124  yes
6       pqr   20170101      124   no

【讨论】:

  • @charmander 你想检查我对你数据的回答吗?
  • @Wen 我实际上得到了一个 TypeError 因为我有一个 MultiIndex
【解决方案2】:

如果您只需要组中的最后一个否,请尝试drop_duplicates

df1=df.copy()
df=df[df['Flag'].eq('no')].drop_duplicates(['GroupID'],keep='last')

idx=df.index+1
idy=df.index-2
import itertools
df1.loc[list(itertools.chain(*[list(range(y,x)) for x , y in  zip(idx,idy)]))]
Out[512]: 
  StringCol  Timestamp  GroupID Flag
1       abc   20170101      123  yes
2       def   20170101      123  yes
3       ghi   20170101      123   no
4       abc   20170101      124  yes
5       jkl   20170101      124  yes
6       pqr   20170101      124   no

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-13
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 2019-09-28
    相关资源
    最近更新 更多