Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Dataframe into Series?

I want to convert N columns into one series. How to do it effectively?

Input:

    0   1   2   3
0  64  98  47  58
1  80  94  81  46
2  18  43  79  84
3  57  35  81  31

Expected Output:

0     64
1     80
2     18
3     57
4     98
5     94
6     43
7     35
8     47
9     81
10    79
11    81
12    58
13    46
14    84
15    31
dtype: int64

So Far I tried:

print df[0].append(df[1]).append(df[2]).append(df[3]).reset_index(drop=True)

I'm not satisfied with my solution, moreover it won't work for dynamic columns. Please help me to find a better approach.

like image 836
Mohamed Thasin ah Avatar asked Dec 24 '22 03:12

Mohamed Thasin ah


2 Answers

You can use unstack

pd.Series(df.unstack().values)
like image 88
Mohamed Ali JAMAOUI Avatar answered Jan 15 '23 01:01

Mohamed Ali JAMAOUI


you need np.flatten

pd.Series(df.values.flatten(order='F'))

out[]
0     64
1     80
2     18
3     57
4     98
5     94
6     43
7     35
8     47
9     81
10    79
11    81
12    58
13    46
14    84
15    31
dtype: int64
like image 21
Vicky Avatar answered Jan 15 '23 02:01

Vicky