Transpose, then unpack:

>>> x, y, z = data.T
>>> x
array([1, 4, 7])
Answer from behzad.nouri on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 58964668 › how-to-split-array-with-1-column-into-multiple-columns-numpy-array
How to split array with 1 column into multiple columns (numpy array) - Stack Overflow
Turn that back into numpy (2D). Then use transpose to access columns rather than rows. Also I'd use pandas, which can recognize a list of rows as a dataframe in a single line. ... Go back to the result line. Is line.split(',') right? Are columns of really divided by commas. Your array display suggests not.
Discussions

python - Split a Pandas column of lists into multiple columns - Stack Overflow
0 from list of list in pandas dataframe to new set of list with multiple columns in pandas dataframe · 1 Split a Pandas column of lists with different lengths into multiple columns More on stackoverflow.com
🌐 stackoverflow.com
python - Splitting each item in an array into a separate data frame column - Stack Overflow
2 Python Split a value of arrays into different columns · 0 Split list element in dataframe over multiple rows More on stackoverflow.com
🌐 stackoverflow.com
May 4, 2015
python - Pandas dataframe split array entry into two columns - Stack Overflow
I have a data frame that looks like this: reviewerID asin reviewerName helpful unixReviewTime \ 0 A1N4O8VOJZTDVB B004A9SDD8 Annette Yancey [1, 1] 1383350400 I'd like... More on stackoverflow.com
🌐 stackoverflow.com
November 12, 2016
python - Pandas Column Split (Array) - Stack Overflow
Below is my data in SQL Server After reading data in python it become like this I use the below code to split the value to multiple columns # 1. To split single array column to multiple column ba... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 13
560

You can use the DataFrame constructor with lists created by to_list:

import pandas as pd

d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],
                ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]}
df2 = pd.DataFrame(d1)
print (df2)
       teams
0  [SF, NYG]
1  [SF, NYG]
2  [SF, NYG]
3  [SF, NYG]
4  [SF, NYG]
5  [SF, NYG]
6  [SF, NYG]

df2[['team1','team2']] = pd.DataFrame(df2.teams.tolist(), index= df2.index)
print (df2)
       teams team1 team2
0  [SF, NYG]    SF   NYG
1  [SF, NYG]    SF   NYG
2  [SF, NYG]    SF   NYG
3  [SF, NYG]    SF   NYG
4  [SF, NYG]    SF   NYG
5  [SF, NYG]    SF   NYG
6  [SF, NYG]    SF   NYG

And for a new DataFrame:

df3 = pd.DataFrame(df2['teams'].to_list(), columns=['team1','team2'])
print (df3)
  team1 team2
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG

A solution with apply(pd.Series) is very slow:

#7k rows
df2 = pd.concat([df2]*1000).reset_index(drop=True)

In [121]: %timeit df2['teams'].apply(pd.Series)
1.79 s ± 52.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [122]: %timeit pd.DataFrame(df2['teams'].to_list(), columns=['team1','team2'])
1.63 ms ± 54.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
2 of 13
126

Much simpler solution:

pd.DataFrame(df2["teams"].to_list(), columns=['team1', 'team2'])

Yields,

  team1 team2
-------------
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG
7    SF   NYG

If you wanted to split a column of delimited strings rather than lists, you could similarly do:

pd.DataFrame(df["teams"].str.split('<delim>', expand=True).values,
             columns=['team1', 'team2'])
🌐
w3resource
w3resource.com › numpy › manipulation › hsplit.php
NumPy: numpy.hsplit() function - w3resource
April 24, 2026 - The numpy.hsplit() function is used to split an array into multiple sub-arrays horizontally (column-wise).
Find elsewhere
Top answer
1 of 1
1

The reason is the lists are still stored as strings in the hashtags column when you read them with read_csv. You can convert them upon reading of the data (follwing code taken from the Colab notebook):

import pandas as pd
from ast import literal_eval

url = "https://raw.githubusercontent.com/hashimputhiyakath/datasets/main/hashtags10.csv"

# Notice the added converter to turn strings into lists.
df = pd.read_csv(url, converters={'hashtags': literal_eval})

And then the solution you mentioned will work as expected.

df_hashtags_splitted = pd.DataFrame(df['hashtags'].tolist(), index=df.index).add_prefix('hashtag_')
print(df_hashtags_splitted.head(10))
          hashtag_0     hashtag_1         hashtag_2       hashtag_3           hashtag_4       hashtag_5    hashtag_6         hashtag_7  hashtag_8       hashtag_9 hashtag_10 hashtag_11
0         longcovid     covidhelp              None            None                None            None         None              None       None            None       None       None
1            mumbai         covid      hospitalbeds  covidemergency           mahacovid       oxygenbed  mumbaicovid  covid19indiahelp  covidhelp  covidresources       None       None
2   kawahcoffeeshop   coffeelover             kawah       costarica            puravida         heredia       oxygen              None       None            None       None       None
3           lucknow        mumbai         hyderabad           delhi            verified  covidresources    covidhelp  covid19indiahelp       None            None       None       None
4            oxygen          None              None            None                None            None         None              None       None            None       None       None
5  covid19indiahelp        mahara              None            None                None            None         None              None       None            None       None       None
6            oxygen       amadoda              None            None                None            None         None              None       None            None       None       None
7  plasmadonordelhi  plasmamumbai  covid19indiahelp       covidhelp  covidemergency2021            None         None              None       None            None       None       None
8            oxygen  conservation           wilding       rewilding         environment  sustainability  restorative       agriculture   wildlife    biodiversity      water   wildswim
9             covid      verified            mumbai          oxygen  covidemergency2021         covid19    covidhelp    covidresources       None            None       None       None

Alternatively, to convert the lists to strings after you read the csv you can do:

df['hashtags'] = df['hashtags'].map(literal_eval)
🌐
W3Schools
w3schools.com › python › numpy › numpy_array_split.asp
NumPy Splitting Array
Use the hsplit() method to split the 2-D array into three 2-D arrays along columns.
Top answer
1 of 4
113

Spark >= 2.4

You can replace zip_ udf with arrays_zip function

from pyspark.sql.functions import arrays_zip, col, explode

(df
    .withColumn("tmp", arrays_zip("b", "c"))
    .withColumn("tmp", explode("tmp"))
    .select("a", col("tmp.b"), col("tmp.c"), "d"))

Spark < 2.4

With DataFrames and UDF:

from pyspark.sql.types import ArrayType, StructType, StructField, IntegerType
from pyspark.sql.functions import col, udf, explode

zip_ = udf(
  lambda x, y: list(zip(x, y)),
  ArrayType(StructType([
      # Adjust types to reflect data types
      StructField("first", IntegerType()),
      StructField("second", IntegerType())
  ]))
)

(df
    .withColumn("tmp", zip_("b", "c"))
    # UDF output cannot be directly passed to explode
    .withColumn("tmp", explode("tmp"))
    .select("a", col("tmp.first").alias("b"), col("tmp.second").alias("c"), "d"))

With RDDs:

(df
    .rdd
    .flatMap(lambda row: [(row.a, b, c, row.d) for b, c in zip(row.b, row.c)])
    .toDF(["a", "b", "c", "d"]))

Both solutions are inefficient due to Python communication overhead. If data size is fixed you can do something like this:

from functools import reduce
from pyspark.sql import DataFrame

# Length of array
n = 3

# For legacy Python you'll need a separate function
# in place of method accessor 
reduce(
    DataFrame.unionAll, 
    (df.select("a", col("b").getItem(i), col("c").getItem(i), "d")
        for i in range(n))
).toDF("a", "b", "c", "d")

or even:

from pyspark.sql.functions import array, struct

# SQL level zip of arrays of known size
# followed by explode
tmp = explode(array(*[
    struct(col("b").getItem(i).alias("b"), col("c").getItem(i).alias("c"))
    for i in range(n)
]))

(df
    .withColumn("tmp", tmp)
    .select("a", col("tmp").getItem("b"), col("tmp").getItem("c"), "d"))

This should be significantly faster compared to UDF or RDD. Generalized to support an arbitrary number of columns:

# This uses keyword only arguments
# If you use legacy Python you'll have to change signature
# Body of the function can stay the same
def zip_and_explode(*colnames, n):
    return explode(array(*[
        struct(*[col(c).getItem(i).alias(c) for c in colnames])
        for i in range(n)
    ]))

df.withColumn("tmp", zip_and_explode("b", "c", n=3))
2 of 4
11

You'd need to use flatMap, not map as you want to make multiple output rows out of each input row.

from pyspark.sql import Row
def dualExplode(r):
    rowDict = r.asDict()
    bList = rowDict.pop('b')
    cList = rowDict.pop('c')
    for b,c in zip(bList, cList):
        newDict = dict(rowDict)
        newDict['b'] = b
        newDict['c'] = c
        yield Row(**newDict)

df_split = sqlContext.createDataFrame(df.rdd.flatMap(dualExplode))
🌐
GeeksforGeeks
origin.geeksforgeeks.org › python › pyspark-split-multiple-array-columns-into-rows
Split multiple array columns into rows in Pyspark - GeeksforGeeks
July 23, 2025 - The posexplode() splits the array column into rows for each element in the array and also provides the position of the elements in the array. It creates two columns “pos’ to carry the position of the array element and the ‘col’ to carry the particular array elements and ignores null values.
🌐
Reddit
reddit.com › r/learnpython › separate large arrays into separate columns of pandas dataframe
r/learnpython on Reddit: Separate large arrays into separate columns of pandas dataframe
July 1, 2021 -

So I have a pandas dataframe which contains around 10 columns. Each of the 1000+ (we'll just label it 'z') elements of two of these columns is a list of n values, and when matched they form sets of (x, y) pairs. So those two columns look something like this:

Column 1 Column 2
1 (x0, x1, ..., xn) (y0, y1, ..., yn)
... ... ...
z (x0, x1, ..., xn) (y0, y1, ..., yn)

I want to separate these columns into individual elements. In other words rather than just the two columns, I want a new dataframe to have 2n columns, one for each x and one for each y. I thought of using numpy's array_split(), but I'm not sure how to implement that in a large enough scale without hardcoding it, which isn't really an option. Is anyone aware of a way to go about this?

Top answer
1 of 2
1

You can convert your dataframe in this way:

import pandas as pd
import numpy as np

df = pd.DataFrame({0:[[2387, 1098], [1873, 6792],], 1:[0,1]})
arr = np.array(df.loc[:,0].to_list())
df2 = pd.DataFrame({0:arr[:,0], 1:arr[:,1], 2:df.loc[:,1]})
print(df2)

The result is:

      0     1  2
0  2387  1098  0
1  1873  6792  1

A second way to solve the problem (with a "moon" sample) is:

import sklearn
import sklearn.datasets

X, y = sklearn.datasets.make_moons()
pd.DataFrame({'x0':X[:,0], 'x1': X[:,1], 'y':y})

and the result is:

          x0        x1  y
0   0.981559  0.191159  0
1   0.967948 -0.499486  1
2   0.018441  0.308841  1
3  -0.981559  0.191159  0
4   0.967295  0.253655  0
..       ...       ... ..
95  0.238554 -0.148228  1
96  0.096023  0.995379  0
97  0.327699 -0.240278  1
98  0.900969  0.433884  0
99  1.981559  0.308841  1

[100 rows x 3 columns]

2 of 2
1

EDIT:

Maybe it looks strange but you can use .str[0] to get first column from lists in DataFrame.

import pandas as pd

df = pd.DataFrame({0:[[2387, 1098], [1873, 6792],], 1:[0,1]})

new_df = pd.DataFrame({
              0: df[0].str[0], 
              1: df[0].str[1], 
              2: df[1]
         })

print(new_df)

OLDER:

Using apply() with pandas.Series you can convert first column into new DataFrame with two columns

import pandas as pd

df = pd.DataFrame({0:[[2387, 1098], [1873, 6792],], 1:[0,1]})

new_df = df[0].apply(pd.Series)

print(new_df)

Result:

      0     1
0  2387  1098
1  1873  6792

And later you can assing them back to old `DataFrame

df[2] = df[1]       # move `[0,1,...]` to column 2
df[[0,1]] = new_df  # put `new_df` in columns 0,1

Result:

      0     1  2
0  2387  1098  0
1  1873  6792  1

Or you can copy column [0,1,...] from old df to new_df

import pandas as pd

df = pd.DataFrame({0:[[2387, 1098], [1873, 6792],], 1:[0,1]})

new_df = df[0].apply(pd.Series)
new_df[2] = df[1]

print(new_df)

🌐
datagy
datagy.io › home › pandas tutorials › pandas dataframes › pandas: split a column of lists into multiple columns
Pandas: Split a Column of Lists into Multiple Columns • datagy
June 5, 2023 - In this tutorial, you’ll learn ... columns. By the end of this tutorial, you’ll have learned how to do the following: The Quick Answer: Use Pandas tolist() If you’re in...
🌐
Statology
statology.org › home › pandas: how to split a column of lists into multiple columns
Pandas: How to Split a Column of Lists into Multiple Columns
August 24, 2022 - Note: If your column of lists has an uneven number of values in each list, pandas will simply fill in missing values with NaN values when splitting the lists into columns.