Join pandas dataframe with a python list by index

Question:

I have a pandas dataframe and a python list of arrays [index, value]

I need to join dataframe and the list by index and select a list of arrays [i, df['col1'][i]] where value == 1

pseudocode:

f = pd.DataFrame([10, 20 ,30, 40, 50...])

l = [[0, -1], [2, 1], [4, 1], [3, 0]


result = f join l where l.value == 1 select [index, f.value]

result: [[2, 30], [4, 50]]

Asked By: Boppity Bop

||

Answers:

One option:

out = (
 pd.DataFrame(l, columns=['A', 'B'])
   .loc[lambda d: d.pop('B').eq(1)]
   .merge(f, left_on='A', right_index=True)
   .values.tolist()
)

Or, with a list comprehension:

out = [[a, f.at[a, 0]] for a,b in l if b == 1]

output:

[[2, 30], [4, 50]]
Answered By: mozway
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.