簡體   English   中英

如何從列表的python字典創建數據框?

[英]How to create a dataframe from a python dictionary of lists?

import pandas as pd

new_dict = {'mid': ['1', '2'], 'type': ['a', 'b']}

df = pd.DataFrame(new_dict.items(), columns=list(new_dict), index=None)

print(df)

這打印為:

mid    type
0   mid  [1, 2]
1  type  [a, b]

但我希望它打印為:

mid    type
1       a
2       b

那可能嗎?

--編輯:正如@DeepSpace 在對我的回答的評論中指出的那樣,您的錯誤在於將 new_dict.items() 函數結果作為數據傳遞,而不僅僅是 dict 本身。

保持簡單,如果你只是這樣做,而不需要指定列和索引參數,它可以工作:

new_dict = {"mid":["1","2"], "type":["a", "b"]}
df = pd.DataFrame(new_dict)
print(df)

這就是結果,我認為這就是你想要的:

  mid type
0   1    a
1   2    b

這里是為列和索引指定一些東西: new_dict = {"mid":["1","2"], "type":["a", "b"]} df = pd.DataFrame(new_dict ,列=列表(new_dict),索引=無)打印(df)

輸出:

  mid type
0   1    a
1   2    b

而且,如果您嘗試在不顯示索引的情況下打印 Dataframe,這似乎是您想要的輸出,您可以這樣做:

print(df.to_string(index=False))

mid type
  1    a
  2    b

暫無
暫無

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

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