0

I want to create a dataframe that consists of values obtained inside the for loop.

columns = ['BIN','Date_of_registration', 'Tax','TaxName','KBK',
           'KBKName','Paynum','Paytype', 'EntryType','Writeoffdate', 'Summa']
df = pd.DataFrame(columns=columns)

I have this for loop:

    for elements in tree.findall('{http://xmlns.kztc-cits/sign}payment'):

        print("hello")
        tax = elements.find('{http://xmlns.kztc-cits/sign}TaxOrgCode').text
        tax_name_ru = elements.find('{http://xmlns.kztc-cits/sign}NameTaxRu').text
        kbk = elements.find('{http://xmlns.kztc-cits/sign}KBK').text
        kbk_name_ru = elements.find('{http://xmlns.kztc-cits/sign}KBKNameRu').text
        paynum = elements.find('{http://xmlns.kztc-cits/sign}PayNum').text
        paytype = elements.find('{http://xmlns.kztc-cits/sign}PayType').text
        entry_type = elements.find('{http://xmlns.kztc-cits/sign}EntryType').text
        writeoffdate = elements.find('{http://xmlns.kztc-cits/sign}WriteOffDate').text
        summa = elements.find('{http://xmlns.kztc-cits/sign}Summa').text


        print(tax, tax_name_ru, kbk, kbk_name_ru, paynum, paytype, entry_type, writeoffdate, summa)

How can I append acquired values to the initially created(outside for loop) dataframe?

Mikoupgrade
  • 65
  • 1
  • 9
  • Hi, you can save each new values in a list (new `row` in the `DataFrame`) and then append this list to the `DataFrame`. See in this [appending a list or series to a pandas dataframe as a row](https://stackoverflow.com/questions/26309962/appending-a-list-or-series-to-a-pandas-dataframe-as-a-row) – DavidDr90 Oct 30 '20 at 08:51

1 Answers1

0

A simple way if you only need the dataframe after the loop is completed is to append the data to a list of lists and then convert to a dataframe. Caveat: Responsibility is on you to make sure the list ordering matches the columns, so if you change your columns in the future you have to reposition the list.

list_of_rows = []
for elements in tree.findall('{http://xmlns.kztc-cits/sign}payment'):
   list_of_rows.append([
      tax, tax_name_ru, kbk, kbk_name_ru, paynum, paytype,entry_type, writeoffdate, summa])

df = pd.DataFrame(columns=columns, data=list_of_rows)
fibonachoceres
  • 727
  • 4
  • 14