如何在Python中将ndarray转换为数组

时间:2018-08-28 21:35:17

标签: python arrays numpy numpy-ndarray

我有一个问题,我有以下几行:

s=codecs.open('file.csv', encoding="utf-8").read()
array1=np.asarray(s.splitlines())

print(array1)

我从数组中得到以下结果:

['39, State-gov, 77516, Bachelors, 13, Never-married, Adm-clerical, Not-in-family, White, Male, 2174, 0, 40, United-States, <=50K'
 '50, Self-emp-not-inc, 83311, Bachelors, 13, Married-civ-spouse, Exec-managerial, Husband, White, Male, 0, 0, 13, United-States, <=50K'
 '38, Private, 215646, HS-grad, 9, Divorced, Handlers-cleaners, Not-in-family, White, Male, 0, 0, 40, United-States, <=50K'
 ...
 '36, Private, 146311, 9th, 5, Married-civ-spouse, Machine-op-inspct, Husband, White, Male, 0, 0, 40, United-States, <=50K'
 '47, Self-emp-not-inc, 159869, Doctorate, 16, Married-civ-spouse, Craft-repair, Husband, White, Male, 0, 0, 50, United-States, <=50K'
 '21, Private, 204641, Some-college, 10, Never-married,']

我想要的是将其转换为:

[['39', 'State-gov', '77516', 'Bachelors', '13',....,'<=50K]['50'...]]

现在也是一个具有一行和多列的Array,并且在每一列中都是一个字符串,我想将每一列更改为一行,其中列数与字符数相同。.

我对此没有任何想法,我想将其拆分,但我不能

有人可以帮我吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

方法1:从文件生成所需的数组

如果您是从csv开始的,则最好使用np.genfromtxt

如果filename.csv如下:

39, State-gov, 77516, Bachelors, 13, Never-married, Adm-clerical, Not-in-family, White, Male, 2174, 0, 40, United-States, <=50K
50, Self-emp-not-inc, 83311, Bachelors, 13, Married-civ-spouse, Exec-managerial, Husband, White, Male, 0, 0, 13, United-States, <=50K

然后:

new_arr = np.genfromtxt('filename.csv', dtype='str')

>>> new_arr
array([['39,', 'State-gov,', '77516,', 'Bachelors,', '13,',
        'Never-married,', 'Adm-clerical,', 'Not-in-family,', 'White,',
        'Male,', '2174,', '0,', '40,', 'United-States,', '<=50K'],
       ['50,', 'Self-emp-not-inc,', '83311,', 'Bachelors,', '13,',
        'Married-civ-spouse,', 'Exec-managerial,', 'Husband,', 'White,',
        'Male,', '0,', '0,', '13,', 'United-States,', '<=50K']],
      dtype='<U19')

方法2:修复数组:

否则,如果您已有数组:

>>> arr
array(['39, State-gov, 77516, Bachelors, 13, Never-married, Adm-clerical, Not-in-family, White, Male, 2174, 0, 40, United-States, <=50K',
       '50, Self-emp-not-inc, 83311, Bachelors, 13, Married-civ-spouse, Exec-managerial, Husband, White, Male, 0, 0, 13, United-States, <=50K'],
      dtype='<U133')

您可以遍历它并拆分每个字符串以获得所需的输出:

new_arr = np.array([i.split() for i in arr])

>>> new_arr
array([['39,', 'State-gov,', '77516,', 'Bachelors,', '13,',
        'Never-married,', 'Adm-clerical,', 'Not-in-family,', 'White,',
        'Male,', '2174,', '0,', '40,', 'United-States,', '<=50K'],
       ['50,', 'Self-emp-not-inc,', '83311,', 'Bachelors,', '13,',
        'Married-civ-spouse,', 'Exec-managerial,', 'Husband,', 'White,',
        'Male,', '0,', '0,', '13,', 'United-States,', '<=50K']],
      dtype='<U19')