Search code examples
pythonarrayspandasvectorizationseries

Vectorized way to copy elements from pandas Series to python built-in array


Is there a vectorized way to copy elements from a pandas Series to a python built-in array? For example:

from array import array
import pandas as pd
s = pd.Series(range(0, 10, 2)); s += 0.1
a = array('d', [0.0]*10)

# I am looking for a vectorized equivalent of the below line:
for n,x in enumerate(s): a[n] = x

In my case, the array is given as a memory buffer to an external code, which saves the array address and only re-reads array values upon each call. So, I cannot recreate the array and need to only replace its values as quickly as possible.

Thank you very much for your help!


Solution

  • from array import array
    import pandas as pd
    s = pd.Series(range(0, 10, 2)); s += 0.1
    a = array('d', [0]*10)
        
    temp = array('d',s) 
    a[:len(temp)] = temp