📜  numpy arrauy 到 df - Python (1)

📅  最后修改于: 2023-12-03 14:44:48.120000             🧑  作者: Mango

numpy array to df - Python

In Python, the numpy library is widely used for mathematical operations on arrays. Sometimes, it is required to convert a numpy array into a pandas DataFrame (df) for further data manipulation and analysis. This guide will walk you through the process of converting a numpy array to a pandas DataFrame.

Prerequisites

Before proceeding, ensure that you have the following installed:

  • Python
  • numpy library
  • pandas library
1. Importing the Required Libraries

First, import the necessary libraries: numpy and pandas.

import numpy as np
import pandas as pd
2. Creating a Numpy Array

To demonstrate the conversion process, let's create a numpy array.

array_np = np.array([[1, 2, 3], [4, 5, 6]]) # an example numpy array
3. Converting Numpy Array to DataFrame

Now, convert the numpy array to a pandas DataFrame using the pd.DataFrame() function.

df = pd.DataFrame(data=array_np)

The resulting DataFrame will have the same dimensions as the original numpy array and will be filled with the corresponding values.

4. Optional: Assigning Column Names

By default, the columns in the DataFrame will be labeled with numeric indices. However, it is often useful to assign meaningful column names. You can do this by specifying the columns parameter in the pd.DataFrame() function.

df = pd.DataFrame(data=array_np, columns=['Column1', 'Column2', 'Column3'])
5. View the DataFrame

To verify the conversion, you can print the resulting DataFrame.

print(df)

This will display the DataFrame representation in the console.

|   Column1 |   Column2 |   Column3 |
|----------:|----------:|----------:|
|         1 |         2 |         3 |
|         4 |         5 |         6 |
Conclusion

By following these steps, you can easily convert a numpy array to a pandas DataFrame. This conversion is useful when you want to utilize the powerful data manipulation and analysis capabilities provided by pandas.