我正在尝试从数据框中删除一些行。实际上,我想删除前n
行,而n
应该是某个条件的行号。我希望数据框从包含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]}
答案 0 :(得分:3)
&
代替and
loc
代替iloc
。您可以使用iloc
,但它可能会因索引而中断idxmax
查找第一个正位# 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
答案 1 :(得分:2)
使用cummax
df[((df['x'] == xEnd) & (df['y'] == yEnd)).cummax()]
Out[147]:
id x y
3 3 2 3
4 4 2 4
5 5 2 3