J'ai deux listes 2D:
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
Je souhaite stocker ces valeurs dans un ensemble de données au format:
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]]
4 Réponses :
Utilisation de itertools.chain
Sortie: 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 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)
En utilisant np.concatenate aplatir la liste.
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
Sortie:
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})
Excellente réponse, comme celle-ci, je n'ai pas pensé à numpy moi-même ici.
Un moyen simple consiste à aplatir votre liste. Vous pouvez le faire avec la compréhension de liste (aucun module supplémentaire n'est nécessaire). Voici une discussion sur la façon pour aplatir une liste.
Voici le code:
# 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
L'approche la plus simple serait,
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
O / P:
pd.DataFrame(list(zip(sum(l1, []),sum(l2,[]))))
Explication, aplatir les deux dataframes et effectuez zipping enfin convertir en dataframe