How to Convert Array to Column in Pandas dataframe

You can use pd.DataFrame() function to convert an array to a column in a Pandas dataframe. The following shows examples of how to convert array from Numpy to a column in Pandas.

Example 1: Single Column

Step 1: Using Numpy to create an array

# Create an array using Numpy
import numpy as np
x = np.repeat(['City1','City2'],5)
print(x)

Output:

['City1' 'City1' 'City1' 'City1' 'City1' 'City2' 'City2' 'City2' 'City2'
 'City2']

Step 2: Use pd.DataFrame() to convert the array to a column

# Use pd.DataFrame() to convert the array to a column
import pandas as pd
df_x=pd.DataFrame({'cities':x})
print(df_x)

Output:

  cities
0  City1
1  City1
2  City1
3  City1
4  City1
5  City2
6  City2
7  City2
8  City2
9  City2

Example 2: Multiple Columns

The following is an example of converting two arrays into two columns.

Step 1: Using Numpy to create two arrays

# Create two arrays using Numpy
x_1 = np.repeat(['City1','City2'],5)
print(x_1)
x_2 = np.tile(['store1','store2'], 5)
print(x_2)

Output:

['City1' 'City1' 'City1' 'City1' 'City1' 'City2' 'City2' 'City2' 'City2'
 'City2']
['store1' 'store2' 'store1' 'store2' 'store1' 'store2' 'store1' 'store2'
 'store1' 'store2']

Step 2: Use pd.DataFrame() to convert the array to a column

df_x=pd.DataFrame({'cities':x_1, 'stores':x_2})
print(df_x)

Output:

  cities  stores
0  City1  store1
1  City1  store2
2  City1  store1
3  City1  store2
4  City1  store1
5  City2  store2
6  City2  store1
7  City2  store2
8  City2  store1
9  City2  store2

Further Reading