简体   繁体   中英

Split an numpy array into two numpy arrays

I have a numpy array like this:

A=[(datetime.datetime(2016, 6, 8, 12, 37, 27, 826000), 3.0)
   (datetime.datetime(2016, 6, 8, 12, 37, 27, 827000), nan)
   (datetime.datetime(2016, 6, 8, 12, 37, 27, 832000), nan)
   (datetime.datetime(2016, 6, 8, 12, 37, 27, 833000), nan)
   (datetime.datetime(2016, 6, 8, 12, 37, 27, 837000), 3.0)
   (datetime.datetime(2016, 6, 8, 12, 37, 27, 837000), 35.0)]

And I want to split it into 2 numpy arrays:

B=[(datetime.datetime(2016, 6, 8, 12, 37, 27, 826000),
  (datetime.datetime(2016, 6, 8, 12, 37, 27, 827000),
  (datetime.datetime(2016, 6, 8, 12, 37, 27, 832000),
  (datetime.datetime(2016, 6, 8, 12, 37, 27, 833000),
  (datetime.datetime(2016, 6, 8, 12, 37, 27, 837000), 
  (datetime.datetime(2016, 6, 8, 12, 37, 27, 837000)]

C=[3.0,nan,nan,nan,3.0,35.0]

To give you more details this numpy array was at first a dictionnary and I've convert it into a numpy array, you can find the code below:

def convertarray(dictionary):
    names=['id','data']
    formats=['datetime64[ms]','f8']
    dtype=dict(names=names, formats=formats)
    result=np.array(dictionary.items(),dtype)
    return result

If you just a have a vanilla array with dtype=object , I think your best recourse is to just construct the new arrays by iterating over the old one in a couple list-comprehensions:

import numpy as np from numpy import nan import datetime

A=np.array([(datetime.datetime(2016, 6, 8, 12, 37, 27, 826000), 3.0),
   (datetime.datetime(2016, 6, 8, 12, 37, 27, 827000), nan),
   (datetime.datetime(2016, 6, 8, 12, 37, 27, 832000), nan),
   (datetime.datetime(2016, 6, 8, 12, 37, 27, 833000), nan),
   (datetime.datetime(2016, 6, 8, 12, 37, 27, 837000), 3.0),
   (datetime.datetime(2016, 6, 8, 12, 37, 27, 837000), 35.0)])

print(A.dtype)

times = np.array([x[0] for x in A])
values = np.array([x[1] for x in A])

print(times)
print(values)

With that said, it might be slightly cleaner to use a record array:

import numpy as np
from numpy import nan
import datetime

A=np.array([(datetime.datetime(2016, 6, 8, 12, 37, 27, 826000), 3.0),
   (datetime.datetime(2016, 6, 8, 12, 37, 27, 827000), nan),
   (datetime.datetime(2016, 6, 8, 12, 37, 27, 832000), nan),
   (datetime.datetime(2016, 6, 8, 12, 37, 27, 833000), nan),
   (datetime.datetime(2016, 6, 8, 12, 37, 27, 837000), 3.0),
   (datetime.datetime(2016, 6, 8, 12, 37, 27, 837000), 35.0)],
   dtype=[('time', object), ('value', float)])

print(A.dtype)

print(A['time'])
print(A['value'])

You likely want to slice the data. Inserting a : for that dimension will select all elements of that dimension.

B = A[:, 0]
C = A[:, 1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM