personId
관심 있는 목록이 있습니다 .
agents = {'id': ['20','32','12']}
그런 다음 가정 특성이있는 XML 파일이 있습니다.
<households
<household id="980921">
<members>
<personId refId="5"/>
<personId refId="15"/>
<personId refId="20"/>
</members>
<income currency="CHF" period="month">
8000.0
</income>
<attributes>
<attribute name="numberOfCars" class="java.lang.String" >2</attribute>
</attributes>
</household>
<household id="980976">
<members>
<personId refId="2891"/>
<personId refId="100"/>
<personId refId="2044"/>
</members>
<income currency="CHF" period="month">
8000.0
</income>
<attributes>
<attribute name="numberOfCars" class="java.lang.String" >1</attribute>
</attributes>
</household>
<household id="980983">
<members>
<personId refId="11110"/>
<personId refId="32"/>
<personId refId="34"/>
</members>
<income currency="CHF" period="month">
10000.0
</income>
<attributes>
<attribute name="numberOfCars" class="java.lang.String" >0</attribute>
</attributes>
</household>
</households>
내가 원하는 것은 데이터 프레임을 갖는 것입니다.이 데이터 프레임 income
은 가정 member
의 목록에 속하는 주택 agents
이 관심 있는 것을 보여줍니다 . 다음과 같은 것 (더하기는 관심있는 사람이 거주하는 가구 구성원 수를 나타내는 추가 열입니다) :
personId income
20 8000.0
32 10000.0
내 접근 방식은 너무 멀지 않았습니다. members
"형제"노드에서 정보 를 필터링 하고 액세스 하는 방법에 어려움이 있습니다 . 내 출력은 빈 데이터 프레임입니다.
import xml.etree.ElementTree as ET
import pandas as pd
with open(xml) as fd:
root = ET.parse(fd).getroot()
xpath_fmt = 'household/members/personId[@refId="{}"]/income'
rows = []
for pid in agents['id']:
xpath = xpath_fmt.format(pid)
r = root.findall(xpath)
for res in r:
rows.append([pid, res.text])
d = pd.DataFrame(rows, columns=['personId', 'income'])
도와 주셔서 정말로 고맙습니다!
의견에서 언급했듯이 BeautifulSoup을 사용하는 솔루션은 다음과 같습니다 ( xml_txt
질문의 XML 텍스트입니다).
import pandas as pd
from bs4 import BeautifulSoup
agents = {'id': ['20','32','12']}
soup = BeautifulSoup(xml_txt, 'xml') #xml_txt is your XML text from the question
css_selector = ','.join('household > members > personId[refId="{}"]'.format(i) for i in agents['id'])
data = {'personId':[], 'income':[]}
for person in soup.select(css_selector):
data['personId'].append( person['refId'] )
data['income'].append( person.find_parent('household').find('income').get_text(strip=True) )
df = pd.DataFrame(data)
print(df)
인쇄물:
personId income
0 20 8000.0
1 32 10000.0
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다