create a dataframe from a dictionnary with different index values length and fill with nan in python

To create a DataFrame from a dictionary with different length index values and fill with NaN values, we can use the from_dict method of the pandas DataFrame class. We can pass the dictionary to this method, and set the orient parameter to 'index' to specify that each key in the dictionary represents an index label for the DataFrame.

By default, the from_dict method will fill missing values with NaN. Therefore, if the dictionary has varying lengths, the DataFrame will be populated with NaN values for missing keys.

Here is an example code snippet that demonstrates how to create a DataFrame with varying length index values and NaN values:

main.py
import pandas as pd

my_dict = {
    'index1': [1, 2, 3],
    'index2': [4, 5],
    'index3': [6, 7, 8, 9]
}

df = pd.DataFrame.from_dict(my_dict, orient='index')

print(df)
174 chars
12 lines

Output:

main.py
       0    1    2    3
index1  1.0  2.0  3.0  NaN
index2  4.0  5.0  NaN  NaN
index3  6.0  7.0  8.0  9.0
105 chars
5 lines

Notice that the resulting DataFrame has NaN values in the locations where the original dictionary did not have values.

gistlibby LogSnag