Home > OS >  Pandas selecting nth element based on others column from array in a cell dataframe
Pandas selecting nth element based on others column from array in a cell dataframe

Time:02-21

I have one dataframe:

Prefix      Value
0           [1, 2]
1           [3,8,9]
2           [4, 5, 6]

I wish to have a new column return the element from the Value column based on Prefix column:

Prefix      Value       Element
0           [1, 2]      1
1           [3,8,9]     8
2           [4, 5, 6]   6

I have try below code but error:

df["Element"]=df.Value.str[df.Prefix]

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

CodePudding user response:

This can be done using a list comprehension for a reasonably efficient solution

df['Element'] = [val[prefix] for val, prefix in zip(df['Value'], df['Prefix'])]

   Prefix      Value  Element
0       0     [1, 2]        1
1       1  [3, 8, 9]        8
2       2  [4, 5, 6]        6

Your code failed because you were passing a Series (an iterable) to .str which should only be passed integer values.

CodePudding user response:

Try this one:

df = pd.DataFrame({'col': [[1,3,5], [4,7,9], [7,14, 16], [6,13, 3, 9]]})
df['nth_elmnt'] = [x[i] for x, i in zip(df.col, df.index)] 

CodePudding user response:

Can't think of a vectorized way. But the following apply should work

df['Element'] = df.apply(lambda x: x["Value"][x["Prefix"]], axis=1)
  • Related