需要帮助才能将CSV文件的每一列转换为numpy数组

时间:2015-12-28 15:55:11

标签: python python-3.x numpy

我是一名PHP开发人员,并尝试在PYTHON中实现以下功能 我试图用numpy数组做一些操作。 我的输入来自具有多列的CSV文件。所以我正在读取文件并尝试为每列生成一个numpy数组,如下所示

我实际需要的格式是

[[  3.52173777]
 [  0.46194453]
 [  8.6932777 ]
 [ 15.18824896]
 [  2.15025082]
 [ 11.5823697 ]
 [ 11.23766709]
 [ 17.13780022]
 [ 19.7389633 ]
 [ 10.1521166 ]
 [ 11.68934389]
 [ 13.22986065]
 [  9.3644021 ]
 [ 16.38857516]
 [ 13.30463986]
 [  9.8830318 ]
 [ 18.68062207]
 [ 13.92522195]]

但我能够生成的格式是

['124.4444444' '123.6203091' '139.659803' '171.4285714' '188.6051081'
 '185.0220264' '163.141994' '119.0839695' '124.3027888' '160.6425703'
 '177.7777778' '154.8387097' '120.3438395' '149.8127341' '110.8545035'
 '111.8012422' '146.7889908' '151.4195584' '148.9361702' '163.1067961'
 '111.747851' '112.3110151' '174.1935484' '178.5123967' '144.8275862'
 '176.4705882' '173.9130435' '117.1548117' '111.4285714' '145.2145215'
 '169.0140845' '151.8987342' '151.4726508' '106.5989848' '116.2444113'
 '169.8113208' '156.5217391' '188.2352941' '190.8548708' '122.3449448'
 '118.4210526' '173.9130435' '162.1621622' '152.866242' '181.4744802'
 '130.2170284' '126.2135922' '151.5151515' '154.0436457' '174.1654572]

我正在尝试的代码

csvfile1 = sys.argv[1]
A_list = np.array([])
B_list = np.array([])
with open(csvfile1, newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',', lineterminator='\n')
    for row in spamreader:
        A_list = np.append(A_list, row[0])
        B_list = np.append(B_list, row[1])

print(A_list)
print(B_list)

1 个答案:

答案 0 :(得分:1)

只需将整个CSV读入单个矩阵,然后使用列切片获取所需的单个列:

>>> a = np.loadtxt('so34496620.csv', delimiter=',')
>>> a[:,0]    
array([ 124.4444444,  185.0220264,  177.7777778,  111.8012422,
        111.747851 ,  176.4705882,  169.0140845,  169.8113208,          
        118.4210526,  130.2170284])
>>> a[:,4]
array([ 188.6051081,  160.6425703,  110.8545035,  163.1067961,
        144.8275862,  145.2145215,  116.2444113,  122.3449448,
        181.4744802,  174.1654572])