将标量与熊猫系列连接

时间:2019-10-02 08:19:53

标签: python pandas

我想连接以下两个数据集。任何帮助将不胜感激。

第一数据total_pos

1170050176.9395077

第二个数据p

0    -0.000844
1    -0.002487
2    -0.004132
3    -0.006029
4    -0.004442
Length: 5, dtype: float64

我希望的输出:

0    1170050176.9395077
1    -0.000844
2    -0.002487
3    -0.004132
4    -0.006029
5    -0.004442
Length: 6, dtype: float64

我的代码:

p = np.concatenate([total_pos,p])

错误:

   p = np.concatenate([total_pos,p])
  ValueError: zero-dimensional arrays cannot be concatenated

3 个答案:

答案 0 :(得分:1)

或使用numpy.hstack

arr = np.hstack([total_pos, s])
# or into series
s = pd.Series(np.hstack([total_pos, s]))

输出:

array([ 1.17005018e+09, -8.44000000e-04, -2.48700000e-03, -4.13200000e-03,
       -6.02900000e-03, -4.44200000e-03])

答案 1 :(得分:0)

使用Series.append并将标量转换为一个元素Series

p = pd.Series([total_pos]).append(p, ignore_index=True)
print (p)
0    1.170050e+09
1   -8.440000e-04
2   -2.487000e-03
3   -4.132000e-03
4   -6.029000e-03
5   -4.442000e-03
dtype: float64

如果将标量转换为一个元素列表,您的解决方案将起作用:

a = np.concatenate([[total_pos],p])
print (a)
[ 1.17005018e+09 -8.44000000e-04 -2.48700000e-03 -4.13200000e-03
 -6.02900000e-03 -4.44200000e-03]

对于Series,请添加构造函数:

s = pd.Series(np.concatenate([[total_pos],p]))

答案 2 :(得分:0)

他们提出的两种解决方案都基于Series.append:将元素添加到系列中,但是必须是系列类型。

第一个解决方案:由@jezreal提出,附加忽略索引,以这种方式自动计算新元素的索引

第二种解决方法:请指定索引值:

s=pd.Series([11,22,33])
new_index = [str(s.index[-1] + 1) + 'b'] # you may need to specify a particular index for the new series, in this case calculate the value following the last index
s = s.append(pd.Series(44, index=new_index))

0     11
1     22
2     33
3b    44

如果要转换numpy数组中使用的序列,只需执行以下操作:

arr = np.array(s)
# output: array([11, 22, 33, 44])
相关问题