How to Convert a 2D Array to a DataFrame in Python?

Estimated read time 1 min read

To convert a 2D array (or nested list) to a DataFrame in Python, you can use the pandas library. The pandas library provides the DataFrame() function, which allows you to create a DataFrame from a 2D array. Here’s an example:

import pandas as pd

array = [['key1', 'value1'], ['key2', 'value2'], ['key3', 'value3']]

df = pd.DataFrame(array, columns=['Key', 'Value'])

print(df)

In the code above, we import the pandas library as pd. We have a 2D array called array, where each inner list represents a row in the DataFrame. We use the pd.DataFrame() function, passing in the array and specifying the column names using the columns parameter.

The resulting DataFrame df will have two columns, “Key” and “Value”, with the values populated from the 2D array.

The output will be:

    Key   Value
0  key1  value1
1  key2  value2
2  key3  value3

Each row of the 2D array corresponds to a row in the DataFrame, and the values are placed in the respective columns.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply