python - Pandas 删除前 n 行,直到满足列上的条件

标签 python pandas dataframe row

我正在尝试从我的数据框中删除一些行。其实我想删除第一个n行,而n应该是某个条件的行号。我希望数据框以包含 x-y 值 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找到第一个位置n

#             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

关于python - Pandas 删除前 n 行,直到满足列上的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52907328/

相关文章:

python - 推断日期格式与传递解析器

python - 将数据框写入带有标题的 excel

python - 获取值错误 : Shape of passed values is (14, 78692),索引暗示 (14, 78250)

python - 如何从输出中删除 "Decimal"关键字

javascript - (Web)套接字连接发送 header 而不是字符串

python - 使用paintEvent 在 QLabel 中绘画

python - 将 pandas 数据框中的多行合并为一行?

python - 将函数应用于数据框列的最有效方法

python - 导入信号时出现未绑定(bind)局部变量错误?

python - 如何在 Pandas 中保存符合特定条件的先前结果