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

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

Here's how you can create a pandas DataFrame from a numpy array while specifying the index and column headers:

  1. Setup: First, ensure you have both pandas and numpy installed:

    pip install pandas numpy 
  2. Sample Code:

    import pandas as pd import numpy as np # Create a sample numpy array data = np.array([ [10, 20, 30], [40, 50, 60], [70, 80, 90] ]) # Specify index and columns index_values = ['row1', 'row2', 'row3'] column_headers = ['col1', 'col2', 'col3'] # Create the DataFrame df = pd.DataFrame(data=data, index=index_values, columns=column_headers) # Display the DataFrame print(df) 

    This will give you the following DataFrame:

     col1 col2 col3 row1 10 20 30 row2 40 50 60 row3 70 80 90 

In the above example, the data numpy array provides the data for the DataFrame. The index_values list specifies the row labels, and the column_headers list specifies the column headers. The DataFrame is then created using pd.DataFrame() with the data, index, and columns specified.


More Tags

html-entities gs-vlookup ffmpeg wcf-binding pose-estimation machine-learning count-unique scientific-notation osx-mavericks rigid-bodies

More Programming Guides

Other Guides

More Programming Examples