Python: Dictionaries to Dataframe to Index
A hands on look at how to create a Dictionary, and then create a DataFrame from the Dictionary.
Add indices and columns to our Dataframe.
We create a dictionary with this syntax:
dictonaryName = {
"name1" : value1,
"name2" : value2
}
In dictionaries, values have to be unique.
We can print a single field by using this syntax:
print(dictionaryName['name1']
Find the number of elemnts with:
len(dictionaryName)
Create a collection assigned to a value with:
fieldName = {"index1":[1,2,3],
index2":[4,5,6],
index3":[7,8,9]}
To find the type of a column, use type(dictionrayName['columnName'])
To find the type of a single element of a collection, use type(dictionrayName['columnName'][0]), where 0 is the row you wish to select. This will find a value at the columnName and row collection.
To create a DataFrame from a Dictionary, use:
df = pd.DataFrame(dictionaryName)
Where pd is a reference to Pandas library, and df is the variable name that holds the new DataFrame.
To create an index and associate it with a DataFrame:
df.index=['2020','2021','2022','2023']
df.index.name="Measurement Year"
Be sure you have exactly one index value for each row in the collection!
If we want to append new rows, we can create a dictionary and a DataFrame from that dictionary. Then, use:
pd.concat([df, newDF], ignore_index=False, sort=False)
to append the new dataframe to the old dataframe. This will return a new DataFrame that is a combination of both.
To add one new column to the dataframe, we can use the syntax:
df['newColumnName'] = [1, 2, 3, 4, 5, 6]
If we wish to add multiple columns, we need to iterate:
key, value = newData.items()
for key,value in newData.items(): // let's shake hands with each of the new items. Ask for the value, and append to the dataframe
df[key] = value
#learningpython #pythondatastructures #dictionary #dataframe #index #columns #machinelearning #businessintelligence
On this page of the site you can watch the video online Python: Create DataFrame from Dictionary. Add index, add columns to DataFrame with a duration of hours minute second in good quality, which was uploaded by the user Brandan Jones 02 March 2025, share the link with friends and acquaintances, this video has already been watched 250 times on youtube and it was liked by 8 viewers. Enjoy your viewing!