在pandas DataFrame列中使用多个条目(固定长度)存储项的最佳方法是什么?我在想一个像三维位置矢量的东西。例如,如果我的DataFrame存储有关一组物理对象的数据,它可能如下所示:
df = pandas.DataFrame({
'type': [1, 2, 1, 1, 3],
'mass': [1.1, 2.2, 3.3, 4.4, 5.5],
'pos': [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]],
'vel': [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]
})
# mass pos type vel
# 0 1.1 [1, 2, 3] 1 [1, 2, 3]
# 1 2.2 [4, 5, 6] 2 [4, 5, 6]
# 2 3.3 [7, 8, 9] 1 [7, 8, 9]
# 3 4.4 [10, 11, 12] 1 [10, 11, 12]
# 4 5.5 [13, 14, 15] 3 [13, 14, 15]在这里,列'pos'和'vel'是物体在三维空间中的位置和速度。
我想出了几种选择,其中没有一种似乎是理想的,甚至是可行的:
numpy数组分配给列,但不幸的是,pandas拒绝:
numpy.array([11,12,13,22,23,24,33,34,35,44,45,46,55,56,57]) df.loc:,' pos‘=pos## ValueError追尾(最近一次调用)# in () #' pos‘=pos## /opt/anaconda-3/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py in __setitem__(self,key,value) # 177 key = com._apply_if_callable(key,self.obj) # 178索引器= self._get_setitem_indexer(key) #-> 179 self._setitem_with_indexer(索引器,# 180 # 181 def _has_valid_type(self,k,axis):##_setitem_with_indexer中的##_setitem_with_indexer(自,索引器,值)# 561值=np.array(值,( dtype=object) # 562如果len (标签) != value.shape1:#-> 563引发ValueError(‘必须有相同的len键,值’# 564‘当用ndarray设置时’#564‘)# 565 ## ValueError:必须具有相同的len键和用ndarray设置的值。发布于 2018-08-29 13:18:34
我喜欢这个
d = pd.concat([
df[['mass', 'type']],
pd.DataFrame(df.pos.tolist(), df.index, ['x', 'y', 'z']),
pd.DataFrame(df.vel.tolist(), df.index, ['x', 'y', 'z'])
], axis=1, keys=['Scalar', 'Position', 'Velocity'])
d
Scalar Position Velocity
mass type x y z x y z
0 1.1 1 1 2 3 1 2 3
1 2.2 2 4 5 6 4 5 6
2 3.3 1 7 8 9 7 8 9
3 4.4 1 10 11 12 10 11 12
4 5.5 3 13 14 15 13 14 15您可以轻松地从顶层访问。
d.Velocity
x y z
0 1 2 3
1 4 5 6
2 7 8 9
3 10 11 12
4 13 14 15或者做数学
(d.Velocity + d.Position).div(d.Scalar.mass, axis=0)
x y z
0 1.818182 3.636364 5.454545
1 3.636364 4.545455 5.454545
2 4.242424 4.848485 5.454545
3 4.545455 5.000000 5.454545
4 4.727273 5.090909 5.454545您仍然可以轻松地访问适当的Numpy数组。
d.Position.values
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15]])发布于 2018-08-29 13:20:11
使用选项2:跨多个列以整数系列存储坐标。这是唯一对潘达斯有意义的选择。
您应该考虑的主要属性是结果系列的dtype。使用选项1,您将得到object系列,它只不过是一个指针序列。这可以与list一样很好地实现,并且您将失去执行矢量化计算的所有能力。
使用选项3,Pandas试图为单个系列分配一个NumPy数组序列时会感到困惑。这个错误本身就说明Pandas不是以这种方式设计的。
https://stackoverflow.com/questions/52078235
复制相似问题