首页 > 解决方案 > 从列中的列表到行

问题描述

我有这个数据框

Node                  TLW                            
1                  [2, 22, 3]                           
2                     [12]                              
3                    [2,43]                             
4                     [3]                             
5                     [11]  

                        

我想要这样的东西

Node
1
2
3
4
5
22
12
43
11

你能告诉我如何得到它吗?我会尝试在列表中使用 for 循环,然后附加到我的数据框,检查重复项。这将是我的方法,但我在这里使用 for 循环仍然有困难。我正在考虑使用explode,但输出不是我想要的,因为(不同的)数字(或字符串)应该在 columnNode中,而不是在TLW.

标签: pythonpandas

解决方案


方法一

一种方法是使用apply+lambdaNodeTLW列合并到一个列表中。然后使用explode并取一个unique(). 发布重新创建具有单列的数据框Node

d = {'Node': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},
     'TLW': {0: [2, 22, 3], 1: [12], 2: [2,43], 3: [3], 4: [11]}}
df = pd.DataFrame(d)

nodes = df.apply(lambda x: [x['Node']]+ x['TLW'], axis=1).explode().unique()
new_df = pd.DataFrame(nodes, columns=['Node'])
print(new_df)
  Node
0    1
1    2
2   22
3    3
4   12
5   43
6    4
7    5
8   11

方法二

另一种方法是使用 numpy's np.uniqueafter df.explode-

import numpy as np

d = {'Node': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},
     'TLW': {0: [2, 22, 3], 1: [12], 2: [2,43], 3: [3], 4: [11]}}
df = pd.DataFrame(d)


new_df = pd.DataFrame(np.unique(df.explode('TLW').values), columns=['Nodes'])
print(new_df)
  Nodes
0     1
1     2
2     3
3     4
4     5
5    11
6    12
7    22
8    43

推荐阅读