我曾嘗試使用 Pandas read_xml,它可以很好地讀取大部分 XML,但由于格式略有不同,因此遺漏了一些部分。我在下面包含了一個摘錄,它讀取“型別”,“激活”很好,但不是“Amt”值。它選擇列標題“Amt”而不是值。任何人都可以指出我如何讓??它閱讀正確的方向。謝謝
<Type>PYI</Type>
<Activation>N</Activation>
<Amt val="4000" curr="GBP"/>
xml_df = pd.read_xml(xml_data)
任何能幫助我的人都試過閱讀 Pandas.read_xml 的檔案,但我明白為什么它不會選擇這個?
uj5u.com熱心網友回復:
默認情況下,pandas.read_xml決議一組節點的所有直接后代,包括其子節點和屬性。除非,xpath論據表明它,read_xml不會比直接后代更進一步。
說明您的用例。下面可能是您的 XML where<Type>和它的兄弟姐妹的一般設定 ,<Activation>并被<Amt>決議。但是,<Amt>不包含文本節點,僅包含屬性。所以該列中的值應該為空。
<root>
<row>
<Type>PYI</Type> <!-- Type IS A CHILD NODE OF row -->
<Activation>N</Activation> <!-- Activation IS A CHILD NODE OF row -->
<Amt val="4000" curr="GBP"/> <!-- Amt IS A CHILD NODE OF row -->
</row>
</root>
但后來你問,為什么read_xml忽略了val和curr屬性?因為每個不是一個直接的后裔<row>。他們是 的后代<Amt>(即 的孫子<row>)。如果屬性被移動到<row>,那么它們將被捕獲,如下所示:
<root>
<row val="4000" curr="GBP"> <!-- val AND curr ARE CHILD ATTRIBS OF row -->
<Type>PYI</Type> <!-- Type IS A CHILD NODE OF row -->
<Activation>N</Activation> <!-- Activation IS A CHILD NODE OF row -->
<Amt/> <!-- Amt IS A CHILD NODE OF row -->
</row>
</root>
要捕獲這些屬性,請調整xpath引數以指向其直接父級:
amt_df = pd.read_xml("Input.xml", xpath="//Amt")
要使用<row>級別資訊捕獲此類屬性,請考慮使用專用語言XSLT將原始 XML 轉換為以下內容:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<row>
<Type>PYI</Type>
<Activation>N</Activation>
<Amt_val>4000</Amt_val>
<Amt_curr>GBP</Amt_curr>
</row>
</root>
以上是read_xml使用stylesheet引數時決議的中間輸出,如下所示:
xsl = '''<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="row">
<xsl:copy>
<xsl:copy-of select="*[name() != 'Amt']"/>
<Amt_val><xsl:value-of select="Amt/@val"/></Amt_val>
<Amt_curr><xsl:value-of select="Amt/@curr"/></Amt_curr>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>'''
row_df = pd.read_xml("Input.xml", xpath="//row", stylesheet=xsl")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/350822.html
