简体   繁体   中英

pandas: extract certain rows as a dataframe by the value of a column

I have a list of column value and from a existing dataframe I want to extract the row by this column value by using a loop since the list has lots of values.

list = [2,4,5,6,7,8, ....., 2345]
df # df is an existing dataframe 
#'number' is the name of the column that has the value of list in it 

for i in list:
    df.loc[(df["number"] == i)])
df

for i in list:
   P = pd.DataFrame(df.loc[(df["number"] == i)])
P # extract only one column of a certain number

both does not get the result I want.

Use isin for getting the rows which have given list values as:

df = pd.DataFrame(np.arange(0,20).reshape(5,4),columns=list('abcd'))
    a   b   c   d
0   0   1   2   3
1   4   5   6   7
2   8   9  10  11
3  12  13  14  15
4  16  17  18  19

l = [2,7,19]

df.loc[df['d'].isin(l)]

    a   b   c   d
1   4   5   6   7
4  16  17  18  19

So, the column d has 7 and 19 in 1st and 4th rows which we selected using isin .

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