对 Numpy 数组求和

我有一个形式的numpy数组:


np.Array1 = 


[

   ['2019-12-01' '0.03555' '0.03' '0.03' '0.03'],

   ['2019-12-02' '0.03' '0.03' '1' '0.03']

]

第二个:


np.Array2 = 


[

   array(['2019-12-01', '1', '1', '1', '1']),

   array(['2019-12-02', '1', '1', '1', '20'])

]

有没有办法让我这样做:


对每个元素求和npArray1.col1 = npArray2.col1- 即:当日期相同时,逐个元素添加元素(不包括日期)


'2019-12-01' = '2019-12-01' so [0.03555+1, 0.03+1, 0.03+1, 0.03+1]


我知道我可能会以错误的方式解决这个问题,通过改变同一个数组中的类型


任何关于基于条件逻辑添加值的更好方法的建议都值得赞赏。


明月笑刀无情
浏览 111回答 2
2回答

沧海一幻觉

您可以通过将数组转换为以日期为索引的 pandas 数据框并使用add:import numpy as npimport pandas as pda1 = np.array( [['2019-12-01', '0.03555', '0.03', '0.03', '0.03'],                ['2019-12-02', '0.03', '0.03', '1', '0.03']] )a2 = np.array([['2019-12-01', '1', '1', '1', '1'],               ['2019-12-02', '1', '1', '1', '20']])# convert to dataframe and set the date as the index# also convert to floats:df1 = pd.DataFrame(a1).set_index(0).astype(float)df2 = pd.DataFrame(a2).set_index(0).astype(float)df1.add(df2, fill_value = 0)然后,您可以通过转换回字符串、重置索引并获取值来将其作为原始格式的 numpy 数组取回:df1.add(df2, fill_value = 0).astype(str).reset_index().values

皈依舞

这对我有用,它不需要熊猫:import numpy as npa1 = [&nbsp; &nbsp; np.array(['2019-12-01', '0.03555', '0.03', '0.03', '0.03']),&nbsp; &nbsp; np.array(['2019-12-02', '0.03', '0.03', '1', '0.03'])]a2 = [&nbsp; &nbsp; np.array(['2019-12-01', '1', '1', '1', '1']),&nbsp; &nbsp; np.array(['2019-12-02', '1', '1', '1', '20'])]def array_adder(A, B):&nbsp; &nbsp; C = []&nbsp; &nbsp; for outer, outer2 in zip(A, B):&nbsp; &nbsp; &nbsp; &nbsp; temp = []&nbsp; &nbsp; &nbsp; &nbsp; if len(outer) == len(outer2):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for inner, inner2 in zip(outer, outer2):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if len(temp) < 1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; temp.append(inner)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; temp.append(float(inner) + float(inner2))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; C.append(temp)&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print('Arrays must have the same length..')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; return Cprint(array_adder(a1, a2))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python