Explore Courses Blog Tutorials Interview Questions
0 votes
in Data Science by (17.6k points)

I have a Numpy array consisting of a list of lists, representing a two-dimensional array with row labels and column names as shown below:

data = array([['','Col1','Col2'],['Row1',1,2],['Row2',3,4]])

I'd like the resulting DataFrame to have Row1 and Row2 as index values, and Col1, Col2 as header values

I can specify the index as follows:

df = pd.DataFrame(data,index=data[:,0]),

however I am unsure how to best assign column headers.

1 Answer

0 votes
by (41.4k points)

Here, specify the data, index, and columns to DataFrame constructor:

>>> pd.DataFrame(data=data[1:,1:],    # values

...              index=data[1:,0],    # 1st column as index

...              columns=data[0,1:])  # 1st row as the column names

If you wish to learn more about Python, visit Python tutorial and Python course by Intellipaat.

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers


108k users

Browse Categories