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 dictionary comprehension.
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]) )
pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in d.items() ]))
to create the dictionary d
that has the some values in it.
And then we use (k,pd.Series(v)) for k,v in d.items()
to return a dictionary with the same name on each column.
And then we use the returned dictionary with the DataFrame
class to create the data frame.
The empty values are filled with NaN.
Conclusion
To create dataframe from a dictionary where entries have different lengths with Python Pandas, we can use dictionary comprehension.