熊猫删除前n行,直到满足列条件

毛里求斯

我正在尝试从数据框中删除一些行。实际上我想删除第一n行,而n应该是某个条件的行号。我希望dataframe从包含的行开始x-y values xEnd,yEnd所有先前的行应从数据帧中删除。我不知何故没有解决方案。到目前为止,这就是我所拥有的。

例:

import pandas as  pd
xEnd=2
yEnd=3
df = pd.DataFrame({'x':[1,1,1,2,2,2], 'y':[1,2,3,3,4,3], 'id':[0,1,2,3,4,5]})
n=df["id"].iloc[df["x"]==xEnd and df["y"]==yEnd]
df = df.iloc[n:]

我希望我的代码减少数据框

{'x':[1,1,1,2,2,2], 'y':[1,2,3,3,4,3], 'id':[0,1,2,3,4,5]}

{'x':[2,2,2], 'y':[3,4,3], 'id':[3,4,5]}
海盗
  • 使用&代替and
  • 使用loc代替iloc您可以使用,iloc但可能会因索引而中断
  • idxmax找到的第positiopn

#             I used idxmax to find the index |
#                                             v
df.loc[((df['x'] == xEnd) & (df['y'] == yEnd)).idxmax():]
# ^
# | finding the index goes with using loc

   id  x  y
3   3  2  3
4   4  2  4
5   5  2  3

这是一个iloc变化

#    I used values.argmax to find the position |
#                                              v
df.iloc[((df['x'] == xEnd) & (df['y'] == yEnd)).values.argmax():]
# ^
# | finding the position goes with using iloc

   id  x  y
3   3  2  3
4   4  2  4
5   5  2  3

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章