Tuesday, October 31, 2023

AutoCAD, Python and Pandas

 

Pandas “pandas is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool, built on top of the Python programming language.”

 You can also use pandas in AutoCAD as a data extraction tool. I’m just learning pandas myself, thankfully there’s good documentation

In this example, I want to search for all block references that begin with ‘SPK’,  to create a takeoff of what sprinkler systems are in this drawing. Then, I’ll use pandas to combine rows and format the output. I’m just printing the output to the command line, but it’s simple enough to create a table or export the data to Excel

 here's the code


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 traceback

import pandas as pd

#get the attribues and return them as a list
def getAttValues(ref: Db.BlockReference)->list[str]:
    v = [ref.getBlockName()]
    for attrefid in ref.attributeIds():
        attref = Db.AttributeReference(attrefid)
        match attref.tag():
            case 'PART#':
                v.append(attref.textString())
            case 'DESCRIPTION':
                v.append(attref.textString())
            case _:
                pass
    return v

def PyRxCmd_doit():
    try:
        spkIds = []
        db = Db.curDb()

        #define our columns
        data = {'Name': [],
                'PART#': [],
                'DESCRIPTION': [],
                'QTY': []}

        #search for blocks that start with 'SPK'
        bt = Db.BlockTable(db.blockTableId())
        for name, id in bt.toDict().items():
            if name.startswith('SPK'):
                spkIds.append(id)

        for id in spkIds:
            btr = Db.BlockTableRecord(id)
            for refid in btr.getBlockReferenceIds():
                ref = Db.BlockReference(refid)
                values = getAttValues(ref)
               
                #pandas wants equal length lists
                if len(values) != 3:
                    continue
               
                data['Name'].append(values[0].rstrip('.dwg'))
                data['PART#'].append(values[1])
                data['DESCRIPTION'].append(values[2])
                data['QTY'].append(1) #we know we have one

        #create the dataframe, then group by
        df = pd.DataFrame(data)
        dfgr = df.groupby(['Name', 'PART#', 'DESCRIPTION'],
                         sort=False, as_index=False).agg({'QTY': 'sum'})
       
        print(dfgr.to_string())

    except Exception as err:
        traceback.print_exception(err)
 
 


No comments:

Post a Comment

TraceBoundary sample in Python for AutoCAD

    import traceback from pyrx_imp import Rx from pyrx_imp import Ge from pyrx_imp import Gi from pyrx_imp import Db from pyrx_imp...