w3resource

Pandas: Create a DataFrame from a Numpy array and specify the index column and column headers


Write a Pandas program to create a DataFrame from a Numpy array and specify the index column and column headers.

Sample Solution :

Python Code :

import pandas
import numpy
dtype = [('Column1','int32'), ('Column2','float32'), ('Column3','float32')]
values = numpy.zeros(15, dtype=dtype)
index = ['Index'+str(i) for i in range(1, len(values)+1)]
df = pandas.DataFrame(values, index=index)
print(df)

Sample Output:

          Column1  Column2  Column3
Index1         0      0.0      0.0
Index2         0      0.0      0.0
Index3         0      0.0      0.0
Index4         0      0.0      0.0
Index5         0      0.0      0.0
Index6         0      0.0      0.0
Index7         0      0.0      0.0
Index8         0      0.0      0.0
Index9         0      0.0      0.0
Index10        0      0.0      0.0
Index11        0      0.0      0.0
Index12        0      0.0      0.0
Index13        0      0.0      0.0
Index14        0      0.0      0.0
Index15        0      0.0      0.0                 

Explanation:

dtype = [('Column1','int32'), ('Column2','float32'), ('Column3','float32')]: This code creates a Pandas DataFrame with 15 rows and 3 columns, named 'Column1', 'Column2', and 'Column3', respectively. The data type of the columns are set to be 'int32', 'float32', and 'float32', respectively.

values = numpy.zeros(15, dtype=dtype): This code creates a NumPy structured array with 15 rows and 3 fields using numpy.zeros function. numpy.zeros function initializes an array with zeros of given shape and data type.

index = ['Index'+str(i) for i in range(1, len(values)+1)]: This code sets the index for the DataFrame using a list comprehension. Here, the index is a list of strings starting from "Index1" to "Index15".

df = pandas.DataFrame(values, index=index): Finally, it creates the DataFrame using the Pandas DataFrame function with the values and index as parameters, and prints it using the print function.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to get a list of a specified column of a DataFrame.
Next: Write a Pandas program to find the row for where the value of a given column is maximal.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.