Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Build a numpy array from the rows of two dataframe

I have two DataFrames, I want to choose each rows of each one and stick them together to build an array.

import pandas as pd
df = pd.DataFrame()
df ['a'] = [1, 2, 3]
df ['b'] = [4, 7, 1]

df1 = pd.DataFrame()
df1 ['a'] = [3, 7, 8]
df1 ['b'] = [9, 2, 1]

for example, I want to choose the row 1 from two data frame and build an array as:

array([[1, 3],
   [4, 9]]) 

or for row 3, the output should be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array([[3, 8],
   [1, 1]])

This is in a loop, and each time I need the array of each row.

>Solution :

You can use a simple approach as follow, the 2,2 size of the test is changed based on your df.

import numpy as np
test = np.zeros((2, 2))
test [0,:] = df.iloc[0,:]
test [1,:] = df1.iloc[0,:]
test = test.T

With a for loop, you can change the index of the df.iloc[i,:].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading