Issue
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?
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
Answered By - inquirer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.