Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

Python Pandas slice with nested for loop condition

I have a dataframe like this:

df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6],'C':[7,8,9],'D':[10,11,12]})

and a list, here x, that may vary in length like this:

x = [1,4]
x = [2,5,8]

And I would like to slice df according to values in x like this

if len(x) == 1:
   df[df['A'] == x[0]]
elif len(x) == 2:
   df[(df['A'] == x[0]) & (df['B'] == x[1])]
elif len(x) == 3:
   df[(df['A'] == x[0]) & (df['B'] == x[1]) & (df['C'] == x[2])]

Do you know a better solution with nested for loop like below that actually work?

df[(df.iloc[:,i] == x[i]) for i in range(len(x))]

Thanks guys!

question from:https://stackoverflow.com/questions/65887540/python-pandas-slice-with-nested-for-loop-condition

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try:

def list_slice(df,x): 
    return df[df.iloc[:, :len(x)].eq(x).all(1)]

list_slice(df, [1,4])
#    A  B  C   D
# 0  1  4  7  10

list_slice(df, [2,5,8])
#    A  B  C   D
# 1  2  5  8  11

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...