Create pandas DataFrame from NumPy Array in Python (2 Examples)
In this tutorial you’ll learn how to create a pandas DataFrame from a NumPy array in the Python programming language.
Setting up the Examples
import numpy as np # Load NumPy library |
import numpy as np # Load NumPy library
npa = np.array([['a', 'b', 'c'], # Constructing a NumPy array ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l'], ['m', 'n', 'o']]) print(npa) # [['a' 'b' 'c'] # ['d' 'e' 'f'] # ['g' 'h' 'i'] # ['j' 'k' 'l'] # ['m' 'n' 'o']] |
npa = np.array([['a', 'b', 'c'], # Constructing a NumPy array ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l'], ['m', 'n', 'o']]) print(npa) # [['a' 'b' 'c'] # ['d' 'e' 'f'] # ['g' 'h' 'i'] # ['j' 'k' 'l'] # ['m' 'n' 'o']]
Example 1: Creating a pandas DataFrame from the Rows of a NumPy Array
import pandas as pd # Load pandas |
import pandas as pd # Load pandas
pdf1 = pd.DataFrame({'A': npa[0, :], # Constructing a pandas DataFrame 'B': npa[1, :], 'C': npa[2, :], 'D': npa[3, :], 'E': npa[4, :]}) print(pdf1) # A B C D E # 0 a d g j m # 1 b e h k n # 2 c f i l o |
pdf1 = pd.DataFrame({'A': npa[0, :], # Constructing a pandas DataFrame 'B': npa[1, :], 'C': npa[2, :], 'D': npa[3, :], 'E': npa[4, :]}) print(pdf1) # A B C D E # 0 a d g j m # 1 b e h k n # 2 c f i l o
Example 2: Creating a pandas DataFrame from the Columns of a NumPy Array
pdf2 = pd.DataFrame({'A': npa[:, 0], # Constructing a pandas DataFrame 'B': npa[:, 1], 'C': npa[:, 2]}) print(pdf2) # A B C # 0 a b c # 1 d e f # 2 g h i # 3 j k l # 4 m n o |
pdf2 = pd.DataFrame({'A': npa[:, 0], # Constructing a pandas DataFrame 'B': npa[:, 1], 'C': npa[:, 2]}) print(pdf2) # A B C # 0 a b c # 1 d e f # 2 g h i # 3 j k l # 4 m n o
Related Articles & Further Resources
You may find some further Python programming tutorials on topics such as data conversion and lists in the following list: