2

I have a dataframe,and want to set first column to index using iloc[:,0],but something's wrong.

I apply iloc[:,0] to set first column to index.

data12 = pd.DataFrame({"b":["a","h","r","e","a"],
                       "a":range(5)})
data2 = data12.set_index(data12.iloc[:,0])
data2

    b   a
b       
a   a   0
h   h   1
r   r   2
e   e   3
a   a   4


I want to get the follwing result.

    a
b   
a   0
h   1
r   2
e   3
a   4

thank you very much

0

1 Answer 1

1

Use the name of the Series, not the Series itself.

data12.set_index(data12.iloc[:, 0].name) # or data12.columns[0]

   a  
b     
a  0  
h  1  
r  2  
e  3  
a  4 

From the documentation for set_index

keys This parameter can be either a single column key, a single array of the same length as the calling DataFrame, or a list containing an arbitrary combination of column keys and arrays. Here, “array” encompasses Series, Index and np.ndarray.

You need to pass a key, not an array if you want to set the index and have the respective Series no longer included as a column of the DataFrame.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for your help! If i want to change the name of the index on the condition that i don't know the name of the index, so i can not use dict {"b":"A"} ,thank you !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.