python - 你将如何重塑一个数组,遍历一列的所有行,并将重塑后的数组分配给一个新列?- 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() 方法,但这也不起作用(也许我实现错了)。
我应该如何处理这个?
解决方案
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)
推荐阅读
- java - 使用 Java 的 volatile 关键字的不一致
- c# - Httpclienthandler Webproxy 值没有改变
- c++ - 当例程“free”在 C++ 中的“try”块中失败时会发生什么
- bash - ${i%.*} 在这种情况下做了什么?
- c# - C# Devexpress 面板
- amazon-web-services - AWS 教育账户,但 Sage Maker 在训练模型时出错
- java - findAll(Pageable) 返回错误的排序顺序
- glsl - 关于鼠标位置的鱼眼扭曲 - 片段着色器
- android-animation - 应用的动画将视图移动到屏幕顶部
- react-native - Amazon S3 在 React Native 中显示来自 URL 的视频