Home > Blockchain >  Save each row of df to separate xml
Save each row of df to separate xml

Time:08-13

I am trying to iterate through each row of an excel file, and save the output for each row to it's separate .xml file. However, when I run the code, instead of having each row in a separate .xml file, I have all rows being saved to each generated .xml files. Obviously, I'm having confusion about iteration, and would gladly appreciate any help. Here's my current code:

import pandas as pd

df = pd.read_excel ('C:/Users/Downloads/Book1.xlsx')

df['name'] = df['name'].map(str)
df.set_index('name',inplace=True)

for name, data in df.iterrows():
    (df.to_xml('D:/Test/'   name   '.xml' , attr_cols=["disabled", "error-if-not-time", "interval-type", "name" , "type" , "verbose"], 
                 row_name = "assesslet"))

CodePudding user response:

Try to change df in loop to data then convert data to one row DataFrame since there is no Series.to_xml()

for name, data in df.iterrows():
    (data.to_frame().T.to_xml('D:/Test/'   name   '.xml' , attr_cols=["disabled", "error-if-not-time", "interval-type", "name" , "type" , "verbose"], 
                 row_name = "assesslet"))

CodePudding user response:

try:

for name, data in df.iterrows():
    pd.DataFrame(data).to_xml(('D:/Test/'   name   '.xml') , attr_cols=["disabled", "error-if-not-time", "interval-type", "name" , "type" , "verbose"], 
                 row_name = "assesslet")

to_xml() is DataFrame specific. But each time you iterate, you end up with Pandas Series. That is why I used pd.DataFrame(). You can also use to_frame() just like mentioned above. Also first argument, encapsulate it with parenthesis since it is a string concatenation.

  • Related