การจัดการข้อมูลเบื้องต้นด้วย Pandas
..
👉การเปิดข้อมูล (Read Data)
import pandas as pd
#Read CSV file
df = pd.read_csv(r"C:\Users\user\Desktop\data_pandas.csv")
#Print results
print(df)
เมื่อรันโปรแกรมแล้วผลลัพท์ที่ได้
👉การแสดงขนาดของข้อมูล
import pandas as pd
#Read CSV file
df = pd.read_csv(r"C:\Users\user\Desktop\data_pandas.csv")
print(df.shape)
เมื่อรันโปรแกรมแล้วผลลัพท์ที่ได้
👉การจำกัดการแสดงข้อมูล
import pandas as pd
#Read CSV file
df = pd.read_csv(r"C:\Users\user\Desktop\data_pandas.csv")
df = df.head(2)
#Print results
print(df)
print(df.shape)
เมื่อรันโปรแกรมแล้วผลลัพท์ที่ได้
👉การเลือกคอลัมน์แสดงข้อมูล
import pandas as pd
#Read CSV file
df = pd.read_csv(r"C:\Users\user\Desktop\data_pandas.csv")
df = df.[['Value1','Value2']]
#Print results
print(df)
เมื่อรันโปรแกรมแล้วผลลัพท์ที่ได้
👉การกำหนดช่องของการแสดงข้อมูล
import pandas as pd
#Read CSV file
df = pd.read_csv(r"C:\Users\user\Desktop\data_pandas.csv")
df = df[['Value2','Value3']]
age_range = df.loc[(df['Value2'] >= 30) & (df['Value2'] <= 40), 'Value3']
print(age_range)
เมื่อรันโปรแกรมแล้วผลลัพท์ที่ได้
👉การจัดกลุ่มข้อมูล (GroupBy Data)
import pandas as pd
# Read CSV file
df = pd.read_csv(r"C:\Users\user\Desktop\data_pandas.csv")
# Group by 'Category' and sum the 'Value' column
grouped = df.groupby('Category')['Value'].sum()
# Print results
print(grouped)
เมื่อรันโปรแกรมแล้วผลลัพท์ที่ได้
👉การจัดกลุ่มข้อมูล (GroupBy Data) Table
import pandas as pd
import tkinter as tk
from tkinter import Tk, Frame, ttk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# Read CSV file
df = pd.read_csv(r"C:\Users\user\Desktop\data_GroupBy.csv") # Ensure the file path is correct
# Group by 'Category' and sum the 'Value' column
grouped = df.groupby('Category', as_index=False)['Value'].sum()
# Create Tkinter Window
root = Tk()
root.title("Grouped Data Display with Bar Graph")
root.geometry("1000x600")
# Set Treeview style
style = ttk.Style()
style.configure("Treeview", font=("Courier", 15, "bold"), rowheight=25)
style.configure("Treeview.Heading", font=("Courier", 15, "bold"))
# Create frame for table and scrollbar
frame = Frame(root, width=400, height=200) # Fixed frame size
frame.place(x=300, y=150) # Adjust x to center horizontally
frame.pack_propagate(False) # Prevent frame from shrinking
# Create Treeview
tree = ttk.Treeview(frame, columns=("Category", "Sum"), show="headings", height=5)
# Configure column headings
tree.heading("Category", text="Category", anchor="center")
tree.heading("Sum", text="Total Value", anchor="center")
# Configure column widths and alignment
tree.column("Category", anchor="center", width=200)
tree.column("Sum", anchor="center", width=200)
# Insert Data into Treeview
for index, row in grouped.iterrows():
tree.insert("", tk.END, values=(row["Category"], row["Value"]))
tree.pack(side=tk.TOP, fill="both", expand=True)
root.mainloop()
เมื่อรันโปรแกรมแล้วผลลัพท์ที่ได้
👉การจัดกลุ่มข้อมูล (GroupBy Data) Table + Bar Graph
import pandas as pd
import tkinter as tk
from tkinter import Tk, Frame, ttk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# Read CSV file
df = pd.read_csv(r"C:\Users\user\Desktop\data_GroupBy.csv") # Ensure the file path is correct
# Group by 'Category' and sum the 'Value' column
grouped = df.groupby('Category', as_index=False)['Value'].sum()
# Create Tkinter Window
root = Tk()
root.title("Grouped Data Display with Bar Graph")
root.geometry("1000x800")
# Set Treeview style
style = ttk.Style()
style.configure("Treeview", font=("Courier", 15, "bold"), rowheight=25)
style.configure("Treeview.Heading", font=("Courier", 15, "bold"))
# Create frame for table
frame = Frame(root, width=400, height=200)
frame.place(x=300, y=50)
frame.pack_propagate(False)
# Create Treeview
tree = ttk.Treeview(frame, columns=("Category", "Sum"), show="headings", height=5)
# Configure column headings
tree.heading("Category", text="Category", anchor="center")
tree.heading("Sum", text="Total Value", anchor="center")
# Configure column widths and alignment
tree.column("Category", anchor="center", width=200)
tree.column("Sum", anchor="center", width=200)
# Insert Data into Treeview
for index, row in grouped.iterrows():
tree.insert("", tk.END, values=(row["Category"], row["Value"]))
tree.pack(side=tk.TOP, fill="both", expand=True)
# -------------------- ADDING BAR GRAPH --------------------
# Create a Matplotlib figure
fig, ax = plt.subplots(figsize=(5, 4))
# Plot bar graph
ax.bar(grouped["Category"], grouped["Value"], color=["blue", "green", "red"])
# Set labels and title
ax.set_xlabel("Category")
ax.set_ylabel("Total Value")
ax.set_title("Category Wise Total Value")
# Embed Matplotlib figure in Tkinter
canvas = FigureCanvasTkAgg(fig, root)
canvas.get_tk_widget().place(x=240, y=300) # Adjust position below the table
canvas.draw()
root.mainloop()
เมื่อรันโปรแกรมแล้วผลลัพท์ที่ได้
👉การจัดกลุ่มข้อมูล (GroupBy Data) Table + PIE CHART
import pandas as pd
import tkinter as tk
from tkinter import Tk, Frame, ttk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# Read CSV file
df = pd.read_csv(r"C:\Users\user\Desktop\data_GroupBy.csv")
# Group by 'Category' and sum the 'Value' column
grouped = df.groupby('Category', as_index=False)['Value'].sum()
# Create Tkinter Window
root = Tk()
root.title("Grouped Data Display with Pie Chart")
root.geometry("1000x800")
# Set Treeview style
style = ttk.Style()
style.configure("Treeview", font=("Courier", 15, "bold"), rowheight=25)
style.configure("Treeview.Heading", font=("Courier", 15, "bold"))
# Create frame for table
frame = Frame(root, width=400, height=200)
frame.place(x=300, y=50)
frame.pack_propagate(False)
# Create Treeview
tree = ttk.Treeview(frame, columns=("Category", "Sum"), show="headings", height=5)
# Configure column headings
tree.heading("Category", text="Category", anchor="center")
tree.heading("Sum", text="Total Value", anchor="center")
# Configure column widths and alignment
tree.column("Category", anchor="center", width=200)
tree.column("Sum", anchor="center", width=200)
# Insert Data into Treeview
for index, row in grouped.iterrows():
tree.insert("", tk.END, values=(row["Category"], row["Value"]))
tree.pack(side=tk.TOP, fill="both", expand=True)
# -------------------- ADDING PIE CHART --------------------
# Create a Matplotlib figure
fig, ax = plt.subplots(figsize=(5, 5))
random_colors = ['red','green','blue']
# Pie chart with percentage labels
ax.pie(
grouped["Value"],
labels=grouped["Category"],
autopct="%1.1f%%",
colors=random_colors,
startangle=140
)
# Ensure the pie chart is circular
ax.axis("equal")
# Embed Matplotlib figure in Tkinter
canvas = FigureCanvasTkAgg(fig, root)
canvas.get_tk_widget().place(x=240, y=300) # Adjust position below the table
canvas.draw()
root.mainloop()
เมื่อรันโปรแกรมแล้วผลลัพท์ที่ได้
👉การแสดงข้อมูลจากไฟล์ DataLogger ในอุตสาหกรรม
import pandas as pd
import matplotlib.pyplot as plt
# Step 1: Read the CSV file into a DataFrame
df = pd.read_csv(r"C:\Users\user\Desktop\datalogger.csv")
# Step 2: Combine 'date' and 'time' columns into a single datetime column
# Adjust the year in the 'date' column
df['date'] = df['date'].apply(lambda x: x.replace('/2568', '/2025'))
# Step 3: Proceed with the rest of the code
df['datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'], format='%d/%m/%Y %H:%M:%S')
df.set_index('datetime', inplace=True)
# Step 4: Plot the data
plt.figure(figsize=(10, 6))
plt.plot(df.index, df['value1'], label='Value1')
plt.title('Value1 Over Time')
plt.xlabel('Date and Time')
plt.ylabel('Value1')
plt.legend()
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
เมื่อรันโปรแกรมแล้วผลลัพท์ที่ได้
👉การแสดงข้อมูลจากไฟล์ DataLogger ในอุตสาหกรรม
import pandas as pd
import matplotlib.pyplot as plt
# Step 1: Read the CSV file into a DataFrame
df = pd.read_csv(r"C:\Users\user\Desktop\datalogger.csv")
# Adjust the year in the 'date' column
df['date'] = df['date'].apply(lambda x: x.replace('/2568', '/2025'))
# Step 2: Combine 'date' and 'time' columns into a single datetime column
df['datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'], format='%d/%m/%Y %H:%M:%S')
# Step 3: Set the combined datetime column as the index
df.set_index('datetime', inplace=True)
# Step 4: Define the time range
start_time = pd.to_datetime('15:09:31', format='%H:%M:%S').time()
end_time = pd.to_datetime('15:09:45', format='%H:%M:%S').time()
# Step 5: Filter the data for the specified time range
filtered_df = df.between_time(start_time, end_time)
# Step 6: Plot the filtered data as a line chart
plt.figure(figsize=(10, 6))
plt.plot(filtered_df.index, filtered_df['value1'], label='Value1', marker='o')
# Customize the plot
plt.title('Value1 Over Time (15:09:30 to 15:09:40)')
plt.xlabel('Time')
plt.ylabel('Value1')
plt.legend()
plt.grid(True)
plt.xticks(rotation=45) # Rotate x-axis labels for better readability
# Show the plot
plt.tight_layout()
plt.show()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
เมื่อรันโปรแกรมแล้วผลลัพท์ที่ได้