Reputation: 99
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
Upvotes: 2
Views: 5748
Reputation: 51165
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.
Upvotes: 1