पांडा के साथ html तालिकाएँ कैसे पढ़ें (एक उदाहरण सहित)


आप HTML तालिकाओं को पांडा डेटाफ़्रेम में पढ़ने के लिए पांडा read_html() फ़ंक्शन का उपयोग कर सकते हैं।

यह फ़ंक्शन निम्नलिखित मूल सिंटैक्स का उपयोग करता है:

 df = pd. read_html (' https://en.wikipedia.org/wiki/National_Basketball_Association ')

निम्नलिखित उदाहरण दिखाता है कि इस विकिपीडिया पृष्ठ से एनबीए टीम के नामों की तालिका को पढ़ने के लिए इस फ़ंक्शन का उपयोग कैसे करें।

उदाहरण: पांडा के साथ एक HTML तालिका पढ़ें

read_html() फ़ंक्शन का उपयोग करने से पहले, आपको संभवतः lxml इंस्टॉल करना होगा:

 pip install lxml

ध्यान दें : यदि आप ज्यूपिटर नोटबुक का उपयोग कर रहे हैं, तो आपको यह इंस्टॉलेशन करने के बाद कर्नेल को पुनरारंभ करना होगा।

इसके बाद, हम इस विकिपीडिया पृष्ठ पर प्रत्येक HTML तालिका को पढ़ने के लिए read_html() फ़ंक्शन का उपयोग कर सकते हैं:

 import pandas as pd
import numpy as np
import matplotlib. pyplot as plt
from unicodedata import normalize

#read all HTML tables from specific URL
tabs = pd. read_html (' https://en.wikipedia.org/wiki/National_Basketball_Association ')

#display total number of tables read
len (tabs)

44

हम देख सकते हैं कि इस पृष्ठ पर कुल 44 HTML तालिकाएँ मिलीं।

मुझे पता है कि जिस तालिका में मेरी रुचि है, उसमें “डिवीजन” शब्द है, इसलिए मैं केवल इस शब्द वाली HTML तालिकाओं को पुनः प्राप्त करने के लिए मैच तर्क का उपयोग कर सकता हूं:

 #read HTML tables from specific URL with the word "Division" in them
tabs = pd. read_html (' https://en.wikipedia.org/wiki/National_Basketball_Association ',
                    match=' Division ')

#display total number of tables read
len (tabs)

1

फिर मैं तालिका स्तंभों के नाम सूचीबद्ध कर सकता हूं:

 #define table
df = tabs[0]

#list all column names of table
list (df)

[('Division', 'Eastern Conference'),
 ('Team', 'Eastern Conference'),
 ('Location', 'Eastern Conference'),
 ('Arena', 'Eastern Conference'),
 ('Capacity', 'Eastern Conference'),
 ('Coordinates', 'Eastern Conference'),
 ('Founded', 'Eastern Conference'),
 ('Joined', 'Eastern Conference'),
 ('Unnamed: 8_level_0', 'Eastern Conference')]

मुझे केवल पहले दो कॉलमों में दिलचस्पी है, इसलिए मैं डेटाफ़्रेम को केवल इन कॉलमों को शामिल करने के लिए फ़िल्टर कर सकता हूं:

 #filter DataFrame to only contain first two columns
df_final = df. iloc [:, 0:2]

#rename columns
df_final. columns = [' Division ', ' Team ']

#view first few rows of final DataFrame
print ( df_final.head ())

   Division Team
0 Atlantic Boston Celtics
1 Atlantic Brooklyn Nets
2 Atlantic New York Knicks
3 Atlantic Philadelphia 76ers
4 Atlantic Toronto Raptors

अंतिम तालिका में केवल “डिवीजन” और “टीम” कॉलम हैं।

अतिरिक्त संसाधन

निम्नलिखित ट्यूटोरियल बताते हैं कि पांडा में अन्य फ़ाइल प्रकारों को कैसे पढ़ा जाए:

पंडों के साथ टेक्स्ट फ़ाइल कैसे पढ़ें
पंडों के साथ एक्सेल फ़ाइलें कैसे पढ़ें
पांडा के साथ सीएसवी फ़ाइलें कैसे पढ़ें

एक टिप्पणी जोड़ने

आपका ईमेल पता प्रकाशित नहीं किया जाएगा. आवश्यक फ़ील्ड चिह्नित हैं *