Home > Software engineering >  Set list as index of Pandas DataFrame
Set list as index of Pandas DataFrame

Time:07-22

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.

CodePudding user response:

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

CodePudding user response:

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]

CodePudding user response:

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