ভূমিকা
ডুনিয়া এক্সেল দিয়ে চালিত হয় বলে মনে হয়। ডেটা ইঞ্জিনিয়ারিংয়ের কাজে আমি দেখেছি সহকর্মীরা কতটুকু এক্সেলকে ডিসিশন মেকিং-এ ক্রিটিক্যাল টুল হিসেবে ব্যবহার করে। বড় এক্সেল স্প্রেডশিট হ্যান্ডল করার একটি নাট খাট ট্রিক দেখাচ্ছি।
কীভাবে করবেন
১. ইনস্টলেশন
openpyxl এবং xlwt ইনস্টল করুন।
২. বেসিক এক্সেল পান্ডাস অপারেশন
import xlsxwriter
import pandas as pd
def write_data_to_files(inp_data, inp_file_name):
workbook = xlsxwriter.Workbook(inp_file_name)
worksheet = workbook.add_worksheet()
row, col = 0, 0
for player, titles in inp_data:
worksheet.write(row, col, player)
worksheet.write(row, col + 1, titles)
row += 1
workbook.close()
def excel_functions_with_pandas(inp_file_name):
data = pd.read_excel(inp_file_name)
print(data.head())
print(data.info())
# নতুন শিটে ডেটা লিখুন
new_players_info = pd.DataFrame(...)
new_data = pd.ExcelWriter(inp_file_name)
new_players_info.to_excel(new_data, sheet_name="Sheet2")
৩. বড় এক্সেল ফাইল চাঙ্কে প্রসেস করা
Pandas CSV-তে chunksize দেয় কিন্তু Excel-এ দেয় না। নিচের ফাংশন চাঙ্কে পড়ে কনক্যাট করে।
def global_excel_to_db_chunks(file_name, nrows):
chunks = []
i_chunk = 0
skiprows = 1
df_header = pd.read_excel(file_name, nrows=1)
while True:
df_chunk = pd.read_excel(file_name, nrows=nrows, skiprows=skiprows, header=None)
skiprows += nrows
if not df_chunk.shape[0]:
break
print(f" ** Reading chunk number {i_chunk} with {df_chunk.shape[0]} Rows")
chunks.append(df_chunk)
i_chunk += 1
df_chunks = pd.concat(chunks)
# কলাম নাম রিনেম করে হেডারের সাথে জোড়া দিন
columns = {i: col for i, col in enumerate(df_header.columns.tolist())}
df_chunks.rename(columns=columns, inplace=True)
df = pd.concat([df_header, df_chunks])
print(' *** Reading is Completed in chunks...')
if __name__ == '__main__':
file_name = 'Sample-sales-data-excel.xls'
stats = pd.read_excel(file_name)
print(f" ** Total rows in the spreadsheet are - {len(stats.index)} Rows")
global_excel_to_db_chunks(file_name, 1000)
আউটপুট
** Total rows in the spreadsheet are - 9994 Rows
** Reading chunk number 0 with 1000 Rows
** Reading chunk number 1 with 1000 Rows
...
** Reading chunk number 9 with 994 Rows
*** Reading is Completed in chunks...