Skip to main content
 首页 » 编程设计

python之将两列 Pandas 的值(value)合并为一个

2025年05月04日25luoye11

我有数据,必须使用 pandas 进行处理,这是示例代码:

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 

但我也需要 source_old 包含 target,例如:

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

我怎样才能用 pandas 做到这一点? 谢谢

请您参考如下方法:

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 

或

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 

或

准确地得到你所要求的

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