상세 컨텐츠

본문 제목

SQL to PANDAS

TIL

by 30303 2024. 3. 10. 21:54

본문

728x90

문제 1.

각 카테고리별로 가장 비싼 제품의 이름과 가격 조회

#SQL
SELECT Category, ProductName, MAX(Price) AS HighestPrice
FROM Products
GROUP BY Category
ORDER BY HighestPrice DESC;

 


 

 

import pandas as pd
# DataFrame 
data = {
    'ProductID': [1, 2, 3, 4],
    'ProductName': ['Apple iPhone 13', 'Samsung Galaxy S22', 'LogitechMouse', 'Nike Running Shoes'],
    'Price': [999.99, 899.99, 29.99, 120.00],
    'Category': ['Electronics', 'Electronics', 'Accessories', 'Apparel']
}
products_df = pd.DataFrame(data)
def find_highest_price_product(group):
    return group.loc[group['Price']==group['Price'].max()]

→ max price를 가진 제품에 해당하는 행을 반환하는 함수. 

highest_price_products_df = products_df.groupby('Category').apply(find_highest_price_product).reset_index(drop=True)

→ category에 대해 groupby 한 후, apply(함수) / 각 카테고리별 최고값인 상품에 대한 데이터프레임 생성

print(highest_price_products_df[['Category', 'ProductName', 'Price']])

→ 문제 요구 사항에 맞게 추출


문제2.

재고 수량이 10개 이하인 모든 아이템의 이름과 재고 수량을 조회

#SQL
SELECT ItemName, StockQuantity
FROM Inventory
WHERE StockQuantity <= 10
ORDER BY StockQuantity ASC;

import pandas as pd
# DataFrame 
data = {
    'ItemID': [1, 2, 3, 4],
    'ItemName': ['Wooden Chair', 'Desk Lamp', 'Office Desk', 'Monitor Stand'],
    'StockQuantity': [15, 22, 10, 5],
    'Price': [45.00, 23.99, 150.00, 29.99],
    'Supplier': ['WoodCrafters', 'LightBright', 'OfficeFurnish', 'TechGear'] }
inventory_df = pd.DataFrame(data)

 

low_stock_item_df=inventory_df[inventory_df['StockQuantity']<=10]

→ 재고가 10개 이하인 아이템

print(low_stock_item_df[['ItemName','StockQuantity']].sort_values(by='StockQuantity'))

→재고 수량이 낮은 아이템 순으로 정렬


 

문제 3.

'Fiction' 장르인 모든 책의 제목과 저자명을 조회

#SQL
SELECT Title, Author
FROM Books
WHERE Genre = 'Fiction'
ORDER BY PublishedYear ASC;

import pandas as pd
# DataFrame 
data = {
    'BookID': [1, 2, 3, 4],
    'Title': ['The Great Gatsby', 'Brave New World', 'A Brief History of Time', 'The Art of War'],
    'Author': ['F. Scott Fitzgerald', 'Aldous Huxley', 'Stephen Hawking', 'Sun Tzu'],
    'Genre': ['Fiction', 'Fiction', 'Science', 'Philosophy'],
    'PublishedYear': [1925, 1932, 1988, -500],
    'InStock': [True, False, True, True]
}
books_df = pd.DataFrame(data)
fiction_books_df=books_df[books_df['Genre']=='Fiction']

→ 장르가 픽션인 경우

print(fiction_books_df[['Title', 'Author']].sort_values(by='PublishedYear'))

로 하면, 

KeyError: 'PublishedYear'

에ㅔ러.. 

sort_values -- 문자형이라 안되나? 했지만 확인해보니 정수형,, 

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.sort_values.html

 

pandas.DataFrame.sort_values — pandas 2.2.1 documentation

If True, the resulting axis will be labeled 0, 1, …, n - 1.

pandas.pydata.org

ascending, inplace 추가해두 안 된다..

print(fiction_books_df[['Title', 'Author']])

→일단 이렇게..

 


문제4. 

전체 기간 동안 가장 많이 판매된 제품의 이름과 총 판매량 조회

#SQL
SELECT ProductName, SUM(Quantity) AS TotalQuantity
FROM SalesData
GROUP BY ProductName
ORDER BY TotalQuantity DESC
LIMIT 1;

import pandas as pd
# DataFrame 
data = {
    'SaleID': [1, 2, 3, 4, 5],
    'ProductName': ['Gaming Laptop', 'Wireless Mouse', 'Mechanical Keyboard', 'Gaming Laptop', 'Wireless Mouse'],
    'SaleDate': ['2024-01-01', '2024-01-03', '2024-01-05', '2024-01-07', '2024-01-09'],
    'Quantity': [2, 5, 3, 1, 2],
    'SalePrice': [1200.00, 25.99, 75.50, 1200.00, 25.99],
    'CustomerID': [101, 102, 103, 104, 101]
}
sales_data_df = pd.DataFrame(data)
total_quauntity_by_product=sales_data_df.groupby('ProductName')['Quantity'].sum()

→각 제품별 총 판매량

→각 productname에 대하여, quantity 값을 모두 더함

top_selling_product=total_quauntity_by_product.idxmax()
top_selling_quantity=total_quauntity_by_product.max()

→가장 많이 판매된 상품, 판매량

idxmax와 idxmin은 각각 축에서 최대/최소값의 인덱스를 반환하는 메서드
print(f"Top Selling Product: {top_selling_product}, Total Quantity: {top_selling_quantity}")

 

 

 

 

 

 

 

 

 

'TIL' 카테고리의 다른 글

SQL to Pandas (2)  (0) 2024.03.12
240311월_TIL  (0) 2024.03.11
제4회 스파르톤  (0) 2024.03.09
240308금_TIL  (0) 2024.03.08
240307목_TIL  (1) 2024.03.07

관련글 더보기