🎓 A1Learner
🔍
0 of 50 lessons completed

NumPy and Pandas Together

A DataFrame column can become a NumPy array, and an array can become a DataFrame. The two tools share the same values.

A column as an array

values turns one column into an array. The numbers keep their order.

import pandas as pd

df = pd.DataFrame({"product": ["Tea", "Coffee", "Mug"], "units": [2, 1, 3]})
print(df["units"].values)

A whole frame as an array

to_numpy turns a frame of numbers into one array. Each row becomes one row of the array.

import pandas as pd

df = pd.DataFrame({"units": [2, 1, 3], "price": [4.5, 6.0, 12.0]})
print(df.to_numpy())

An array as a frame

pd.DataFrame builds a frame from an array. The columns list names each column.

import numpy as np
import pandas as pd

arr = np.array([[2, 4.5], [1, 6.0]])
df = pd.DataFrame(arr, columns=["units", "price"])
print(df)

Example

import io
import pandas as pd

SALES_CSV = """
order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""

sales = pd.read_csv(io.StringIO(SALES_CSV))
units = sales["units"].to_numpy()
prices = sales["price"].values
revenue = units * prices
print(revenue.sum())

Key points

  • Use .values on a column to get its values as an array.
  • Use .to_numpy on a whole frame to get all its values as an array.
  • Use pd.DataFrame to build a frame from an array.
  • Column names stay in the frame. They do not travel into the array.

In this example, the sales table loads from its CSV text. to_numpy turns the units column into an array, and values turns the price column into an array. Multiplying them gives the money for each order. sum adds the twelve amounts to 221.5.

Note

.values drops the column names. The array holds only the values, in order.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which call turns a whole DataFrame into a NumPy array?