How to convert a dictionary to a pandas DataFrame in Python
How to convert a dictionary to a pandas DataFrame in Python.
Here is a step-by-step tutorial on how to convert a dictionary to a pandas DataFrame in Python.
Step 1: Import the necessary libraries
First, you need to import the pandas library, which will be used for creating the DataFrame. You can also import other libraries if needed, such as numpy.
import pandas as pd
Step 2: Create a dictionary
Next, you need to create a dictionary that you want to convert into a DataFrame. The dictionary can have any structure, with keys representing column names and values representing column data.
data = {
'Name': ['John', 'Emma', 'Ryan'],
'Age': [25, 28, 32],
'City': ['New York', 'London', 'Paris']
}
Step 3: Convert the dictionary to a DataFrame
To convert the dictionary to a DataFrame, you can use the pd.DataFrame() function from the pandas library. Pass the dictionary as the argument to this function.
df = pd.DataFrame(data)
Step 4: Optional - Specify the column order
If you want to specify the order of the columns in the DataFrame, you can pass a list of column names to the columns parameter of the pd.DataFrame() function.
df = pd.DataFrame(data, columns=['Name', 'Age', 'City'])
Step 5: Optional - Add an index to the DataFrame
By default, pandas assigns a numeric index to the DataFrame. However, you can specify a custom index by passing a list of index values to the index parameter of the pd.DataFrame() function.
df = pd.DataFrame(data, index=['A', 'B', 'C'])
Step 6: View the DataFrame
To see the resulting DataFrame, simply print it.
print(df)
Here is the complete code:
import pandas as pd
data = {
'Name': ['John', 'Emma', 'Ryan'],
'Age': [25, 28, 32],
'City': ['New York', 'London', 'Paris']
}
df = pd.DataFrame(data)
print(df)
Output:
Name Age City
0 John 25 New York
1 Emma 28 London
2 Ryan 32 Paris
That's it! You have successfully converted a dictionary to a pandas DataFrame in Python.