So say I have an input which is a list of dictionaries:
in: List[Dict[Decimal, Decimal]] = [{0: 0.05, 0.5: 0.15, 1: 0.1}, {0: 0.06, 0.5: 0.14, 1: 0.2}, {0: 0.09, 0.5: 0.25, 1: 0.17}]
Each dictionary is basically {x_1 : f(x_1), x_2: f(x_2),...}
. There are m key-value pairs in a given dictionary, m is fixed.
I want my output to look like
# Index | Dict 1 | Dict 2 | Dict 3
# 0 0.05 0.06 0.09
# 0.5 0.15 0.14 0.25
# 1 0.1 0.2 0.17
So generalised it would be
Index | Col 1 | Col 2 | ... | Col n
x_1 | f_1(x_1)| f_2(x_1)| ... | f_n(x_1)
x_2 | f_1(x_2)| f_2(x_2)| ... | f_n(x_2)
... ... ... ... ...
x_m | f_1(x_m)| f_2(x_m)| ... | f_n(x_m)
For a fixed and constant n,m where n=len(in)
and m= len(in.keys())
.
The only thing I could think from is to use pd.DataFrame.from_dict()
on each individual dict and then pd.concat
all of them. I was wondering if there is a more straightforward (and/or fast) way.
CodePudding user response:
See if this helps
import pandas as pd
l=[{0: 0.05, 0.5: 0.15, 1: 0.1}, {0: 0.06, 0.5: 0.14, 1: 0.2}, {0: 0.09, 0.5: 0.25, 1: 0.17}]
df=pd.DataFrame(l)
cols=df.columns
df.set_index(cols,inplace=True)
print(df.head())
You can then transform the cols and index however you like.
CodePudding user response:
You can do:
dict_list = [{0: 0.05, 0.5: 0.15, 1: 0.1}, {0: 0.06, 0.5: 0.14, 1: 0.2}, {0: 0.09, 0.5: 0.25, 1: 0.17}]
df = pd.DataFrame(dict_list).T
df.columns = (df.columns 1).map('Dict{}'.format)
print(df):
Dict1 Dict2 Dict3
0.0 0.05 0.06 0.09
0.5 0.15 0.14 0.25
1.0 0.10 0.20 0.17
If you want index to be a separate column you can do:
df = df.reset_index().rename(columns={'index':'Index'})