所以說我有一個輸入是字典串列:
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}]
每個字典基本上都是{x_1 : f(x_1), x_2: f(x_2),...}. 給定字典中有 m 個鍵值對,m 是固定的。
我希望我的輸出看起來像
# 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
如此概括它會是
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)
對于一個固定不變的 n,m 其中n=len(in)和m= len(in.keys())。我唯一能想到的就是pd.DataFrame.from_dict()在每個單獨的 dict 上使用,然后在pd.concat所有這些上使用。我想知道是否有更直接(和/或快速)的方式。
uj5u.com熱心網友回復:
你可以做:
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)
列印(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
如果您希望索引成為單獨的列,您可以執行以下操作:
df = df.reset_index().rename(columns={'index':'Index'})
uj5u.com熱心網友回復:
看看這是否有幫助
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())
然后,您可以隨心所欲地轉換 cols 和 index。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/492329.html
標籤:Python python-3.x 熊猫 数据框 字典
上一篇:我想從字典串列中獲取隨機選擇的鍵值,但出現型別錯誤。(注意串列很長,所以很難放置索引)
下一篇:用字典中的值替換串列中的專案
