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
0  0.551402  49
1  0.620870  34
2  0.535525  52
3  0.920922  13
4  0.708109  48
          r   s  t
0  0.231480  43  a
1  0.492576  10  b
          r   s    t
0  0.551402  49  NaN
1  0.620870  34  NaN
2  0.535525  52  NaN
3  0.920922  13  NaN
4  0.708109  48  NaN
0  0.231480  43    a
1  0.492576  10    b

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