2

I have the following list:

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

I would like to use it to define an index for the following DataFrame:

df = pd.DataFrame(index= [0,1,4,7])

The DataFrames index corresponds to an entry in the list. The end result should look like:

df_target = pd.DataFrame(index= ['a','b','e','h'])

I have tried a number of built in functions for pandas, but no luck.

3 Answers 3

2

Use Index.map with dictonary created by enumerate:

target_df = pd.DataFrame(index=df.index.map(dict(enumerate(index_list))))
print (target_df)
Empty DataFrame
Columns: []
Index: [a, b, e, h]

If need change index in existing DataFrame:

df = pd.DataFrame({'a':range(4)}, index= [0,1,4,7])
print (df)
   a
0  0
1  1
4  2
7  3

df = df.rename(dict(enumerate(index_list)))
print (df)
   a
a  0
b  1
e  2
h  3
Sign up to request clarification or add additional context in comments.

Comments

0

like this:

print(pd.DataFrame(index=[index_list[i] for i in [0,1,4,7]]))

Output:

Empty DataFrame
Columns: []
Index: [a, b, e, h]

Comments

0

You can pass a Series object to Index.map method.

df.index.map(pd.Series(index_list))


# Index(['a', 'b', 'e', 'h'], dtype='object')

Or rename the Dataframe index directly

df.rename(index=pd.Series(index_list))

# Empty DataFrame
# Columns: []
# Index: [a, b, e, h]

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.