1

I have a dataframe like the belows.

df
   a  b  c
w  5  3  3
x  4  7  6
y  6  2  5
z  2  6  2

And I have a list like belows.

a
[['w', 'x', 'w'], 
['x', 'y', 'y']]

How can I get the results like

[[5,7,3],
[4,2,5]]

If the only way is using a for loop, which is the fastest way?

2 Answers 2

4

I think for loop should be fast enough

[[df.loc[z,y] for z,y in zip(x,df.columns)] for x in l ]
Out[981]: [[5, 7, 3], [4, 2, 5]]
2
  • 1
    df.at instead.
    – piRSquared
    Commented Aug 27, 2018 at 3:19
  • 1
    Thank u so much. I use the df.at version.
    – LiuHao
    Commented Aug 27, 2018 at 4:50
2

Assuming length of sub-lists are always the same as the length of columns

[[*df.lookup(i, df.columns)] for i in a]

[[5, 7, 3], [4, 2, 5]]
1
  • Thanks a lot. df.at is definitely faster than df.loc
    – LiuHao
    Commented Aug 27, 2018 at 4:49

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.