Skip to content Skip to sidebar Skip to footer

Concatenating Dictionaries Of Numpy Arrays (avoiding Manual Loops If Possible)

I am looking for a way to concatenate the values in two python dictionaries that contain numpy arrays whilst avoiding having to manually loop over the dictionary keys. For example:

Solution 1:

You can use pandas for that:

from __future__ import print_function, division
import pandas as pd
import numpy as np

# Create first dictionary
n = 5
s = np.random.randint(1,101,n)
r = np.random.rand(n)
d = {"r":r,"s":s}
df = pd.DataFrame(d)
print(df)

# Create second dictionary
n = 2
s = np.random.randint(1,101,n)
r = np.random.rand(n)
t = np.array(["a","b"])
d2 = {"r":r,"s":s,"t":t}
df2 = pd.DataFrame(d2)
print(df2)

print(pd.concat([df, df2]))

Outputs:

          r   s
00.5514024910.6208703420.5355255230.9209221340.70810948
          r   s  t
00.23148043  a
10.49257610  b
          r   s    t
00.55140249NaN10.62087034NaN20.53552552NaN30.92092213NaN40.70810948NaN00.23148043    a
10.49257610    b

Post a Comment for "Concatenating Dictionaries Of Numpy Arrays (avoiding Manual Loops If Possible)"