Pandas series to 2d array

When converting a pandas series to a 2D array, you can use the values attribute of the series. The values attribute will return a numpy array representing the underlying data of the series.

Here’s an example to illustrate the process:

# Import required libraries
import pandas as pd

# Create a pandas series
data = pd.Series([10, 20, 30, 40, 50])

# Convert series to 2D array
array_2d = data.values.reshape(-1, 1)

# Print the 2D array
print(array_2d)

In the above example, we first import the pandas library. Then, we create a pandas series called ‘data’ with values [10, 20, 30, 40, 50].

Next, we convert the series to a 2D array by using the values attribute and reshaping it with reshape(-1, 1). The -1 in the reshape function automatically calculates the appropriate number of rows based on the length of the data series.

Finally, we print the resulting 2D array which will look like this:

[[10]
 [20]
 [30]
 [40]
 [50]]

By using the values attribute and reshaping, we have successfully converted the pandas series to a 2D array.

Leave a comment