How to set in pandas the first column and row as index?

PythonPython 3.xPandas

Python Problem Overview


When I read in a CSV, I can say pd.read_csv('my.csv', index_col=3) and it sets the third column as index.

How can I do the same if I have a pandas dataframe in memory? And how can I say to use the first row also as an index? The first column and row are strings, rest of the matrix is integer.

Python Solutions


Solution 1 - Python

You can try this regardless of the number of rows

df = pd.read_csv('data.csv', index_col=0)

Solution 2 - Python

Maybe try set_index()?

df = df.set_index([2])

Solution 3 - Python

Making the first (or n-th) column the index in increasing order of verboseness:

df.set_index(list(df)[0])
df.set_index(df.columns[0])
df.set_index(df.columns.tolist()[0])

Making the first (or n-th) row the index:

df.set_index(df.iloc[0].values)

You can use both if you want a multi-level index:

df.set_index([df.iloc[0], df.columns[0]])

Observe that using a column as index will automatically drop it as column. Using a row as index is just a copy operation and won't drop the row from the DataFrame.

Solution 4 - Python

Maybe try df = pd.read_csv(header = 0)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOliView Question on Stackoverflow
Solution 1 - PythonY. YazarelView Answer on Stackoverflow
Solution 2 - PythonAnnie GuoView Answer on Stackoverflow
Solution 3 - PythonvillasvView Answer on Stackoverflow
Solution 4 - Pythondevelop_opiView Answer on Stackoverflow