python使用pandas实现csv文件的读取

358 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第15天,点击查看活动详情

在办公方面excel的功能已经非常强大了,数据统计、绘图分析等等,拥有非常多的功能,但是为了方便数据的操作,python也提供了专门的库函数用于对csv文件进行操作,其中pandas就是其中之一。

一般对于数据的操作还会涉及一些科学运算,所以pandas经常与numpy一起使用,下面就是非常简单一个示例,使用pandas读取csv文件

df = pd.read_csv("file.csv")

读取过程就是这么简单,python将其中的操作都已经封装好,我们只需要调用即可。

而且pandas可以直接对列名进行操作,例如打开csv文件后,我们不需要载入全部列,所以我们可以使用drop函数将指定的列名丢弃。

df = df.drop(columns=['col_name1','col_name2'])

同时也支持取单列或者多列数据,例如

data = df['col_name1']

也支持获取指定行和列的数据,例如获取名字为col1-4列的前四行数据

df.loc[df.index[0:4], ['col1', 'col2', 'col3', 'col4']]

如果想要按照某一列或者某几列的排序数据,pandas也提供了函数,表示先按照col1列的值进行排序,如果相同再按照clo2的值进行排序

df.sort_values(by=['col1', 'col2'])

而且直接读取csv的数据使用matplotlib绘图也很方便

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("file.csv")
df = df.drop(columns=['Program Title', 'Program Network'])
df = df.groupby(['Program Genre', 'Viewer Hometown'], as_index=False).agg({'Number of Viewers': 'sum'})
df.pivot(index='Program Genre', columns='Viewer Hometown', values='Number of Viewers').plot(kind='bar')
plt.show()

image.png

上面几行代码就可以将csv里面的数据以表格形式进行展现。

利用tkinter可制作简单的csv统计工具,可以显示csv里面的内容,也可以实现简单的统计功能。

import pandas as pd, tkinter as tk, os
from tkinter import filedialog as fd


class CSVReader:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title('CSV FILE READER')
        sw, sh = int(self.root.winfo_screenwidth()*.5), int(self.root.winfo_screenheight()*.7)
        self.root.geometry('{w}x{h}'.format(w=sw, h=sh))
        self.root.resizable(0, 0)
        self.root.rowconfigure(0, weight=1), self.root.columnconfigure(0, weight=1)
        self.startpage()
        self.root.mainloop()

    def startpage(self):
        bg = 'green'
        frame = tk.Frame(self.root, bg=bg)
        self.menupage(widg=frame)

    def menupage(self, widg):
        bg = 'purple'
        widg.grid_forget()
        self.root.geometry('170x50')
        frame = tk.Frame(self.root, bg=bg)
        frame.grid(sticky='nsew')
        frame.rowconfigure(1, weight=1), frame.columnconfigure(0, weight=1)
        tk.Label(frame, text='Choose CSV File', bg=bg, fg='white').grid(sticky='ew')
        btn = tk.Button(frame, text='Open', bg='white', fg='green',
                  command=self.file_opener)
        btn.grid(row=0, column=1, sticky='ew', padx=4, pady=4)
        btn.bind('<Enter>', lambda event: btn.config(bg='yellow'))
        btn.bind('<Leave>', lambda event: btn.config(bg='white'))

    def file_opener(self):
        fp = fd.askopenfilename(initialdir=os.getcwd(), filetypes=[('CSV FILES', '*.csv')])
        print('Selected File:\t{}'.format(fp))
        self.csv_reader(fp)

    def csv_reader(self,  file_path, old_window=None):
        if old_window:
            old_window.destroy()
        bg = 'gold'
        fn = file_path.split('/')[-1]
        print(fn)
        win = tk.Toplevel()
        win.title(fn)
        sw, sh = int(self.root.winfo_screenwidth()*.5), int(self.root.winfo_screenheight()*.7)
        win.geometry('{w}x{h}'.format(w=sw, h=sh))
        win.resizable(0, 0)
        win.rowconfigure(0, weight=1), win.columnconfigure(0, weight=1)
        df = pd.read_csv(filepath_or_buffer=file_path)
        frame = tk.Frame(win, bg=bg)
        frame.grid(sticky='nsew')
        frame.rowconfigure(0, weight=1), frame.columnconfigure(0, weight=1)
        tk.Label(frame, text='FILE CONTENT:\n{}'.format(df), bg=bg, fg='black', font=('calibri', 12)).grid(sticky='nsew')
        info_btn = tk.Button(frame, text='Check Info', bg='blue', fg='white', command=lambda: self.disp_info(win, df, file_path))
        info_btn.grid(row=1, column=1)
        info_btn.bind('<Enter>', lambda event: info_btn.config(bg='pink'))
        info_btn.bind('<Leave>', lambda event: info_btn.config(bg='blue'))

    def disp_info(self, old_window, dataframe, file_path):
        old_window.destroy()
        bg = 'gold'
        fn = file_path.split('/')[-1]
        print(fn)
        win = tk.Toplevel()
        win.title(fn)
        sw, sh = int(self.root.winfo_screenwidth() * .5), int(self.root.winfo_screenheight() * .7)
        win.geometry('{w}x{h}'.format(w=sw, h=sh))
        win.resizable(0, 0)
        win.rowconfigure(0, weight=1), win.columnconfigure(0, weight=1)
        frame = tk.Frame(win, bg=bg)
        frame.grid(sticky='nsew')
        frame.rowconfigure(0, weight=1), frame.columnconfigure(0, weight=1)
        tk.Label(frame,
                 text=f'CONTENT INFO:\nDataFrame Contains {dataframe.shape[0]} rows/indices and {dataframe.shape[1]} columns\n\n'
                      f'EXPLORATORY DATA ANALYSIS:\n{dataframe.describe().transpose()}',
                 bg=bg,
                 fg='black',
                 font=('calibri', 12)).grid(sticky='nsew')
        back_btn = tk.Button(frame, text='Back', bg='brown', fg='white', command=lambda: self.csv_reader(file_path, win))
        back_btn.grid(row=1)
        back_btn.bind('<Enter>', lambda event: back_btn.config(bg='pink'))
        back_btn.bind('<Leave>', lambda event: back_btn.config(bg='brown'))


if __name__ == '__main__':
    CSVReader()

image.png

image.png

最后的统计结果可以结合上面使用matplotlib的方式展示到tkinter界面中,这里就不进行合成了,需要的自己构建函数实现一下。