用pandas中的向量列替换值a列

2024-09-28 05:18:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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. 

我能理解。在

所以问题是:怎么做?在


Tags: 数据函数示例pandasfor度量矢量错误
2条回答

这个例外来自这样一个事实:您想要在存储int的列(array)中插入list或{},Pandas和NumPy中的array不能有“参差不齐的形状”,因此一行不能有2个元素,其他行中不能有1个元素(可能除了使用遮罩)。在

要使其工作,您需要存储“通用”对象。例如:

import pandas as pd

df = pd.DataFrame({'col1' : [25, 12, 14, 21]})
df.col1[0] = [1, 2]
# ValueError: setting an array element with a sequence. 

但这是有效的:

^{pr2}$

注意:我不建议这样做,因为object列比特定类型的列慢得多。但是,由于使用for循环遍历列,因此似乎不需要这样的性能,所以也可以使用object数组。在


如果您希望它更快,您应该做的是将convert2vector函数矢量化,并将结果分配给两列:

import pandas as pd
import numpy as np

def convert2Vector(angle):
    """I don't know what your function does so this is just something that
    calculates the sin and cos of the input..."""
    ret = np.zeros((angle.size, 2), dtype=float)
    ret[:, 0] = np.sin(angle)
    ret[:, 1] = np.cos(angle)
    return ret

>>> df = pd.DataFrame({'col1' : [25, 12, 14, 21]})
>>> df['col2'] = [0]*len(df)
>>> df[['col1', 'col2']] = convert2Vector(df.col1)
>>> df
       col1      col2
0 -0.132352  0.991203
1 -0.536573  0.843854
2  0.990607  0.136737
3  0.836656 -0.547729

您应该调用一个像df.applydf.transform这样的一阶函数将创建一个新列,然后将其分配回:

In [1022]: df.col1.apply(lambda x: [x, x // 2])
Out[1022]: 
0    [25, 12]
1     [12, 6]
2     [14, 7]
3    [21, 10]
Name: col1, dtype: object 

在您的情况下,您可以:

^{pr2}$

相关问题 更多 >

    热门问题