求和Numpy数组

2024-09-26 22:42:12 发布

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

我有一个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]

我发现我的做法是错误的,在同一个数组中改变类型

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


Tags: numpy元素类型so错误np数组array
2条回答

这对我来说很有效,不需要熊猫:

import numpy as np

a1 = [
    np.array(['2019-12-01', '0.03555', '0.03', '0.03', '0.03']),
    np.array(['2019-12-02', '0.03', '0.03', '1', '0.03'])
]

a2 = [
    np.array(['2019-12-01', '1', '1', '1', '1']),
    np.array(['2019-12-02', '1', '1', '1', '20'])
]

def array_adder(A, B):
    C = []
    for outer, outer2 in zip(A, B):
        temp = []
        if len(outer) == len(outer2):
            for inner, inner2 in zip(outer, outer2):
                if len(temp) < 1:
                    temp.append(inner)
                else:
                    temp.append(float(inner) + float(inner2))
            C.append(temp)
        else:
            print('Arrays must have the same length..')
            break
    return C

print(array_adder(a1, a2))

您可以通过将数组转换为以日期为索引的数据帧,并使用add来实现这一点:

import numpy as np
import pandas as pd

a1 = 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

相关问题 更多 >

    热门问题