我正在尝试从我的数据框中删除一些行。其实我想删除第一个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/