我有两个二维列表:
1. [['VDM:1', 'VDM:2', 'VDM:3', 'VDM:4', 'VDM:5'], ['MDM:1', 'MDM:2', 'MDM:3', 'MDM:4', 'MDM:5'], ['OM:1', 'OM:2', 'OM:3', 'OM:4', 'OM:5']]
2. [[9, 2, 0, 0, 1], [2, 6, 0, 3, 1], [2, 6, 0, 3, 1]]
我想以以下格式将这些值存储在数据集中:
Attribute:Value Support
VDM:1 9
VDM:2 2
VDM:3 0
VDM:4 0
VDM:5 1
MDM:1 2
MDM:2 6
MDM:3 0
MDM:4 3
MDM:5 1
OM:1 2
OM:2 6
OM:3 0
OM:4 3
OM:5 1
发布于 2019-06-10 09:37:15
使用itertools.chain
Ex:
import pandas as pd
from itertools import chain
Attribute = [['VDM:1', 'VDM:2', 'VDM:3', 'VDM:4', 'VDM:5'], ['MDM:1', 'MDM:2', 'MDM:3', 'MDM:4', 'MDM:5'], ['OM:1', 'OM:2', 'OM:3', 'OM:4', 'OM:5']]
Support = [[9, 2, 0, 0, 1], [2, 6, 0, 3, 1], [2, 6, 0, 3, 1]]
df= pd.DataFrame({"Attribute:Value": list(chain.from_iterable(Attribute)), "Support": list(chain.from_iterable(Support))})
print(df)
输出:
Attribute:Value Support
0 VDM:1 9
1 VDM:2 2
2 VDM:3 0
3 VDM:4 0
4 VDM:5 1
5 MDM:1 2
6 MDM:2 6
7 MDM:3 0
8 MDM:4 3
9 MDM:5 1
10 OM:1 2
11 OM:2 6
12 OM:3 0
13 OM:4 3
14 OM:5 1
发布于 2019-06-10 09:43:16
使用np.concatenate
可以使列表变平。
a = [['VDM:1', 'VDM:2', 'VDM:3', 'VDM:4', 'VDM:5'], ['MDM:1', 'MDM:2', 'MDM:3', 'MDM:4', 'MDM:5'], ['OM:1', 'OM:2', 'OM:3', 'OM:4', 'OM:5']]
s = [[9, 2, 0, 0, 1], [2, 6, 0, 3, 1], [2, 6, 0, 3, 1]]
a = np.concatenate(a)
s = np.concatenate(s)
df = pd.DataFrame({'Attribute:value': a, 'Support': s})
输出:
Attribute:value Support
0 VDM:1 9
1 VDM:2 2
2 VDM:3 0
3 VDM:4 0
4 VDM:5 1
5 MDM:1 2
6 MDM:2 6
7 MDM:3 0
8 MDM:4 3
9 MDM:5 1
10 OM:1 2
11 OM:2 6
12 OM:3 0
13 OM:4 3
14 OM:5 1
发布于 2019-06-10 09:47:23
一种简单的方法是将压缩到列表中。您可以使用列表理解(不需要额外的模块)来完成它。Here是关于如何扁平列表的讨论之一。
在这里,代码:
# Import module
import pandas as pd
# Your data
attributs = [['VDM:1', 'VDM:2', 'VDM:3', 'VDM:4', 'VDM:5'], [
'MDM:1', 'MDM:2', 'MDM:3', 'MDM:4', 'MDM:5'], ['OM:1', 'OM:2', 'OM:3', 'OM:4', 'OM:5']]
support = [[9, 2, 0, 0, 1], [2, 6, 0, 3, 1], [2, 6, 0, 3, 1]]
# Flatten the list
attributs_flatten = [item for sublist in attributs for item in sublist]
support_flatten = [item for sublist in support for item in sublist]
# create dataframe
df = pd.DataFrame({'Attributes:Value': attributs_flatten, "Support": support_flatten})
print(df)
# Attributes:Value Support
# 0 VDM: 1 9
# 1 VDM: 2 2
# 2 VDM: 3 0
# 3 VDM: 4 0
# 4 VDM: 5 1
# 5 MDM: 1 2
# 6 MDM: 2 6
# 7 MDM: 3 0
# 8 MDM: 4 3
# 9 MDM: 5 1
# 10 OM: 1 2
# 11 OM: 2 6
# 12 OM: 3 0
# 13 OM: 4 3
# 14 OM: 5 1
https://stackoverflow.com/questions/56523806
复制相似问题