Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a list as the index of an existing pandas dataframe?

I have an existing pandas dataframe, which looks something like:

    Gr          R           B           Gb
0   1.537037    1.733333    1.400000    1.537037
1   1.657952    1.706522    1.650407    1.713024
2   1.670982    1.690476    1.626263    1.661202
3   1.689229    1.683761    1.607143    1.676923
...

I have a separate list, where the length of the list is equal to the number of rows in the above dataframe. Something like:

separate_list = ['a','b','c',....]

How can I make the separate list to be the index of the above dataframe, replacing the default index (0,1,2,...)? All I can find are ways to set an existing column to the index.

Thank you.

like image 720
wookiekim Avatar asked Oct 16 '25 15:10

wookiekim


2 Answers

Simply making your list a column of the DataFrame (df['new_index'] = separate_list) and then setting to be the index should work.

like image 176
Oliver.R Avatar answered Oct 18 '25 10:10

Oliver.R


A pandas df has a set_index method that allows you to make an existing column or a separate series the new df index.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html

like image 35
Conner M. Avatar answered Oct 18 '25 09:10

Conner M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!