This repository has been archived by the owner on Mar 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a507c3e
commit 10ed5d8
Showing
5 changed files
with
37 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
"""Write a pandas dataframe to xml.""" | ||
import pandas as pd | ||
from xml.sax.saxutils import escape | ||
|
||
|
||
def to_xml(df, filename=None, mode='w'): | ||
"""Write df to xml.""" | ||
def row_to_xml(row): | ||
"""Row by row.""" | ||
xml = ['<item>'] | ||
for i, col_name in enumerate(row.index): | ||
raw = row.iloc[i] | ||
if not isinstance(raw, float) and '&' in raw: | ||
print(raw, type(raw)) | ||
value = escape(raw) if isinstance(raw, str) else raw | ||
|
||
xml.append(' <field name="{0}">{1}</field>' | ||
.format(col_name, value) | ||
) | ||
xml.append('</item>') | ||
return '\n'.join(xml) | ||
|
||
res = '<?xml version="1.0" encoding="UTF-8"?>\n' | ||
res += '\n'.join(df.apply(row_to_xml, axis=1)) | ||
|
||
if filename is None: | ||
return res | ||
with open(filename, mode) as f: | ||
f.write(res) | ||
|
||
|
||
pd.DataFrame.to_xml = to_xml |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters