Sometimes, we want to create dataframe from a dictionary where entries have different lengths with Python Pandas.
in this article, we’ll look at how to create dataframe from a dictionary where entries have different lengths with Python Pandas.
How to create dataframe from a dictionary where entries have different lengths with Python Pandas?
To create dataframe from a dictionary where entries have different lengths with Python Pandas, we can use the DataFrame class with the dict.
For instance, we write
import pandas as pd
import numpy as np
d = dict(A = np.array([1,2]), B = np.array([1,2,3,4]))
df = pd.DataFrame(dict([ (k, pd.Series(v)) for k,v in d.items() ]))
to create a dict with the 2 arrays with
d = dict(A = np.array([1,2]), B = np.array([1,2,3,4]))
Then we use the DataFrame class with the dict by creating another dict that we get from the dict d by calling pd.Series with d‘s values.
Then we use the new dict as the argument of DataFrame to create the data frame.
The missing values will be set to NaN.
Conclusion
To create dataframe from a dictionary where entries have different lengths with Python Pandas, we can use the DataFrame class with the dict.