0

I have a df with columns a-h, and I wish to create a list of these column values, but in the order of values in another list (list1). list1 corresponds to the index value in df.

df

a  b  c  d  e  f  g  h

list1
[3,1,0,5,2,7,4,6]

Desired list

['d', 'b', 'a', 'f', 'c', 'h', 'e', 'g']

3 Answers 3

2

You can just do df.columns[list1]:

import pandas as pd
df = pd.DataFrame([], columns=list('abcdefgh'))

list1 = [3,1,0,5,2,7,4,6]

print(df.columns[list1])
# Index(['d', 'b', 'a', 'f', 'c', 'h', 'e', 'g'], dtype='object')
Sign up to request clarification or add additional context in comments.

Comments

1

First get a np.array of alphabets

arr = np.array(list('abcdefgh'))

Or in your case, a list of your df columns

arr = np.array(df.columns)

Then use your indices as a indexing mask

arr[[3,1,0]]

out:

['d', 'b', 'a']

Comments

0

Check

df.columns.to_series()[list1].tolist()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.