首页 > 解决方案 > 你将如何重塑一个数组,遍历一列的所有行,并将重塑后的数组分配给一个新列?- Python/熊猫/Numpy

问题描述

有多种迭代行和应用函数的方法。但是,我无法将其应用于我的具体案例。这是一个解释问题的简单表格:

    'Label'                    'Dimension'          'what I want'        
[12 323 345 235]                  (4,)                  (4,1)
[55 22 141 124 124]               (5,)                  (5,1)
[77 12 11]                        (3,)                  (3,1)

如果我要使用 1 个数组来实现这一点,它会是这样的:

label_ex = np.array([12,13,14,15])
label_ex.shape >> (4, )
label_ex = label_ex.reshape(len(label_ex), 1)
label_ex.shape >> (4, 1)

这是我尝试过的:

for index, row in samp.iterrows():
    samp.loc[index, 'label'] = samp.loc[index, 'label'].reshape(len(samp.loc[index, 'label']), 1)

不知何故,这是将我所有的数组转换为列表,然后显示错误

"AttributeError: 'list' object has no attribute 'shape'"

我尝试使用 df.column.apply() 方法,但这也不起作用(也许我实现错了)。

我应该如何处理这个?

标签: pythonarrayspandasnumpy

解决方案


df.apply()将工作。

df['New_Dimension'] = df['Label'].apply(lambda row : np.array(row).reshape(-1,1).shape)

>>>
    Label                        Dimension         New_Dimension      
[12, 323, 345, 235]                 (4,)                (4,1)
[55, 22, 141, 124, 124]             (5,)                (5,1)
[77, 12, 11]                        (3,)                (3,1)


推荐阅读