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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics