Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 547
Oli Avatar asked Apr 13 '16 18:04

Oli


People also ask

How do you set a column to index in pandas?

To create an index, from a column, in Pandas dataframe you use the set_index() method. For example, if you want the column “Year” to be index you type <code>df. set_index(“Year”)</code>. Now, the set_index() method will return the modified dataframe as a result.

How do I get first row index in pandas?

Use DataFrame.iloc[0] to set the column labels by extracting the first row. In pandas, the index starts from 0 hence 0 means first row.

How do I give a row an index in pandas?

Pandas DataFrame: set_index() function The set_index() function is used to set the DataFrame index using existing columns. Set the DataFrame index (row labels) using one or more existing columns or arrays of the correct length. The index can replace the existing index or expand on it.


1 Answers

You can try this regardless of the number of rows

df = pd.read_csv('data.csv', index_col=0) 
like image 180
Y. Yazarel Avatar answered Oct 05 '22 16:10

Y. Yazarel