How to create a pandas DataFrame using a dictionary?

PandasServer Side ProgrammingProgramming

DataFrame is used to represent the data in two-dimensional data table format. Same as data tables, pandas DataFrames also have rows and columns and each column and rows are represented with labels.

By using the python dictionary we can create our own pandas DateFrame, here keys of the dictionary will become the column labels, and values will be the row data.

Here we will create a DataFrame using a python dictionary, Let’s see the below example.

Example

# importing the pandas package
import pandas as pd

data = {"int's":[1, 2, 3, 4],
"float's":[2.4, 6.67, 8.09, 4.3]}

# creating DataFrame
df = pd.DataFrame(data)

# displaying resultant DataFrame
print(df)

Explanation

The variable data has a python dictionary object with keys and value pair, here the keys of the dictionary are represented as column labels, and values of the dictionary are represented as row data in the resultant DataFrame.

In the given dictionary the keys have string data “int's, float's” and the values of the dictionary are loaded with list integer and float values.

Output

   int's   float's
0     1     2.40
1     2     6.67
2     3     8.09
3     4     4.30

The ‘df’ DataFrame object output is displayed in the above block, as we see that the column labels “int's, float's” are from dictionary keys and the values present in DataFrame are taken from dictionary values of the data variable.

Example

# importing the pandas package
import pandas as pd

data = {'B':'Black',
'W':'White',
'R':'Red',
'G':'Green'}

# creating DataFrame
df = pd.DataFrame(data, index=['Colors'])

# displaying resultant DataFrame
print(df)

Explanation

In this following example, the dictionary ‘data’ is having only scalar values so that we need to mention the index labels explicitly. If we haven’t mentioned the index values then it will rise “ValueError”. And the keys in the dictionary will become the column labels by default.

Output

          B     W   R     G
Colors Black White Red Green

The above DataFrame object has a single row and four columns.

raja
Updated on 17-Nov-2021 08:39:36

Advertisements