簡體   English   中英

從字典創建數據框的最佳方法是什么,其中字典鍵是元組:(索引,列)?

[英]What would be the best way of creating a dataframe from dictionary, where dict keys are tuples: (index, column)?

我有以下格式的字典:

 tuple_key_dict = {
     (0, 'Q2'): 0.41,
     (1, 'Q2'): 0.52,
     (2, 'Q2'): 0.61,
     (0, 'Q3'): 0.66,
     (1, 'Q3'): 0.53,
     (3, 'Q3'): 0.66,
     (0, 'Q4'): 0.47,
     (1, 'Q4'): 0.52,
     (2, 'Q4'): 0.67
          }

我還有一個列名列表:

interesting_columns=['Q2', 'Q3', 'Q4']

...並且知道索引在范圍內(0,1000)。 使用了所有列名稱和索引,但缺少一些組合(例如,在上面的示例中:(2,'Q2')。)

這里的工作是將所有這些都放在一個漂亮的數據框中,其中元組的第一個元素(鍵)是索引,第二個元素是列名(值是字典值)。 我嘗試了許多我什至不想在這里提及的方法 - 都失敗了:)

我假設您在寫缺少組合(2, 'Q2')時打錯了字,我將沒有值的單元格保留為 NaN。

代碼

tuple_key_dict = {
     (0, 'Q2'): 0.41,
     (1, 'Q2'): 0.52,
     (2, 'Q2'): 0.61,
     (0, 'Q3'): 0.66,
     (1, 'Q3'): 0.53,
     (3, 'Q3'): 0.66,
     (0, 'Q4'): 0.47,
     (1, 'Q4'): 0.52,
     (2, 'Q4'): 0.67
          }
columns = ["Q2", "Q3", "Q4"]
# our indexes are a set that contains all the first item of the keys
indexes = {key[0] for key in tuple_key_dict}
df = pd.DataFrame(index=indexes, columns=columns)
for key, value in tuple_key_dict.items():
     df.at[key[0], key[1]] = value
print(df)

輸出

     Q2    Q3    Q4
0  0.41  0.66  0.47
1  0.52  0.53  0.52
2  0.61   NaN  0.67
3   NaN  0.66   NaN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM