ihsansat ihsansat - 3 months ago 13
Python Question

Combine value of two column pandas into one

I have data, and have to use pandas for processing, this is example the code:

d = [
(1,70399,0.988375133622),
(1,33919,0.981573492596),
(1,62461,0.981426807114),
(579,1,0.983018778374),
(745,1,0.995580488899),
(834,1,0.980942505189)
]

df = pd.DataFrame(d, columns=['source', 'target', 'weight'])
source_old = df.source.copy()

>>> source_old
source_old
0 1
1 1
2 1
3 579
4 745
5 834


but i need source_old contain
target
too, like:

0 1
1 1
2 1
3 579
4 745
5 834
6 33919
7 62461
8 70399


how can i do that with pandas ?
thx

Answer
df[['source', 'target']].T.stack()

source  0        1
        1        1
        2        1
        3      579
        4      745
        5      834
target  0    70399
        1    33919
        2    62461
        3        1
        4        1
        5        1
dtype: int64

or

pd.concat([df[col] for col in ['source', 'target']])

0        1
1        1
2        1
3      579
4      745
5      834
0    70399
1    33919
2    62461
3        1
4        1
5        1
dtype: int64

or

to get precisely what you asked for

pd.concat([df['source'], df['target'].iloc[:3]], ignore_index=True)

0        1
1        1
2        1
3      579
4      745
5      834
6    70399
7    33919
8    62461
dtype: int64
Comments