简体   繁体   中英

How to drop rows after minimum value reached in specific column in Pandas DataFrame?

If I have a pandas data frame like this:

      Col A  Col B
 0      9      2
 1      7      1
 2      6      9
 3      3      3
 4      1      4
 5      6      3
 6      7      2
 7      9      1

How do I remove all rows after the minimum value is reached in Column A (which is 1) such that I get a pandas data frame like this:

      Col A  Col B
 0      9      2
 1      7      1
 2      6      9
 3      3      3
 4      1      4
df[df.index<=df['Col A'].idxmin()]

Try the below code, Hope it will help.

df = pd.DataFrame({'Col A': [9,7,6,3,1,6,7,9],'Col B':[2,1,9,3,4,3,2,1]})
df_list = df['Col A'].tolist()
index = df_list.index(min(df_list))
df.iloc[:index+1]

Ouput will be :

  Col A     Col B
0   9       2
1   7       1
2   6       9
3   3       3
4   1       4

使用idxmin()

df = df.loc[:df['Col A'].idxmin()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM