Pandas DataFrames from NumPy Arrays

Build DataFrames from 1-D and 2-D NumPy arrays, preserve numeric dtypes and convert selected columns back to arrays.

Create a DataFrame from a 1-D array 🔝

The original four marks are retained. A 1-D array creates one column. NumPy arrays have one dtype, which may also be object or structured; a DataFrame can keep a separate dtype per column.
import pandas as pd
import numpy as np
marks = np.array([30, 40, 50, 45])
single = pd.DataFrame(marks, columns=["MATH"])
print(single)
assert single.shape == (4, 1)

Expected output

   MATH
0    30
1    40
2    50
3    45

Create the original 2-D table 🔝

Each array row becomes a DataFrame row by default. The original two-by-four array has subjects as rows.
subjects = np.array([[30, 40, 50, 45], [50, 60, 50, 55]])
raw = pd.DataFrame(subjects)
print(raw)
assert raw.shape == (2, 4)

Expected output

    0   1   2   3
0  30  40  50  45
1  50  60  50  55

Transpose and label the columns 🔝

Transpose the original matrix so students become rows and subjects become columns. See column labels.
scores = pd.DataFrame(subjects).T
scores.columns = ["MATH", "ENGLISH"]
print(scores)
assert scores.shape == (4, 2)
assert scores.iloc[0].tolist() == [30, 50]

Expected output

   MATH  ENGLISH
0    30       50
1    40       60
2    50       50
3    45       55

Add names without mixing array types 🔝

Keep Alex, Ron, Jack and King from the source. The original transposed list of names and marks can produce object columns. A dictionary of separate arrays preserves the numeric columns for arithmetic.
names = np.array(["Alex", "Ron", "Jack", "King"])
legacy = pd.DataFrame([names, subjects[0], subjects[1]]).T
legacy.columns = ["NAMES", "MATH", "ENGLISH"]
print("Original mixed layout:")
print(legacy)
students = pd.DataFrame({"NAMES": names, "MATH": subjects[0], "ENGLISH": subjects[1]})
print("Numeric marks preserved:")
print(students)
assert pd.api.types.is_integer_dtype(students["MATH"])
assert pd.api.types.is_integer_dtype(students["ENGLISH"])

Expected output

Original mixed layout:
  NAMES MATH ENGLISH
0  Alex   30      50
1   Ron   40      60
2  Jack   50      50
3  King   45      55
Numeric marks preserved:
  NAMES  MATH  ENGLISH
0  Alex    30       50
1   Ron    40       60
2  Jack    50       50
3  King    45       55

Calculate total marks from separate arrays 🔝

Retain the original subject addition and separate 1-D arrays. An explicit subject list avoids including numeric IDs in a total. More on sum().
math = np.array([30, 40, 50, 45])
english = np.array([50, 60, 50, 55])
result = pd.DataFrame({"NAMES": names, "MATH": math, "ENGLISH": english})
result["Total"] = result["MATH"] + result["ENGLISH"]
print(result)
assert result["Total"].tolist() == [80, 100, 100, 100]

Expected output

  NAMES  MATH  ENGLISH  Total
0  Alex    30       50     80
1   Ron    40       60    100
2  Jack    50       50    100
3  King    45       55    100

Hide index labels when printing 🔝

to_string(index=False) changes the display; it does not remove the DataFrame index. The original index-hiding concept is retained.
print(students.to_string(index=False))
assert students.index.tolist() == [0, 1, 2, 3]

Expected output

NAMES  MATH  ENGLISH
 Alex    30       50
  Ron    40       60
 Jack    50       50
 King    45       55

Generate repeatable random marks and student IDs 🔝

Retain five students and marks from 40 through 99, with a seeded Generator so results can be reproduced. These are synthetic marks, not measured performance. Explore NumPy random generators and random integer ranges.
rng = np.random.default_rng(42)
n = 5
random_students = pd.DataFrame({"ID": np.arange(1, n + 1),
    "MATH": rng.integers(40, 100, size=n), "ENG": rng.integers(40, 100, size=n)})
print(random_students[["MATH", "ENG"]])
print(random_students.to_string(index=False))
assert random_students["ID"].tolist() == [1, 2, 3, 4, 5]
assert random_students[["MATH", "ENG"]].ge(40).all().all()
assert random_students[["MATH", "ENG"]].lt(100).all().all()

Expected output

   MATH  ENG
0    45   91
1    86   45
2    79   81
3    66   52
4    65   45
 ID  MATH  ENG
  1    45   91
  2    86   45
  3    79   81
  4    66   52
  5    65   45

Convert selected numeric columns back to NumPy 🔝

to_numpy() returns values without row or column labels. Select numeric features deliberately. copy=False does not guarantee avoiding a copy; copy=True requests an independent array. Keep labels separately when restoring results.
features = students[["MATH", "ENGLISH"]].to_numpy(dtype="float64", copy=True)
print(features)
features[0, 0] = -1
assert students.loc[0, "MATH"] == 30
assert features.shape == (4, 2)

Expected output

[[30. 50.]
 [40. 60.]
 [50. 50.]
 [45. 55.]]

Export nullable numeric data deliberately 🔝

Specify dtype and na_value when exporting missing numeric values to a floating array. Review missing data before calculations; NumPy mean does not automatically ignore NaN.
nullable = pd.DataFrame({"MATH": pd.Series([30, None, 50], dtype="Int64")})
exported = nullable.to_numpy(dtype="float64", na_value=np.nan)
print(exported)
assert np.isnan(exported[1, 0])

Expected output

[[30.]
 [nan]
 [50.]]

Shape and dtype pitfalls 🔝

A two-dimensional constructor expects column labels matching its width; dictionaries of arrays require equal lengths. A single mixed string/number NumPy array may coerce numbers to strings. Do not assume object columns are safe numeric features. Transposition changes orientation, not the meaning of records. An exported array loses DataFrame labels. See astype() and select_dtypes() for dtype decisions.

Exercise: checked NumPy feature table 🔝

Using the original four students, export MATH and ENGLISH as a numeric array and calculate each row total with NumPy. Add those totals to a copy of the DataFrame; verify the result.

Exercise solution 🔝

Check that the numeric matrix and labelled table have matching row order.
matrix = students[["MATH", "ENGLISH"]].to_numpy(copy=True)
answer = students.copy()
answer["Total"] = matrix.sum(axis=1)
print(answer)
assert answer["Total"].tolist() == [80, 100, 100, 100]
assert "Total" not in students.columns

Expected output

  NAMES  MATH  ENGLISH  Total
0  Alex    30       50     80
1   Ron    40       60    100
2  Jack    50       50    100
3  King    45       55    100

Practice in Google Colab 🔝

Open in Google Colab View on GitHub

Run examples in order, inspect formatted dates and try the exercise. Save a copy to keep edits.

Reference: Pandas NumPy arrays documentation.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer