0

I have a Dataframe ,you can have it by running :

import pandas as pd
from io import StringIO

df = """    
Name        Type     Format
loan1        i       type:num;width:10
loan2        a       type:char;width:2
loan3        i       type:date;width:8;dec:0

"""
df= pd.read_csv(StringIO(df.strip()), sep='\s\s+', engine='python')

I want to receive something like this:

<th name="loan1" type="i" format="type:num;width:10">loan1</th>
<th name="loan2" type="a" format="type:char;width:2">loan2</th>
<th name="loan3" type="i" format="type:date;width:8;dec:0">loan3</th>

It can be either string in txt or a xml file , Any friend can help ?

William
  • 3,724
  • 9
  • 43
  • 76

1 Answers1

2

Create a format template then map each record in the dataframe to the format template and write the formatted record to the file

with open('data.txt', 'w') as file:
    fmt = '<th name="{Name}" type="{Type}" format="{Format}">{Name}</th>\n'
    for r in df.to_dict('records'):
        file.write(fmt.format_map(r))

Result

# data.txt
<th name="loan1" type="i" format="type:num;width:10">loan1</th>
<th name="loan2" type="a" format="type:char;width:2">loan2</th>
<th name="loan3" type="i" format="type:date;width:8;dec:0">loan3</th>
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
  • Given the OP is not asking for a true XML, your answer suffices. But future readers should avoid building true XML with [string concatenation](https://stackoverflow.com/q/3034611/1422451). – Parfait Mar 23 '23 at 00:23