You're trying to split the entire review column of the data frame (which is the Series mentioned in the error message). What you want to do is apply a function to each row of the data frame, which you can do by calling apply on the data frame:

f = lambda x: len(x["review"].split("disappointed")) -1
reviews["disappointed"] = reviews.apply(f, axis=1)
Answer from hoyland on Stack Overflow
Discussions

python - Split (explode) pandas dataframe string entry to separate rows - Stack Overflow
I have a pandas dataframe in which one column of text strings contains comma-separated values. I want to split each CSV field and create a new row per entry (assume that CSV are clean and need only... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Python - Parsing Columns and Rows - Stack Overflow
I am running into some trouble with parsing the contents of a text file into a 2D array/list. I cannot use built-in libraries, so have taken a different approach. This is what my text file looks li... More on stackoverflow.com
๐ŸŒ stackoverflow.com
numpy - How to split row of data into columns separated by comma in python - Stack Overflow
I have a text file in the following format that I am trying to convert into rows and columns: red,red,blue blue,red,blue blue,blue,red Once the conversion is complete, I want to store the above i... More on stackoverflow.com
๐ŸŒ stackoverflow.com
October 15, 2017
Pandas to split single df row into multiple
You're being too fancy and it's messing you up. Given: >>> df ID Name1 Age Name2 Age2 0 001 Joe 25 Mary 89.0 1 002 Chris 38 NaN NaN Just make IDs the index, separate out the two sets of Name + Age columns, rename their columns to be the same, then concatenate and drop NA rows. >>> df = df.set_index('ID') >>> df1 = df.iloc[:, :2] >>> df2 = df.iloc[:, 2:] >>> df2.columns = df1.columns >>> df = pd.concat([df1, df2]).dropna().sort_index().reset_index() Produces: >>> df ID Name1 Age 0 001 Joe 25.0 1 001 Mary 89.0 2 002 Chris 38.0 More on reddit.com
๐ŸŒ r/learnpython
3
2
March 25, 2022
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_string_split.asp
Python String split() Method
txt = "apple#banana#cherry#orange" # setting the maxsplit parameter to 1, will return a list with 2 elements! x = txt.split("#", 1) print(x) Try it Yourself ยป ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com ยท If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com ยท HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
๐ŸŒ
Real Python
realpython.com โ€บ python-split-string
How to Split a String in Python โ€“ Real Python
November 4, 2024 - The .split() method in Python is a versatile tool that allows you to divide a string into a list of substrings based on a specified delimiter. By default, .split() separates a string at each occurrence of whitespace, which includes spaces, tabs, ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ split-pandas-dataframe-by-rows
Split Pandas Dataframe by Rows - GeeksforGeeks
July 15, 2025 - In this article, we will elucidate several commonly employed methods for Split Pandas Dataframe by Rows. These methods are widely utilized for the purpose of dividing a Pandas DataFrame, and we will discuss the which are following: Using Row Index ยท In Groups From Unique Column Values ยท Using Predetermined-Sized Chunks ยท By Shuffling Rows ยท Consider a dataset: To illustrate, let's consider a dataset featuring information about diamonds. Python3 ยท
Top answer
1 of 16
260

UPDATE 3: it makes more sense to use Series.explode() / DataFrame.explode() methods (implemented in Pandas 0.25.0 and extended in Pandas 1.3.0 to support multi-column explode) as is shown in the usage example:

for a single column:

In [1]: df = pd.DataFrame({'A': [[0, 1, 2], 'foo', [], [3, 4]],
   ...:                    'B': 1,
   ...:                    'C': [['a', 'b', 'c'], np.nan, [], ['d', 'e']]})

In [2]: df
Out[2]:
           A  B          C
0  [0, 1, 2]  1  [a, b, c]
1        foo  1        NaN
2         []  1         []
3     [3, 4]  1     [d, e]

In [3]: df.explode('A')
Out[3]:
     A  B          C
0    0  1  [a, b, c]
0    1  1  [a, b, c]
0    2  1  [a, b, c]
1  foo  1        NaN
2  NaN  1         []
3    3  1     [d, e]
3    4  1     [d, e]

for multiple columns (for Pandas 1.3.0+):

In [4]: df.explode(['A', 'C'])
Out[4]:
     A  B    C
0    0  1    a
0    1  1    b
0    2  1    c
1  foo  1  NaN
2  NaN  1  NaN
3    3  1    d
3    4  1    e

UPDATE 2: more generic vectorized function, which will work for multiple normal and multiple list columns

def explode(df, lst_cols, fill_value='', preserve_index=False):
    # make sure `lst_cols` is list-alike
    if (lst_cols is not None
        and len(lst_cols) > 0
        and not isinstance(lst_cols, (list, tuple, np.ndarray, pd.Series))):
        lst_cols = [lst_cols]
    # all columns except `lst_cols`
    idx_cols = df.columns.difference(lst_cols)
    # calculate lengths of lists
    lens = df[lst_cols[0]].str.len()
    # preserve original index values    
    idx = np.repeat(df.index.values, lens)
    # create "exploded" DF
    res = (pd.DataFrame({
                col:np.repeat(df[col].values, lens)
                for col in idx_cols},
                index=idx)
             .assign(**{col:np.concatenate(df.loc[lens>0, col].values)
                            for col in lst_cols}))
    # append those rows that have empty lists
    if (lens == 0).any():
        # at least one list in cells is empty
        res = (res.append(df.loc[lens==0, idx_cols], sort=False)
                  .fillna(fill_value))
    # revert the original index order
    res = res.sort_index()
    # reset index if requested
    if not preserve_index:        
        res = res.reset_index(drop=True)
    return res

Demo:

Multiple list columns - all list columns must have the same # of elements in each row:

In [134]: df
Out[134]:
   aaa  myid        num          text
0   10     1  [1, 2, 3]  [aa, bb, cc]
1   11     2         []            []
2   12     3     [1, 2]      [cc, dd]
3   13     4         []            []

In [135]: explode(df, ['num','text'], fill_value='')
Out[135]:
   aaa  myid num text
0   10     1   1   aa
1   10     1   2   bb
2   10     1   3   cc
3   11     2
4   12     3   1   cc
5   12     3   2   dd
6   13     4

preserving original index values:

In [136]: explode(df, ['num','text'], fill_value='', preserve_index=True)
Out[136]:
   aaa  myid num text
0   10     1   1   aa
0   10     1   2   bb
0   10     1   3   cc
1   11     2
2   12     3   1   cc
2   12     3   2   dd
3   13     4

Setup:

df = pd.DataFrame({
 'aaa': {0: 10, 1: 11, 2: 12, 3: 13},
 'myid': {0: 1, 1: 2, 2: 3, 3: 4},
 'num': {0: [1, 2, 3], 1: [], 2: [1, 2], 3: []},
 'text': {0: ['aa', 'bb', 'cc'], 1: [], 2: ['cc', 'dd'], 3: []}
})

CSV column:

In [46]: df
Out[46]:
        var1  var2 var3
0      a,b,c     1   XX
1  d,e,f,x,y     2   ZZ

In [47]: explode(df.assign(var1=df.var1.str.split(',')), 'var1')
Out[47]:
  var1  var2 var3
0    a     1   XX
1    b     1   XX
2    c     1   XX
3    d     2   ZZ
4    e     2   ZZ
5    f     2   ZZ
6    x     2   ZZ
7    y     2   ZZ

using this little trick we can convert CSV-like column to list column:

In [48]: df.assign(var1=df.var1.str.split(','))
Out[48]:
              var1  var2 var3
0        [a, b, c]     1   XX
1  [d, e, f, x, y]     2   ZZ

UPDATE: generic vectorized approach (will work also for multiple columns):

Original DF:

In [177]: df
Out[177]:
        var1  var2 var3
0      a,b,c     1   XX
1  d,e,f,x,y     2   ZZ

Solution:

first let's convert CSV strings to lists:

In [178]: lst_col = 'var1' 

In [179]: x = df.assign(**{lst_col:df[lst_col].str.split(',')})

In [180]: x
Out[180]:
              var1  var2 var3
0        [a, b, c]     1   XX
1  [d, e, f, x, y]     2   ZZ

Now we can do this:

In [181]: pd.DataFrame({
     ...:     col:np.repeat(x[col].values, x[lst_col].str.len())
     ...:     for col in x.columns.difference([lst_col])
     ...: }).assign(**{lst_col:np.concatenate(x[lst_col].values)})[x.columns.tolist()]
     ...:
Out[181]:
  var1  var2 var3
0    a     1   XX
1    b     1   XX
2    c     1   XX
3    d     2   ZZ
4    e     2   ZZ
5    f     2   ZZ
6    x     2   ZZ
7    y     2   ZZ

OLD answer:

Inspired by @AFinkelstein solution, i wanted to make it bit more generalized which could be applied to DF with more than two columns and as fast, well almost, as fast as AFinkelstein's solution):

In [2]: df = pd.DataFrame(
   ...:    [{'var1': 'a,b,c', 'var2': 1, 'var3': 'XX'},
   ...:     {'var1': 'd,e,f,x,y', 'var2': 2, 'var3': 'ZZ'}]
   ...: )

In [3]: df
Out[3]:
        var1  var2 var3
0      a,b,c     1   XX
1  d,e,f,x,y     2   ZZ

In [4]: (df.set_index(df.columns.drop('var1',1).tolist())
   ...:    .var1.str.split(',', expand=True)
   ...:    .stack()
   ...:    .reset_index()
   ...:    .rename(columns={0:'var1'})
   ...:    .loc[:, df.columns]
   ...: )
Out[4]:
  var1  var2 var3
0    a     1   XX
1    b     1   XX
2    c     1   XX
3    d     2   ZZ
4    e     2   ZZ
5    f     2   ZZ
6    x     2   ZZ
7    y     2   ZZ
2 of 16
157

Pandas >= 0.25

Series and DataFrame methods define a .explode() method that explodes lists into separate rows. See the docs section on Exploding a list-like column.

Since you have a list of comma separated strings, split the string on comma to get a list of elements, then call explode on that column.

df = pd.DataFrame({'var1': ['a,b,c', 'd,e,f'], 'var2': [1, 2]})
df
    var1  var2
0  a,b,c     1
1  d,e,f     2

df.assign(var1=df['var1'].str.split(',')).explode('var1')

  var1  var2
0    a     1
0    b     1
0    c     1
1    d     2
1    e     2
1    f     2

Note that explode only works on a single column (for now). To explode multiple columns at once, see below.

NaNs and empty lists get the treatment they deserve without you having to jump through hoops to get it right.

df = pd.DataFrame({'var1': ['d,e,f', '', np.nan], 'var2': [1, 2, 3]})
df
    var1  var2
0  d,e,f     1
1            2
2    NaN     3

df['var1'].str.split(',')

0    [d, e, f]
1           []
2          NaN

df.assign(var1=df['var1'].str.split(',')).explode('var1')

  var1  var2
0    d     1
0    e     1
0    f     1
1          2  # empty list entry becomes empty string after exploding 
2  NaN     3  # NaN left un-touched

This is a serious advantage over ravel/repeat -based solutions (which ignore empty lists completely, and choke on NaNs).


Exploding Multiple Columns

pandas 1.3 update

df.explode works on multiple columns starting from pandas 1.3:

df = pd.DataFrame({'var1': ['a,b,c', 'd,e,f'], 
                   'var2': ['i,j,k', 'l,m,n'], 
                   'var3': [1, 2]})
df
    var1   var2  var3
0  a,b,c  i,j,k     1
1  d,e,f  l,m,n     2

(df.set_index(['var3']) 
       .apply(lambda col: col.str.split(','))
       .explode(['var1', 'var2'])
       .reset_index()
       .reindex(df.columns, axis=1))

  var1 var2  var3
0    a    i     1
1    b    j     1
2    c    k     1
3    d    l     2
4    e    m     2
5    f    n     2

On older versions, you would move the explode column inside the apply which is a lot less performant:

(df.set_index(['var3']) 
   .apply(lambda col: col.str.split(',').explode())
   .reset_index()
   .reindex(df.columns, axis=1))

The idea is to set as the index, all the columns that should NOT be exploded, then explode the remaining columns via apply. This works well when the lists are equally sized.

๐ŸŒ
IncludeHelp
includehelp.com โ€บ python โ€บ split-cell-into-multiple-rows-in-pandas-dataframe.aspx
Python - Split cell into multiple rows in pandas dataframe
# Importing pandas package import pandas as pd # Importing display attribute from Ipython from IPython.display import display # Creating a dictionary d = { "Product_id":[1,3,7], "Product_code":["#101,#102,#103","#104","#105,#106"], "Manufacturing_date":["22/6/2018","21/8/2019","27/11/2020"], "Cities":["c1,c2,c3","c4","c5,c6"] } # Creating a DataFrame df = pd.DataFrame(d) # Display Original DataFrames print("Created DataFrame:\n",df,"\n") # splitting cities column res = df.set_index(['Product_id', 'Product_code']).apply(lambda x: x.str.split(',').explode()).reset_index() # Display result print("Result:\n",res)
Find elsewhere
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.Series.str.split.html
pandas.Series.str.split โ€” pandas 3.0.4 documentation - PyData |
Without the n parameter, the outputs of rsplit and split are identical. >>> s.str.rsplit() 0 [this, is, a, regular, sentence] 1 [https://docs.python.org/3/tutorial/index.html] 2 NaN dtype: object
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ pandas to split single df row into multiple
r/learnpython on Reddit: Pandas to split single df row into multiple
March 25, 2022 -

Hi there. I'm trying to rack my brain about how to accomplish this. I have a form where each submission is one row in a csv file.

ID Name1 Age Name2 Age
001 Joe 25 Mary 89
002 Chris 38

What I want to accomplish is to splice a single row into 2 rows if Name2 has a value. I want to take this original df, and create something like this:

ID Name Age
001 Joe 25
001 Mary 89
002 Chris 38

That way, I can still group submissions (it's easy to see that Joe and Mary came from the same form), but I have a clean df.

df2=pd.DataFrame(columns=['ID','Name','Age])

#append just the first 3 columns 0,1,2 to new df2
for x in range(len(df):
   df2.append(df[x,0:3]

   #append columns 0,3,4  to df2--but only if there is data in the Name2 column
   if pd.notnull(df.iloc[x,3]):
      df2.append(df.iloc[x,0]   
      df2.append(df.iloc[x,3:5]

This is my logic, but not implementing correctly. Can somebody point me to the right direction? Is this a smart way to approach this? In reality, I have a csv file with about 100 columns and I'm picking and choosing new columns to be added to a much cleaner second data frame. This involves lots of guessing about which columns I want and then getting the right index for .iloc.

Thanks for any tips.

๐ŸŒ
Saturn Cloud
saturncloud.io โ€บ blog โ€บ how-to-split-text-in-a-column-into-multiple-rows-using-pandas
How to Split Text in a Column into Multiple Rows using Pandas | Saturn Cloud Blog
May 1, 2026 - In this blog, discover essential ... task of splitting text within a column into multiple rows. This process is vital for effective data preprocessing, especially when dealing with unstructured data like text. Explore practical methods using Pandas, a widely-used data manipulation library in Python...
๐ŸŒ
Esri Community
community.esri.com โ€บ t5 โ€บ python-questions โ€บ split-attribute-into-multiple-rows-using-python โ€บ td-p โ€บ 756859
Split attribute into multiple rows using python - Esri Community
March 30, 2018 - And now I have to split the code attribute so that every copy I've made has only one road code (order doesn't matter). So from one polyline with attribute (N: x, y, z) I need N polylines each with one single attribute x, y and z. My idea is to loop over FID_copy to get a selection of duplicated rows in table.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-32598.html
Pandas: how to split one row of data to multiple rows and columns in Python
I have a set of data with one row and several columns. I want to split it into multiple rows and 10 columns (kind of multiple dimensional). Here an example of my data( i have 1583717 samples in total): VALUES: [ 0 0 0 ... 5740 -11760 ...
๐ŸŒ
Medium
theitken.medium.com โ€บ pandas-tricks-split-one-row-of-data-into-multiple-rows-7ecd8545c5d4
Pandas Tricks - Split One Row Of Data Into Multiple Rows | by Ken | Medium
September 29, 2020 - As a data scientist or analyst, you will need to spend a lot of time wrangling the data from various sources so that you can have a standard data structure for your further analysis. There are cases that you get the raw data in some sort of summary view and you would need to split one row of data into multiple rows based on certain conditions in order to do grouping and matching from different perspectives.
๐ŸŒ
Medium
medium.com โ€บ @ryan_forrester_ โ€บ splitting-strings-with-multiple-delimiters-in-python-a-complete-guide-2e0c7b424811
Splitting Strings with Multiple Delimiters in Python: A Complete Guide | by ryan | Medium
October 28, 2024 - import re def smart_split(text, delimiters, keep_empty=False): """ A robust splitting function that handles common edge cases: - Multiple delimiters in a row (like "a,,b") - Extra whitespace around fields - Empty input strings - Preserving or removing empty fields Args: text: The string to split delimiters: List of characters to split on keep_empty: Whether to keep empty fields in the result """ # Build the regex pattern, escaping special characters pattern = '|'.join(map(re.escape, delimiters)) # Split the text parts = re.split(pattern, text) # Handle empty fields based on the keep_empty para
๐ŸŒ
Esri Support
support.esri.com โ€บ en-us โ€บ knowledge-base โ€บ how-to-split-values-within-a-field-into-separate-rows-u-000027735
How To: Split Values within a Field into Separate Rows Using ArcPy
August 18, 2023 - import arcpy in_fc = r"C:\Users\Test\Desktop\Folder\Project\Test.gdb\Water_Main" in_fields = ["OBJECTID", "FACILITYID", "INSTALLDATE", "MATERIAL"] out_fc = r"C:\Users\Test\Desktop\Folder\Project\Test.gdb\Water_Main_SPLIT" out_fields = ["OBJECTID", "FACILITYID", "INSTALLDATE", "MATERIAL"] data = [list(row) for row in arcpy.da.SearchCursor(in_fc, in_fields)] arcpy.management.TruncateTable(out_fc) cursor = arcpy.da.InsertCursor(out_fc, out_fields) for row in data: if row[3] is None: cursor.insertRow(row) continue for value in split_field.split(", "): value = row[3] cursor.insertRow(row) print("Completed") Press Enter on the keyboard to execute the code in the Python window.