0

I have an array of arrays that I want to combine with a data frame.

arrays=[np.array(i) for i in [[1,2],[5,6,7],[]]] #let me illustrate the arrays like this

df=pd.DataFrame({'Col':['x','y','z']})

Each array element corresponds to a row in the df. This is my desired output:

ht

Here is a way you could duplicate the df rows to accomodate the array elements going in:

df.loc[df.index.repeat([max(1,len(i)) for i in arrays])]

Thank you

3
  • Make a dataframe from the array. I believe pandas has many ways of joining frames. Commented Apr 14, 2020 at 20:51
  • I thought about that but I get the array elements listed within each row of that dataframe. I couldn't figure out how to stack them vertically into more rows. Commented Apr 14, 2020 at 20:52
  • What exactly is the issue? Please see How to Ask, help center. Also, please do not share information as images unless absolutely necessary. See: meta.stackoverflow.com/questions/303812/…, idownvotedbecau.se/imageofcode, idownvotedbecau.se/imageofanexception. Commented Apr 15, 2020 at 1:08

2 Answers 2

1

You could do the following:

import numpy as np
import pandas as pd
from itertools import product

arrays = [np.array(i) for i in [[1, 2], [5, 6, 7], []]]
df = pd.DataFrame({'Col': ['x', 'y', 'z']})

# this creates a mesh (cross-product) Dataframe
mesh = pd.DataFrame([pair for co in zip(df['Col'], arrays) for pair in product(*co)],
                    columns=['Col', 'n'])

# merge with the original Dataframe
result = df.merge(mesh, on='Col', how='left').fillna(0)

Output

  Col    n
0   x  1.0
1   x  2.0
2   y  5.0
3   y  6.0
4   y  7.0
5   z  0.0
Sign up to request clarification or add additional context in comments.

Comments

0
df=pd.DataFrame({'Col':['x','y','z']})

arrays=[i for i in [[1,2],[5,6,7],[]]] #let me illustrate the arrays like this

df['newcol']=arrays


df.explode('newcol')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.