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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…