Search code examples
pythondelete-rowdbf

How to delete dbf rows containing an alpha value or an entire dbf column


I would like to delete some rows & columns on my dfb that contain specific data.

Let's assume that the structure of the dfb looks like the image bellow and that I want to remove the rows with 'knapford' as 'Prov' and the 'Reg' column.

enter image description here

When I try following this script:

table = dbf.Table(wonderland.dbf).open(mode=dbf.READ_WRITE)
with table as tab:
    print (table)
    for record in dbf.Process(tab):
        dbf.delete(record[0])

I get this error:

  File "<ipython-input-4-d8feabfc9819>", line 4, in <module>
    dbf.delete(record[0])

  File "C:\Users\fassi\AppData\Local\Continuum\anaconda3\lib\site-packages\dbf\__init__.py", line 8349, in delete
    if not template and record._meta.status == CLOSED:

AttributeError: 'int' object has no attribute '_meta'

I had this other suggestion in mind, but I wonder if it will really delete all the fields of the row, just some specific ones or all the records!

table = dbf.Table(wonderland.dbf).open(mode=dbf.READ_WRITE)
with table as tab:
    dbf.delete_fields(table, Reg)
    for record in dbf.Process(tab):
        if record[0].strip()=='Knapford': #since we've delete the Reg, Prov is becoming record[0]?
            dbf.delete(record)

Thanks in advance


Solution

  • I think that this should work:

    from simpledbf import Dbf5
    
    dbf = Dbf5('file.dbf')
    data = dbf.to_dataframe()
    
    for row in range(len(data)):
        Reg= data.loc[row,'Reg']
        Prov = data.loc[row,'Prov']
        if Reg =='knapford' or Prov =='knapford':
            data.drop(index=row, axis=0, inplace=True)
    

    This other script work very well:

    import dbf
    with table as tab:
        for record in dbf.Process(tab):
            if record[1].strip()=='Knapford':
                #print (record)
                dbf.delete(record)
    table.pack()