1

Let's say I have a dataframe df in the form:

| a,b,c,d |
|  e,f,g  |
|   h     |

But, using a comma delimiter, want to collapse the values into a single column dataframe like:

| a |
| b |
| c |
| d |
| e |
| f |
| g |
| h |

What's the most pythonic / Pandas-preferred solution to solving this in Python?

zthomas.nc
  • 3,689
  • 8
  • 35
  • 49

3 Answers3

3

You should use .explode():

df['col_1'] = df['col_1'].str.split(',')
df = df.explode('col_1')
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
1

if it's a data-frame with size=(3,4), the following line can solve it

pd.DataFrame(df.values.reshape(-1,1))
Mohammed Khalid
  • 155
  • 1
  • 6
0

The solution I came up with involves iterating over the rows of the dataframe:

new_list = []

for indx, row in table.iterrows():
  new_list += row[0].split(',')

new_df = pd.DataFrame(new_list)
zthomas.nc
  • 3,689
  • 8
  • 35
  • 49