w3resource

How to combine a NumPy array and a Pandas DataFrame into one DataFrame?


19. Array and DataFrame Combination

Write a NumPy program to combine a NumPy array and a Pandas DataFrame into a single DataFrame and print it.

Sample Solution:

Python Code:

import numpy as np
import pandas as pd

# Create a NumPy array
array = np.array([[10, 20], [30, 40], [50, 60]])

# Create a Pandas DataFrame
data = {
    'A': [1, 2, 3],
    'B': ['a', 'b', 'c']
}
df = pd.DataFrame(data)

# Combine the NumPy array and Pandas DataFrame into a single DataFrame
# Adding columns to match the DataFrame structure
array_df = pd.DataFrame(array, columns=['C', 'D'])

# Concatenate both DataFrames
combined_df = pd.concat([df, array_df], axis=1)

# Print the combined DataFrame
print(combined_df)

Output:

   A  B   C   D
0  1  a  10  20
1  2  b  30  40
2  3  c  50  60

Explanation:

  • Import NumPy and Pandas Libraries: Import the NumPy and Pandas libraries to handle arrays and DataFrames.
  • Create NumPy Array: Define a NumPy array with some example data.
  • Create Pandas DataFrame: Define a Pandas DataFrame with some example data, ensuring it has the same number of rows as the NumPy array.
  • Convert Array to DataFrame: Convert the NumPy array to a DataFrame, specifying column names to match the structure of the original DataFrame.
  • Combine DataFrames: Use pd.concat() to concatenate the original DataFrame and the new DataFrame created from the NumPy array along the columns (axis=1).
  • Print Combined DataFrame: Output the resulting combined DataFrame to verify the merge.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to combine a NumPy array and a Pandas DataFrame by aligning them on a common index and merging columns.
  • Write a Numpy program to horizontally stack a NumPy array to a DataFrame and then verify data integrity through cross-checking.
  • Write a Numpy program to merge a NumPy array with a DataFrame by converting the array into a DataFrame and performing an inner join.
  • Write a Numpy program to combine data from a NumPy array and a DataFrame and then sort the resulting DataFrame based on a computed column.

Go to:


Previous: How to convert a Pandas DataFrame with mixed data types to a NumPy array?
Next: How to append a NumPy array to a Python list and print the result?

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.