There are different ways of creating a pandas data frame:
Creating using list
Creating using dictionary
Using arrays
Using zip()
Creating using list without index:
# Import pandas library
import pandas as pd
# initialize list of lists
data = [['A', 18, 'M'], ['B', 14, 'F'], ['C', 13, 'M']]
df = pd.DataFrame(data, columns = ['Name', 'Age', 'Gender'])
print(df)
Output:
Name Age Gender
0 A 18 M
1 B 14 F
2 C 13 M
Creating using list with index:
# Import pandas library
import pandas as pd
# initialize list of lists
data = [['A', 18, 'M'], ['B', 14, 'F'], ['C', 13, 'M']]
df = pd.DataFrame(data, columns = ['Name', 'Age', 'Gender'], index = ['row1', 'row2', 'row3'])
print(df)
Output:
Name Age Gender row1 A 18 M row2 B 14 F row3 C 13 M
Creating using dictionary:
Creating the data frame using the dictionary, all the array must be of the same length.
import pandas as pd
# intialise data of lists.
data = {'Job':['sofware Eng', 'IT consultant', 'Teacher'], 'Age':[27, 29, 30]}
# Create DataFrame
df = pd.DataFrame(data)
# Print the output.
print(df)
Output:
Job Age
0 sofware Eng 27
1 IT consultant 29
2 Teacher 30
Using arrays:
import pandas as pd
# initialise data of lists.
data = {'Name':['A', 'B', 'C', 'D'], 'Grade':['A+','B+', 'A', 'C']}
# Creates pandas DataFrame.
df = pd.DataFrame(data, index =['1', '2', '3', '4'])
print(df)
Output:
Name Grade
1 A A+
2 B B+
3 C A
4 D C
Using zip()
In this merge two lists using list(zip()) function and use.
#using dic
import pandas as pd
# List1
Name = ['A', 'B', 'C', 'D']
# List2
Age = [22, 18, 32, 27]
Gender = ['M', 'F', 'M', 'M']
# and merge them by using zip().
list_tuple = list(zip(Name, Age, Gender))
# Assign data to tuples.
list_tuple
#convert list into the pandas
df = pd.DataFrame(list_tuple, columns = ['Name', 'Age', 'Gender'])
# Print data.
print(df)
Output:
Name Age Gender 0 A 22 M 1 B 18 F 2 C 32 M 3 D 27 M
#pandashelp #pandasassignmenthelp #machinelearningassignmenthelp #python #pythonproject #machinelearning #machinelearninghomeworkhelp