DataFrame handling using Pandas and NumPy: CSV and Excel extract and write using DataFrame

pandas एक पूरी CSV या Excel sheet को एक DataFrame object में एक call से load करता है (read_csv, read_excel), और इसे उतनी ही आसानी से वापस लिखता है (to_csv, to_excel), numpy इसके नीचे numbers को power देता है।

9 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

साठ lines एक बन जाती हैं

पिछले lesson का csv-module code marks.csv को एक with-block, एक reader, एक header skip, एक loop, और int() conversions से पढ़ता था: honest काम, कोई analysis शुरू होने से पहले एक दर्जन lines।

अब वही काम उस tool में देखिए जो data analysts असल में इस्तेमाल करते हैं:

df = pd.read_csv('marks.csv')

एक line। Header समझा गया, numbers पहले से numbers हैं, पूरी table एक object में बैठी जिसे DataFrame कहते हैं। वह object, और इसके पीछे की pandas library, इस subject के बाक़ी हिस्से को power देती है।

Theory

आपके desk पर पूरी sheet

csv module एक postman था जो आपको एक बार में एक envelope थमाता था: mail sort करने के लिए ठीक, analysis के लिए painful।

pandas पूरी spreadsheet को आपके desk पर एक अकेले object के रूप में उठा लेता है: हर row, हर column, labelled और typed। एक average चाहिए? Sheet से पूछिए। इसे Excel के रूप में save करना है? Sheet को बताइए। आप lines-of-a-file में सोचना छोड़ते हैं और tables में सोचना शुरू करते हैं, वही mental model जो SQL ने आपको दिया।

Theory

pandas, numpy, DataFrame: कौन कौन है

numpy: engine: lightning-fast arrays और maths (import numpy as np)।

pandas: numpy पर बनी table layer (import pandas as pd)। Aliases pd और np universal convention हैं: exams में भी इन्हें इस्तेमाल कीजिए।

DataFrame: pandas का central object: एक index (row labels, default से 0,1,2,...), named columns, और प्रति column एक dtype (int64, float64, text के लिए object) वाली एक 2-D table।

दोनों libraries third-party हैं: pip install pandas numpy प्रति machine एक बार, built-in csv और sqlite3 के उलट।

Practical

CSV अंदर, Excel बाहर (और वापस)

import pandas as pd

# load: one line, header + types handled
df = pd.read_csv('marks.csv')

print(df.shape)      # (60, 3)   rows, columns
print(df.columns)    # Index(['roll', 'subject', 'score'], ...)
print(df.dtypes)     # roll int64, subject object, score int64
print(df)            # the table itself, index on the left

# write: CSV and Excel (Excel needs: pip install openpyxl)
df.to_csv('backup.csv', index=False)     # index=False: no row-number column
df.to_excel('report.xlsx', index=False)

# Excel in, too:
sheet = pd.read_excel('attendance.xlsx')

# the numpy engine underneath, when you need the raw array:
arr = df.to_numpy()
print(arr[0])        # [101 'DBMS' 78]

Quiz

pd.read_csv('marks.csv') क्या return करता है, और इसकी values csv.reader से कैसे अलग हैं?

  1. एक DataFrame: named, TYPE-INFERRED columns वाला एक table object (score int64 है, string '78' नहीं)
  2. Strings की lists की एक list, csv.reader जैसी ही
  3. प्रति row एक dictionary, DictReader जैसी ही
  4. एक generator जिसे कोई data मौजूद होने से पहले loop करना ज़रूरी है
Show the answer

एक DataFrame: named, TYPE-INFERRED columns वाला एक table object (score int64 है, string '78' नहीं)

read_csv पूरी file को एक DataFrame में parse करता है और इसके content से हर column का type infer करता है: score maths के लिए तैयार numbers के रूप में आता है, कोई int() conversions नहीं। यह type inference csv.reader की everything-is-a-string दुनिया के ऊपर practical leap है। Options B और C पिछले lesson के tools describe करते हैं; एक DataFrame eagerly loaded होता है, generator नहीं।

Think first

Mystery column

एक student df.to_csv('backup.csv') से save करता है (कोई index=False नहीं), फिर इसे कल reload करता है। DataFrame में अब एक अजीब extra पहला column है 'Unnamed: 0' नाम का जिसमें 0, 1, 2, ... है। tap करने से पहले: यह कहाँ से आया, और fix क्या है?

Show the answer

to_csv ने DataFrame का index (0,1,2,... row labels) file में एक असली column के रूप में लिखा; reload पर, pandas को एक unlabelled column मिला और इसे 'Unnamed: 0' नाम दिया। कल फिर save कीजिए और आपको दो मिलते हैं: columns बढ़ते हैं।

Fix: df.to_csv('backup.csv', index=False): सबसे ज़्यादा type किया गया pandas argument। जब तक आपके index का कोई असली meaning न हो, export पर इसे हमेशा off कीजिए।

Watch out

Setup और judgement traps

pandas built in नहीं है: ModuleNotFoundError मतलब pip install pandas, और read_excel को अतिरिक्त openpyxl चाहिए: setup सवालों में एक line लायक़।

हर export पर index=False जब तक आप न जानें क्यों नहीं।

हर चीज़ के लिए pandas मत पकड़िए: एक log line append करने को पिछले lesson का open() चाहिए; एक लाख rows row-by-row stream करने को csv.reader चाहिए। जब आप tables ANALYSE करते हैं तभी pandas अपना weight कमाता है।

Theory

वह pull जो आप बना रहे हैं

उस pipeline को देखिए जो अब आपकी है: SQL college.db में data shape करता है, Unit 2 इसे CSV के रूप में export करता है, और read_csv इसे एक DataFrame में उठाता है (pd.read_sql भी मौजूद है, pandas को सीधे आपकी sqlite3 connection से जोड़ते हुए: जानने लायक़ एक line)। अगले lessons: DataFrame को slice करना (rows, columns, conditions) और वे statistics compute करना जिनके लिए ResultDesk पैदा हुआ था।

Summary

Key takeaways

  • import pandas as pd, import numpy as np: universal aliases; दोनों pip-installed हैं, built in नहीं।
  • एक DataFrame = memory में एक 2-D table: index, named columns, प्रति column एक inferred dtype।
  • pd.read_csv / pd.read_excel एक पूरी file एक line में load करते हैं; df.to_csv / df.to_excel वापस लिखते हैं।
  • हमेशा index=False से export कीजिए, वरना row numbers एक mystery 'Unnamed: 0' column बन जाते हैं।
  • df.shape, df.columns, df.dtypes किसी भी loaded table पर पहली तीन inspections हैं।
  • numpy नीचे का fast array engine है; df.to_numpy() इसे expose करता है।
  • Memory hook: आपके desk पर पूरी sheet, एक बार में एक envelope नहीं।

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Python interaction with text and CSV

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

DataFrame handling using Pandas and NumPy: CSV and Excel extract and write using DataFrame · Database Handling using Python · Gri-Learn