w3resource

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

Pandas: DataFrame Exercise-44 with Solution

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                 

Python 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 Python skills with w3resource's quiz



Python: Tips of the Day

Creates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value

Example:

def tips_map_values(obj, fn):
  ret = {}
  for key in obj.keys():
    ret[key] = fn(obj[key])
  return ret
users = {
  'Owen': { 'user': 'Owen', 'age': 29 },
  'Eddie': { 'user': 'Eddie', 'age': 15 }
}

print(tips_map_values(users, lambda u : u['age'])) # {'Owen': 29, 'Eddie': 15}

Output:

{'Owen': 29, 'Eddie': 15}