我使用python pandas在数据帧中组织一些度量值。 其中一列是一个值,我想在二维向量中转换,所以假设该列包含这样的值:
col1
25
12
14
21
我想逐个更改此列的值(在for循环中):
^{pr2}$使列col1
变成:
col1
[-1. 21.]
[-1. -2.]
[-15. 54.]
[11. 2.]
这些值只是示例,convert2Vector()
函数将角度转换为二维矢量。在
我写的for
-循环不起作用。。我得到了一个错误:
ValueError: setting an array element with a sequence.
我能理解。在
所以问题是:怎么做?在
这个例外来自这样一个事实:您想要在存储},Pandas和NumPy中的
int
的列(array
)中插入list
或{array
不能有“参差不齐的形状”,因此一行不能有2个元素,其他行中不能有1个元素(可能除了使用遮罩)。在要使其工作,您需要存储“通用”对象。例如:
但这是有效的:
^{pr2}$注意:我不建议这样做,因为
object
列比特定类型的列慢得多。但是,由于使用for
循环遍历列,因此似乎不需要这样的性能,所以也可以使用object
数组。在如果您希望它更快,您应该做的是将
convert2vector
函数矢量化,并将结果分配给两列:您应该调用一个像
df.apply
或df.transform
这样的一阶函数将创建一个新列,然后将其分配回:在您的情况下,您可以:
^{pr2}$相关问题 更多 >
编程相关推荐