[英]Using Panda to split Sheets and sort. What am I missing?
我是初學者,所以如果這是一個基本問題,我很抱歉。
我一直在使用來自另一個用戶的代碼:(Excel)使用列值將每個列值拆分為單獨的工作表。 您還可以選擇將列拆分為我不使用的不同文件。
我想知道最理想的方法:
(將列拆分為工作表)然后按最大到最小對每個工作表上的特定列進行排序。
我怎樣才能將它添加到這段代碼中,或者我應該使用不同的腳本?
如果有更簡單的方法,請告訴我。
這是一份包含不同產品的廣告報告,我想拆分每個產品,並為每個產品排序轉換最好的關鍵字(從大到小),這樣我就可以輕松區分最暢銷的關鍵字和最差的銷售關鍵字。 希望我最終可以創建一些自動給我符合條件的關鍵字的東西。
謝謝。
import pandas as pd
import os
from openpyxl import load_workbook
import xlsxwriter
from shutil import copyfile
file=input('File Path:')
extension = os.path.splitext(file)[1]
filename = os.path.splitext(file)[0]
pth=os.path.dirname(file)
newfile=os.path.join(pth,filename+'_2'+extension)
df=pd.read_excel(file)
colpick=input('Select Column: ')
cols=list(set(df[colpick].values))
def sendtofile(cols):
for i in cols:
df[df[colpick] == i].to_excel("{}/{}.xlsx".format(pth, i), sheet_name=i, index=False)
print('\nCompleted')
print('Thanks for using this program.')
return
def sendtosheet(cols):
copyfile(file, newfile)
for j in cols:
writer = pd.ExcelWriter(newfile, engine='openpyxl')
for myname in cols:
mydf = df.loc[df[colpick] == myname]
mydf.to_excel(writer, sheet_name=myname, index=False)
writer.save()
print('\nCompleted')
print('Thanks for using this program.')
return
print('You data will split based on these values {} and create {} files or sheets based on next selection. If you are ready to proceed please type "Y" and hit enter. Hit "N" to exit.'.format(', '.join(cols),len(cols)))
while True:
x=input('Ready to Proceed (Y/N): ').lower()
if x == 'y':
while True:
s = input('Split into different Sheets or File (S/F): ').lower()
if s == 'f':
sendtofile(cols)
break
elif s == 's':
sendtosheet(cols)
break
else: continue
break
elif x=='n':
print('\nThanks for using this program.')
break
else: continue
我找到了自己的解決方法! 哇我好開心!
file=input('File Path: ')
data = pd.ExcelFile(file)
df = data.parse(0)
df = df.sort_values(by='7 Day Total Sales ', ascending=False)
writer_orig = pd.ExcelWriter(file, engine='xlsxwriter')
df.to_excel(writer_orig, index=False, sheet_name='report')
writer_orig.save()
我把它放在原始代碼之前,先對它進行排序,然后拆分成表格!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.