Python: Create DataFrame from Dictionary. Add index, add columns to DataFrame

Publicado el: 02 marzo 2025
en el canal de: Brandan Jones
250
8

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


En esta página del sitio puede ver el video en línea Python: Create DataFrame from Dictionary. Add index, add columns to DataFrame de Duración hora minuto segunda en buena calidad , que subió el usuario Brandan Jones 02 marzo 2025, comparta el enlace con amigos y conocidos, en youtube este video ya ha sido visto 250 veces y le gustó 8 a los espectadores. Disfruta viendo!