温馨提示:本文翻译自stackoverflow.com,查看原文请点击:pandas - Python: preprocess data in a format to mine for Association rules and frequent itemsets (apriori/SPA
pandas python

pandas - Python:以某种格式预处理数据以挖掘关联规则和频繁项集(Apriori / SPA

发布于 2020-03-29 21:30:22

我有一个包含245行和2列的格式的数据框,其中“ 唯一 ”列由列表组成:

df = (pd.DataFrame({'TC': ['101', '102', '103'], 
                    'Unique': [[189,113,213,201,125,211],   
                               [206,268,446,149,104,166],
                               [163,103,113,166,800,101]]}))

我想遍历数据框,并将“ 唯一”中的列表分解为单独的列,以便我可以对数据运行一些频繁的项集挖掘算法。 预期产量

TC     0   1    2    3    4     5

101   189  113  213  201  125  211 
102   206  268  446  149  104  166
103   163  103  113  166  800  101

另外,如果可能的话,我想按顺序创建所有唯一字段嵌套列表

unique=[[189,113,213,201,125,211 ],[206,268,446,149,104,166],[163,103,113,166,800,101]]

查看更多

提问者
Devarshi Goswami
被浏览
21
Dames 2020-01-31 18:28

创建一个嵌套列表:

nested_list = list(df['Unique'])

print(nested_list)
# Output:
[[189, 113, 213, 201, 125, 211],
 [206, 268, 446, 149, 104, 166],
 [163, 103, 113, 166, 800, 101]]

要创建所需的表,只需从此嵌套列表中创建一个新的DataFrame并将列TC添加为索引列

x = pd.DataFrame(nested_list)  # fills df with each nested list as a new column
x['TC'] = df['TC']             # add TC column
x = x.set_index('TC')          # set TC column as index to make it show as first column

print(x)

# Output:
       0    1    2    3    4    5
TC                               
101  189  113  213  201  125  211
102  206  268  446  149  104  166
103  163  103  113  166  800  101 2