【问题标题】:Python: how to add columns to a numpy array?Python:如何将列添加到 numpy 数组?
【发布时间】:2021-07-16 18:23:06
【问题描述】:

我有一个如下所示的数组

X
array([[ 0.93387437, -0.6063677 , -1.1959038 ],
       [ 0.53421287, -0.31532495, -1.06524933],
       [ 0.68792884,  0.34513742, -0.90179775],
       ...,
       [-0.41882609, -0.17155083,  1.14911752],
       [-0.04990778,  0.83636566,  0.92968195],
       [-0.48031247,  0.37908409,  1.00781703]])

在哪里

shape(X)
(1700, 3)

我有一个数据框df

    geometry                   data 20  30  40  50  60  80  90  126 200
0   POINT (-17.57616 14.87086)  200 0   0   0   0   0   0   0   0   1
1   POINT (-17.56784 14.87086)  200 0   0   0   0   0   0   0   0   1
2   POINT (-17.55952 14.87086)  200 0   0   0   0   0   0   0   0   1
3   POINT (-17.55119 14.87086)  200 0   0   0   0   0   0   0   0   1
4   POINT (-17.54287 14.87086)  200 0   0   0   0   0   0   0   0   1

shape(df1)
(1700, 11)

我想将列 [20, 30, 40, 50, 60, 80, 90, 126, 200] 添加到数组中。我尝试添加一列,但出现错误

a = np.array(df1.iloc[:,4])
X = np.hstack((X, a))
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)

【问题讨论】:

    标签: python arrays pandas dataframe numpy


    【解决方案1】:

    试试

    a = df.loc[:, 20:120].to_numpy()
    X = np.hstack((X, a))
    

    或者

    a = df.iloc[:, 2:].to_numpy()
    X = np.hstack((X, a))
    

    【讨论】:

    • 列名 '20' 看起来像一个字符串,它是 'int',请查看更新后的答案
    猜你喜欢
    • 1970-01-01
    • 2010-12-26
    • 2014-03-05
    • 2017-07-03
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 2016-02-27
    相关资源
    最近更新 更多