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

how to combine list of row values and a list of column names with python pandas?

Suppose I’ve a list of data that contains multiple row values for multiple columns:

data = ['jack', 34, 'Sydney', 155 , 'Riti', 31, 'Delhi', 177.5 , 'Aadi', 16, 'Mumbai', 81 , 
        'Mohit', 31, 'Delhi', 167 , 'Veena', 12, 'Delhi', 144 , 'Shaunak', 35, 'Mumbai', 135 ,
        'Shaun', 35, 'Colombo', 111]

And I’ve another list that contains the name of columns:

columns = ['Name', 'Age', 'City', 'Score']

Now how can I merge these two lists into a single dataframe with pandas, like this?

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

expected output here

>Solution :

import pandas as pd

data = ['jack', 34, 'Sydney', 155, 'Riti', 31, 'Delhi', 177.5, 'Aadi', 16, 'Mumbai', 81, 'Mohit', 31, 'Delhi', 167,
        'Veena', 12, 'Delhi', 144, 'Shaunak', 35, 'Mumbai', 135, 'Shaun', 35, 'Colombo', 111]

columns = ['Name', 'Age', 'City', 'Score']
nnn = []
for i in range(0, len(data), 4):
    nnn.append(data[i:i + 4])

df = pd.DataFrame(nnn, columns=columns)

Output

      Name  Age     City  Score
0     jack   34   Sydney  155.0
1     Riti   31    Delhi  177.5
2     Aadi   16   Mumbai   81.0
3    Mohit   31    Delhi  167.0
4    Veena   12    Delhi  144.0
5  Shaunak   35   Mumbai  135.0
6    Shaun   35  Colombo  111.0
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