熊猫数据框Python字典

时间:2019-10-12 01:03:55

标签: python pandas dataframe

我有两个python字典。

示例:

{
'hello' : 10
'phone' : 12
'sky' : 13
}

{
'hello' : 8
'phone' :15
'red' :4
}

这是分别在“ book1”和“ book2”书中的字数字典。

如何生成如下所示的pd数据框:

   hello phone  sky  red
book1 10    12     13   NaN
book2 8     15     NaN   4

我尝试过:

pd.DataFrame([words,counts])

它生成了:

    hello phone  sky  red
0     10    12     13   NaN
1      8    15     NaN   4 

如何生成所需的输出?

4 个答案:

答案 0 :(得分:1)

您需要这个:


pd.DataFrame([words, counts], index=['books1', 'books2'])

输出:

      hello phone  red  sky
books1  10   12    NaN  13.0
books2  8    15    4.0  NaN

答案 1 :(得分:1)

尝试以下代码,希望有帮助

dict1 = {
'hello' : 10,
'phone' : 12,
'sky' : 13
}

dict2 = {
'hello' : 8,
'phone' :15,
'red' :4
}


import pandas as pd
df = pd.DataFrame([dict1,dict2], index=['book1','book2'])
print(df)

输出将为:

       hello  phone   sky  red
book1     10     12  13.0  NaN
book2      8     15   NaN  4.0

答案 2 :(得分:0)

使用df.set_index([‘book1’, ‘book2’])。在此处查看文档:{​​{3}}

答案 3 :(得分:0)

假设您有词典列表,则可以执行以下操作:

import tkinter as tk


class Keep(tk.Tk):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.shared_data ={
            "email": tk.StringVar(),
            "password": tk.StringVar()
        }

        self.frames = {
            'StartPage': StartPage(self, self),
            'PageTwo': PageTwo(self, self),
        }

        self.current_frame = None
        self.show_frame('StartPage')

    def show_frame(self, name):
        if self.current_frame:
            self.current_frame.forget()
        self.current_frame = self.frames[name]
        self.current_frame.pack()

        self.current_frame.update_widgets() # <-- update data in widgets


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        super().__init__(parent)
        self.controller = controller

        self.entry1 = tk.Entry(self, textvariable=self.controller.shared_data["email"])
        self.entry1.pack()
        entry2 = tk.Entry(self, show='*')
        entry2.pack()
        button = tk.Button(self, text="Submit", command=lambda:controller.show_frame("PageTwo"))
        button.pack()

    def update_widgets(self):
        pass

class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        super().__init__(parent)
        self.controller = controller

        self.label = tk.Label(self, text="") # <-- create empty label
        self.label.pack()

    def update_widgets(self):
        self.label["text"] = "Welcome, {}".format(self.controller.shared_data["email"].get()) # <-- update text in label


if __name__ == "__main__":
    keep = Keep()
    keep.mainloop()

输出

import pandas as pd
from itertools import chain

data = [{
    'hello': 10,
    'phone': 12,
    'sky': 13,
},
    {
        'hello': 8,
        'phone': 15,
        'red': 4
    }]

df = pd.DataFrame(data=data, columns=set(chain.from_iterable(d.keys() for d in data)))
print(df)