I have this sample excel with sample data:
My problem is, how can I get all the rows with the same EmployeeID and save to a new sheet. For example on the picture above, how can I save the rows with the color yellow in a new sheet but same excel file.
I have this code but it is just creating a new sheet:
writer = ExcelWriter('Employee Timesheet.xlsx')
df.insert(loc=0, column='Number', value=range(1,max_row+1-4))
for i in range(5,max_row+1):
for j in range(2,3):
cell_obj=ws.cell(row=i,column=j)
cell_obj1=ws.cell(row=i+1,column=j)
if cell_obj.value != cell_obj1.value:
#sample only on creating a new sheet
counter = 5
for count in range(1,counter):
sheet_name = 'Sheet%s' % count
df.to_excel(writer, sheet_name=sheet_name, index=False)
writer.save()
Please someone give me an idea on how can I iterate on rows and save everything in a new sheet. Thank you!
I hope this can prove useful, I have a dataframe like this:
#!/usr/bin/python
from numpy import nan
import pandas as pd
my_df=pd.DataFrame({'ID':['Sample1', 'Sample1', 'Sample1', 'Sample1', 'Sample2', 'Sample2', 'Sample2', 'Sample2', 'Sample3', 'Sample3'],
'Purchase':[4, 5, 6, 7, 8, 9, 10, 11, 12, 13],'item':['Item1', 'Item2', nan, 'Item4', 'Item5', 'Item6', 'Item7', nan, nan, nan],})
my_df
ID Purchase item
0 Sample1 4 Item1
1 Sample1 5 Item2
2 Sample1 6 NaN
3 Sample1 7 Item4
4 Sample2 8 Item5
5 Sample2 9 Item6
6 Sample2 10 Item7
7 Sample2 11 NaN
8 Sample3 12 NaN
9 Sample3 13 NaN
Samples having duplicate values in first column can be extracted into a dictionary and then into separate csv files that can also be used with excel:
dict_of_dataframe = {k: v for k, v in my_df.groupby('ID')} # Group based on ID,
for key,value in dict_of_companies.items():
with open(key, 'w+') as f:
f.write(str(value))
f.close()
This will generate csv files based on the values that are duplicate in first column.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.