python-scipyHow do I convert a Python Numpy array to a Pandas Dataframe?
Converting a Python Numpy array to a Pandas Dataframe is a simple task. The following example code demonstrates how to do this:
import pandas as pd
import numpy as np
# Create a Numpy array
data = np.array([['','Col1','Col2'],
['Row1',1,2],
['Row2',3,4]])
# Create a Pandas Dataframe
df = pd.DataFrame(data=data[1:,1:],
index=data[1:,0],
columns=data[0,1:])
print(df)
Output example
Col1 Col2
Row1 1 2
Row2 3 4
The code above consists of the following parts:
import pandas as pd
andimport numpy as np
- imports the necessary libraries for the task.data = np.array([['','Col1','Col2'], ['Row1',1,2], ['Row2',3,4]])
- creates a Numpy array with the data we want to convert.df = pd.DataFrame(data=data[1:,1:], index=data[1:,0], columns=data[0,1:])
- creates a Pandas Dataframe from the Numpy array.print(df)
- prints the Dataframe.
For more information, please refer to the following links:
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How do I create a zero matrix using Python and Numpy?
- How do I create a numpy array of zeros using Python?
- How do I use Python Scipy to generate a PDF?
- How do I create an array of zeros with the same shape as an existing array using Python and NumPy?
- How do I create a numpy array of zeros using Python?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How can I check if a certain version of Python is compatible with SciPy?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How can I use Python and SciPy to solve an ordinary differential equation?
See more codes...