Python Code in Jupyter summing each item, each month of 지출-액수.csv in SQLite

import sqlite3
import pandas as pd

# Define the path to your SQLite database
db_path = "/home/jbyungrokim/CSV/CSV.db"

# Connect to the SQLite database
conn = sqlite3.connect(db_path)

# Adjust the query to calculate the sum for each item by year and month
query = """
SELECT 
    strftime('%Y-%m', '20' || substr(Date_Transaction, 7, 2) || '-' || substr(Date_Transaction, 1, 2) || '-' || substr(Date_Transaction, 4, 2)) AS YearMonth,
    Item, 
    SUM(Pay_Amount) AS Total_Spent
FROM 
    '지출-액수_2024_08_20'
GROUP BY 
    YearMonth, Item
ORDER BY 
    YearMonth, Total_Spent DESC;
"""

# Execute the query and store the result in a pandas DataFrame
monthly_sum = pd.read_sql_query(query, conn)

# Reshape the data into a wide format for better readability in a spreadsheet
monthly_sum_wide = monthly_sum.pivot(index='Item', columns='YearMonth', values='Total_Spent').fillna(0)

# Export the data to a CSV file
output_path = "/home/jbyungrokim/CSV/monthly_sum_by_item_Jupyter.csv"
monthly_sum_wide.to_csv(output_path, index=True)

# Print the result
print("Sum of Pay_Amount by Item for each Year/Month:")
print(monthly_sum_wide)

# Close the connection to the SQLite database
conn.close()

Leave a Reply

Your email address will not be published. Required fields are marked *