w3resource

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

NumPy: Interoperability Exercise-19 with Solution

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.

Python-Numpy Code Editor:

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

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?

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/combine-a-numpy-array-and-a-pandas-dataframe-into-one-dataframe.php