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

时间:2017-08-25 08:49:42

标签: python arrays pandas dataframe

我使用python pandas在DataFrame中组织一些测量值。 其中一列是我想要在2D矢量中转换的值,所以让我们说该列包含这样的值:

 col1
 25
 12
 14
 21

我希望逐列更改此列的值(在for循环中):

for value in values:
    df.['col1'][value] = convert2Vector(df.['col1'][value])

以便列col1成为:

 col1
 [-1. 21.]
 [-1. -2.]
 [-15. 54.]
 [11. 2.]

值仅为示例,函数convert2Vector()将角度转换为2D矢量。

使用我写的for - 循环它不起作用..我收到错误:

ValueError: setting an array element with a sequence. 

我能理解。

所以问题是:怎么做?

2 个答案:

答案 0 :(得分:1)

您应该调用第一个订单函数,例如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 

在你的情况下,你会这样做:

df['col1'] = df.col1.apply(convert2vector)

答案 1 :(得分:0)

该异常来自于您希望在存储list的列(array)中插入arrayint这一事实。并且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. 

但这有效:

>>> df.col1 = df.col1.astype(object)
>>> df.col1[0] = [1, 2]
>>> df
     col1
0  [1, 2]
1      12
2      14
3      21

注意:我不建议这样做,因为object列比特定类型的列慢得多。但是,由于您使用for循环迭代Column,因此您似乎不需要性能,因此您也可以使用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