Python 从两个2D列表中提取值,并将其存储到熊猫数据框中
我有两个2D列表:Python 从两个2D列表中提取值,并将其存储到熊猫数据框中,python,pandas,list,Python,Pandas,List,我有两个2D列表: 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 Supp
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
使用itertools.chain
例:
输出:
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
使用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
一个简单的方法是将列表展平。
你可以通过列表理解来完成,不需要额外的模块。这是一个关于如何展平列表的讨论
代码如下:
# 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
最简单的方法是
pd.DataFrame(list(zip(sum(l1, []),sum(l2,[]))))
O/p:
解释,展平两个数据帧并执行压缩最终转换为数据帧很好的答案,就像这个,我在这里没有想到numpy。
pd.DataFrame(list(zip(sum(l1, []),sum(l2,[]))))
0 1
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