Home > Blockchain >  Join pandas dataframe with a python list by index
Join pandas dataframe with a python list by index

Time:09-04

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]]

CodePudding user response:

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]]
  • Related