Home > Enterprise >  How to join all columns in dataframe?
How to join all columns in dataframe?

Time:04-29

I would like one column to have all the other columns in the data frame combined.

here is what the dataframe looks like
  0   1   2
0 123 321 231
1 232 321 231
2 432 432 432

dataframe name = task_ba
I would like it to look like this
   0
0 123
1 232
2 432
3 321
4 321
5 432
6 231
7 231
8 432

CodePudding user response:

Easiest and fastest option, use the underlying numpy array:

df2 = pd.DataFrame(df.values.ravel(order='F'))

NB. If you prefer a series, use pd.Series instead

Output:

     0
0  123
1  232
2  432
3  321
4  321
5  432
6  231
7  231
8  432

CodePudding user response:

You can use pd.DataFrame.melt() and then drop the variable column:

>>> df
     0    1    2
0  123  321  231
1  232  321  231
2  432  432  432

>>> df.melt().drop("variable", axis=1)  # Drops the 'variable' column
   value
0    123
1    232
2    432
3    321
4    321
5    432
6    231
7    231
8    432

Or if you want 0 as your column name:

>>> df.melt(value_name=0).drop("variable", axis=1)
     0
0  123
1  232
2  432
3  321
4  321
5  432
6  231
7  231
8  432

You can learn all this (and more!) in the official documentation.

  • Related