Python Pandas-将numpy数组列表转换为单个列表?

Python Pandas-将numpy数组列表转换为单个列表?,python,numpy,Python,Numpy,当我尝试在我的机器学习项目中实现OneHotEncoding时,我使用以下代码对我的3个类别特征(工作、婚姻状况和教育)进行编码 这会将3个功能中每个功能的类别返回到列表中捕获的3个不同数组中 [array(['admin.', 'blue-collar', 'management', 'retired', 'self-employed', 'services', 'student', 'technician', 'unemployed', 'unknown'],

当我尝试在我的机器学习项目中实现OneHotEncoding时,我使用以下代码对我的3个类别特征(工作、婚姻状况和教育)进行编码

这会将3个功能中每个功能的类别返回到列表中捕获的3个不同数组中

[array(['admin.', 'blue-collar', 'management', 'retired', 'self-employed',
        'services', 'student', 'technician', 'unemployed', 'unknown'],
       dtype=object),
 array(['divorced', 'married', 'single'], dtype=object),
 array(['primary', 'secondary', 'tertiary', 'unknown'], dtype=object)]
我知道在这个列表中使用for循环可以返回3个列表,其中包含所有3个功能的标签

for value in feature_labels:
    print(value)

['admin.' 'blue-collar' 'management' 'retired' 'self-employed' 'services'
 'student' 'technician' 'unemployed' 'unknown']
['divorced' 'married' 'single']
['primary' 'secondary' 'tertiary' 'unknown']
也就是说,是否有一个更优雅的或一行,我可以合并创建一个列表,包含我的3个功能的所有不同类别?最后,我希望有一个列表,如下所示,这样我就可以将所有3个编码的功能导入到一个数据帧中

['admin.', 'blue-collar', 'management', 'retired', 'self-employed', 'services', 'student' ,'technician', 'unemployed', 'unknown', 'divorced', 'married', 'single', 'primary', 'secondary', 'tertiary', 'unknown']

如果您有嵌套列表:

l = [['admin.', 'blue-collar', 'management', 'retired', 'self-employed','services', 'student', 'technician', 'unemployed', 'unknown'],\
['divorced', 'married', 'single'], ['primary', 'secondary', 'tertiary', 'unknown']]
取消测试的方法之一是:

import itertools

flat_l  = list(itertools.chain(*l))
结果:

['admin.',
 'blue-collar',
 'management',
 'retired',
 'self-employed',
 'services',
 'student',
 'technician',
 'unemployed',
 'unknown',
 'divorced',
 'married',
 'single',
 'primary',
 'secondary',
 'tertiary',
 'unknown']

您可以使用numpy的连接来连接3个数组:()


由于您有一个numpy阵列列表,因此还可以使用:

import numpy as np

l = list(np.concatenate(feature_labels))

labels = np.concatenate(feature_labels)

# The result:
array(['admin.', 'blue-collar', 'management', 'retired', 'self-employed',
       'services', 'student', 'technician', 'unemployed', 'unknown',
       'divorced', 'married', 'single', 'primary', 'secondary',
       'tertiary', 'unknown'], dtype=object)
import numpy as np

l = list(np.concatenate(feature_labels))