python - 从列中的列表到行
问题描述
我有这个数据框
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
.
解决方案
方法一
一种方法是使用apply
+lambda
将Node
和TLW
列合并到一个列表中。然后使用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.unique
after 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
推荐阅读
- go - Go 通道未死锁或锁定
- debugging - VS Code 调试 golang。Delve 调试器
- css - 悬停多个项目后,鼠标悬停文本错位
- javascript - jwplayer 脚本中的 Access-Control-Allow-Origin 错误
- python - Python - 删除字典对的比例/百分比
- sql - 在不使用 CTE 的情况下选择分层数据
- excel - Excel 中的匹配函数返回 N/A
- php - 如何使用 AJAX、node.js 和 mysql 接收 JSON
- c# - 为什么 Xamarin Forms Maps 在 UWP 应用程序中崩溃?
- java - 如果实现不可用,如何实例化接口?