I explored Groupby and Aggregate here
import traceback
import PyRx as Rx
import PyGe as Ge
import PyGi as Gi
import PyDb as Db
import PyAp as Ap
import PyEd as Ed
import pandas as pd
def PyRxCmd_doit():
try:
#setup dictionaries to hold our data
lineMap = {"Type": [], "Layer": [], "Length": [], "QTY": []}
circleMap = {"Type": [], "Layer": [], "Diameter": [], "QTY": []}
#current database
db = Db.curDb()
model = Db.BlockTableRecord(db.modelSpaceId())
#search model for all lines (derived from)
lineIds = model.objectIds(Db.Line.desc())
for id in lineIds:
line = Db.Line(id)
lineMap["Type"].append("Line")
lineMap["Layer"].append(line.layer())
lineMap["Length"].append(line.startPoint().distanceTo(line.endPoint()))
lineMap["QTY"].append(1)
#search model for all circles (derived from)
circleIds = model.objectIds(Db.Circle.desc())
for id in circleIds:
circle = Db.Circle(id)
circleMap["Type"].append("Circle")
circleMap["Layer"].append(circle.layer())
circleMap["Diameter"].append(circle.diameter())
circleMap["QTY"].append(1)
#create the DataFrames
lfd = pd.DataFrame(lineMap)
cfd = pd.DataFrame(circleMap)
# called before concat because the column names are different
# groupby & aggregate
lfd = (lfd.groupby(["Type", "Layer", "Length"],
sort=False, as_index=False).agg({"QTY": "sum"}))
# groupby & aggregate
cfd = (cfd.groupby(["Type", "Layer", "Diameter"],
sort=False, as_index=False).agg({"QTY": "sum"}))
# concat the DataFrames
result = pd.concat([lfd, cfd])
# write to excel, but don't write the index
with pd.ExcelWriter("e:\\pandas_to_excel.xlsx") as writer:
result.to_excel(writer, sheet_name="sheet1", index=False)
except Exception as err:
traceback.print_exception(err)
No comments:
Post a Comment