Printing is unavailable

This course is licensed for personal online viewing only.

Public preview • CL-P000000-C28-L1279-72D60C23

Home Dashboard
Chapter 41 · Module 4 — Data Input and Output with NumPy

Loading Numeric Data from Text and CSV Files

Priority
  • JobHigh
  • InterviewMedium
  • DevelopmentHigh
4,055
words
23
min read
3
tools

1. Learning Outcomes#

या chapter नंतर तुम्हाला:

  • text file आणि CSV file मधील numerical data म्हणजे काय ते समजेल
  • np.loadtxt() वापरून numeric data NumPy array मध्ये load करता येईल
  • whitespace आणि comma-separated data मधील फरक समजेल
  • delimiter, dtype, skiprows, usecols आणि max_rows योग्य प्रकारे वापरता येतील
  • comment lines NumPy कशा handle करते ते समजेल
  • loaded data 1D किंवा 2D का मिळतो ते समजेल
  • ndmin चा basic उपयोग करता येईल
  • loaded array ची shape आणि dtype तपासता येईल
  • common parsing आणि column-count errors ओळखता येतील
  • analysis सुरू करण्याआधी loaded data validate करता येईल

या chapter मध्ये आपला मुख्य प्रश्न सोपा आहे: file मध्ये असलेले numbers NumPy array मध्ये सुरक्षितपणे कसे आणायचे?

2. File मधील Data आणि NumPy Array यांचा संबंध#

Data Science मध्ये data नेहमी Python code मध्येच तयार केलेला असेल असे नाही.

बर्‍याच वेळा data आपल्याला file मधून मिळतो.

उदाहरणार्थ:

  • temperature readings
  • students चे marks
  • sensor measurements
  • sales quantities
  • experiment results
  • exported CSV records

समजा numbers.txt नावाच्या file मध्ये तीन rows आहेत:

File line Content
1 10 20 30
2 40 50 60
3 70 80 90

हा अजून NumPy array नाही.

हा फक्त text स्वरूपात साठवलेला numerical data आहे.

आपल्याला हा data computation साठी वापरायचा असेल तर file read करून values NumPy array मध्ये convert कराव्या लागतात.

Figure 1: Text किंवा CSV data पासून NumPy array पर्यंतचा flow
Text किंवा CSV data पासून NumPy array पर्यंतचा flowText / CSVfileText / CSV filenp.loadtxt()np.loadtxt()Parsing rules:delimiter,dtype, rows,columnsParsing rules: delimiter, dtype, rows, columnsNumPy ndarrayNumPy ndarrayValidate shapeand dtypeValidate shape and dtype

या flow मध्ये np.loadtxt() file आणि NumPy array यांच्यामधील reader म्हणून काम करते.

File मधील text वाचला जातो, त्यातील values parse केल्या जातात आणि शेवटी NumPy ndarray तयार होतो.

3. np.loadtxt() म्हणजे काय?#

np.loadtxt() ही NumPy मधील function आहे जी सोप्या आणि व्यवस्थित formatted text files मधून data load करून NumPy array तयार करते.

Current NumPy documentation नुसार default dtype floating-point असतो, default delimiter whitespace असतो, default comment marker # आहे, usecols मध्ये column numbering 0 पासून सुरू होते आणि ndmin साठी 0, 1, किंवा 2 वापरता येतात.

Basic form:

PYTHON
import numpy as np

data = np.loadtxt("numbers.txt")

इथे:

  • "numbers.txt" म्हणजे आपली input file
  • np.loadtxt() ती file वाचते
  • loaded values पासून NumPy array तयार होतो
  • तयार झालेला array data मध्ये ठेवला जातो
Key Idea

np.loadtxt() म्हणजे file उघडून raw text देणारी सामान्य function नाही. ती text मधील values समजून त्यांना numerical NumPy array मध्ये parse करण्याचा प्रयत्न करते.

4. पहिली Text File Load करूया#

आपल्या numbers.txt file मध्ये खालील data आहे:

Row Column 1 Column 2 Column 3
1 10 20 30
2 40 50 60
3 70 80 90

Values मध्ये space असल्यामुळे हा whitespace-separated data आहे.

आता तो load करूया.

PYTHON
import numpy as np

data = np.loadtxt("numbers.txt")

print(data)
print(data.shape)

Expected Output#

TEXT
[[10. 20. 30.]
 [40. 50. 60.]
 [70. 80. 90.]]
(3, 3)

काय झाले ते समजून घेऊया.

File मध्ये तीन data rows होत्या.

प्रत्येक row मध्ये तीन values होत्या.

म्हणून तयार झालेल्या array ची shape (3, 3) आहे.

Output मध्ये 10. किंवा 20. असे decimal-looking values दिसतात कारण आपण dtype दिलेला नाही.

np.loadtxt() चा default data type floating-point आहे.

5. delimiter का आवश्यक असतो?#

आता दुसरी file पाहूया.

marks.csv:

File line Raw content
1 101,85,90
2 102,78,88
3 103,92,95

इथे numbers space ने वेगळे केलेले नाहीत.

ते comma ने वेगळे केले आहेत.

Comma येथे प्रत्येक value ची boundary सांगतो.

अशा separator ला delimiter म्हणतात.

CSV म्हणजे सामान्यतः Comma-Separated Values.

म्हणून NumPy ला स्पष्ट सांगावे लागेल:

delimiter=","

PYTHON
import numpy as np

marks = np.loadtxt("marks.csv", delimiter=",")

print(marks)

Expected Output#

TEXT
[[101.  85.  90.]
 [102.  78.  88.]
 [103.  92.  95.]]

NumPy प्रत्येक comma पाहून एक value संपली आणि पुढची value सुरू झाली असे समजते.

Remember

File मध्ये values कशाने वेगळ्या केलेल्या आहेत ते आणि delimiter मध्ये दिलेला separator यांचा मेळ असणे आवश्यक आहे.

Current np.loadtxt() मध्ये delimiter हा single character असतो. Comma-separated file साठी ",", semicolon-separated file साठी ";" अशा values वापरल्या जातात.

6. dtype वापरून Result चा Data Type ठरवणे#

Marks आणि student IDs पूर्णांक आहेत.

आपल्याला floating-point array नको असेल तर dtype parameter वापरता येतो.

PYTHON
import numpy as np

marks = np.loadtxt(
    "marks.csv",
    delimiter=",",
    dtype=np.int64
)

print(marks)
print(marks.dtype)

Expected Output#

TEXT
[[101  85  90]
 [102  78  88]
 [103  92  95]]
int64

इथे NumPy ला आपण स्पष्ट सांगितले:

dtype=np.int64

म्हणून values integer स्वरूपात load झाल्या.

dtype कधी द्यायचा?#

File मधील values आणि आपल्या analysis ची गरज पाहून dtype निवडायचा.

उदाहरणार्थ:

  • decimal measurements → floating-point योग्य
  • integer counts → integer योग्य असू शकतो
  • IDs numeric असले तरी calculation करायची नसल्यास त्यांचा अर्थ लक्षात घेऊन data design करावा
Common Mistake

File मध्ये 85.5 सारखी decimal value असेल आणि आपण चुकीचा integer dtype force केला, तर parsing fail होऊ शकते. dtype हा file मधील actual values शी compatible असावा.

7. Header असलेली CSV File#

Real CSV files मध्ये पहिल्या line वर column names असणे खूप common आहे.

उदाहरण:

File line Raw content
1 student_id,math,science
2 101,85,90
3 102,78,88
4 103,92,95

पहिली line numeric नाही.

जर NumPy ने student_id ला number मध्ये convert करण्याचा प्रयत्न केला, तर parsing error येऊ शकतो.

म्हणून header line skip करावी लागेल.

Figure 2: Header असलेल्या CSV मध्ये skiprows=1 चा परिणाम
Header असलेल्या CSV मध्ये skiprows=1 चा परिणामFile line1234Raw contentstudent_id,math,science101,85,90102,78,88103,92,95skipskipskiprows=1पहिली physical line वगळाskiprows=1 पहिली physical line वगळा

8. skiprows वापरणे#

पहिली line skip करण्यासाठी:

PYTHON
import numpy as np

marks = np.loadtxt(
    "marks_with_header.csv",
    delimiter=",",
    skiprows=1,
    dtype=np.int64
)

print(marks)

Expected Output#

TEXT
[[101  85  90]
 [102  78  88]
 [103  92  95]]

skiprows=1 म्हणजे सुरुवातीची एक physical line वगळा.

जर skiprows=2 दिले तर सुरुवातीच्या दोन lines skip होतील.

महत्त्वाचे

skiprows फक्त column header साठीच नाही. सुरुवातीला metadata किंवा दुसऱ्या unnecessary lines असतील तर त्यांनाही skip करता येते.

Official behavior नुसार skiprows मध्ये सुरुवातीच्या lines मोजताना comment lines देखील मोजल्या जातात.

9. usecols — आपल्याला लागणारे Columnsच Load करणे#

प्रत्येक वेळी file मधील सगळे columns आवश्यक नसतात.

आपल्या file मध्ये:

Column index Column
0 student_id
1 math
2 science

समजा आपल्याला फक्त math आणि science marks हवे आहेत.

मग:

PYTHON
import numpy as np

scores = np.loadtxt(
    "marks_with_header.csv",
    delimiter=",",
    skiprows=1,
    usecols=(1, 2),
    dtype=np.int64
)

print(scores)

Expected Output#

TEXT
[[85 90]
 [78 88]
 [92 95]]

usecols=(1, 2) मध्ये 1 म्हणजे दुसरा column आणि 2 म्हणजे तिसरा column.

कारण NumPy मध्ये column indexing 0 पासून सुरू होते.

Figure 3: usecols=(1, 2) वापरून निवडक columns load करणे
usecols=(1, 2) वापरून निवडक columns load करणेstudent_id101102103math857892science908895selectselectusecols=(1, 2)Math आणि Science loadकराusecols=(1, 2) Math आणि Science load करा

एकच Column निवडल्यास काय होते?#

PYTHON
math_marks = np.loadtxt(
    "marks_with_header.csv",
    delimiter=",",
    skiprows=1,
    usecols=1
)

print(math_marks)
print(math_marks.shape)

Expected Output#

TEXT
[85. 78. 92.]
(3,)

एकच column load केल्यामुळे result (3,) shape चा 1D array आहे.

हा मुद्दा पुढे ndmin समजताना महत्त्वाचा आहे.

10. max_rows — File मधील मर्यादित Data Load करणे#

मोठ्या file वर काम सुरू करण्याआधी पहिल्या काही rows पाहायच्या असतील तर max_rows उपयोगी पडतो.

उदाहरण:

PYTHON
import numpy as np

preview = np.loadtxt(
    "marks_with_header.csv",
    delimiter=",",
    skiprows=1,
    max_rows=2,
    dtype=np.int64
)

print(preview)

Expected Output#

TEXT
[[101  85  90]
 [102  78  88]]

File मध्ये तीन data rows होत्या.

पण max_rows=2 असल्यामुळे NumPy ने दोन data rows load केल्या.

Current NumPy behavior मध्ये empty lines आणि comment-only lines max_rows च्या data-row count मध्ये मोजल्या जात नाहीत. skiprows मात्र physical lines skip करतो.

Key Idea

skiprows सांगतो सुरुवातीच्या किती lines वगळायच्या, तर max_rows सांगतो त्यानंतर किती data rows वाचायच्या.

11. Comment Lines Handle करणे#

Numerical files मध्ये माहिती देण्यासाठी comment lines असू शकतात.

उदाहरण:

File line Raw content
1 # sensor_id,temperature
2 1,24.5
3 2,25.0
4 # recalibrated sensor
5 3,24.8

np.loadtxt() मध्ये default comment marker # आहे.

त्यामुळे # ने सुरू होणारा comment data म्हणून parse केला जात नाही.

PYTHON
import numpy as np

sensor_data = np.loadtxt(
    "sensor.csv",
    delimiter=","
)

print(sensor_data)

Expected Output#

TEXT
[[ 1.  24.5]
 [ 2.  25. ]
 [ 3.  24.8]]

Comment lines array मध्ये rows म्हणून आलेल्या नाहीत.

जर वेगळा comment marker वापरला असेल तर comments parameter देता येतो.

उदाहरण:

PYTHON
data = np.loadtxt(
    "readings.txt",
    comments=";"
)

इथे ; comment marker म्हणून वापरला जाईल.

12. 1D आणि 2D Result समजून घेणे#

File मध्ये data आहे म्हणजे result नेहमी 2Dच येईल असे नाही.

हे loaded structure वर अवलंबून असते.

उदाहरणार्थ एकच selected column:

PYTHON
math_marks = np.loadtxt(
    "marks_with_header.csv",
    delimiter=",",
    skiprows=1,
    usecols=1
)

print(math_marks.shape)

Expected Output#

TEXT
(3,)

हा 1D array आहे.

पण काही processing pipelines मध्ये आपल्याला single column असला तरी (3, 1) अशी 2D shape हवी असू शकते.

इथे ndmin मदत करतो.

13. ndmin — Minimum Dimensions ठरवणे#

ndmin म्हणजे minimum number of dimensions.

आपण ndmin=2 दिले तर result किमान 2D ठेवला जातो.

PYTHON
import numpy as np

math_marks = np.loadtxt(
    "marks_with_header.csv",
    delimiter=",",
    skiprows=1,
    usecols=1,
    ndmin=2
)

print(math_marks)
print(math_marks.shape)

Expected Output#

TEXT
[[85.]
 [78.]
 [92.]]
(3, 1)

आधी result (3,) होता.

आता तो (3, 1) आहे.

Values बदलल्या नाहीत.

फक्त array ची dimensional structure बदलली.

Remember

ndmin=2 data मध्ये नवीन observations तयार करत नाही. तो result किमान 2-dimensional representation मध्ये ठेवतो.

ndmin साठी valid basic values 0, 1, आणि 2 आहेत.

14. महत्त्वाचे Parameters एका ठिकाणी#

Parameter काम छोटा Example
fname कोणती file load करायची "marks.csv"
delimiter values कोणत्या separator ने वेगळ्या आहेत delimiter=","
dtype result चा data type dtype=np.int64
skiprows सुरुवातीच्या lines skip करणे skiprows=1
usecols specific columns load करणे usecols=(1, 2)
max_rows मर्यादित data rows load करणे max_rows=100
comments comment marker ओळखणे comments="#"
ndmin minimum dimensions ठरवणे ndmin=2

हे parameters वेगवेगळ्या problems solve करतात.

त्यांना blindly वापरण्यापेक्षा file कशी आहे ते पाहून योग्य parameters निवडणे महत्त्वाचे आहे.

15. Parameters एकत्र वापरणे#

Real work मध्ये अनेक parameters एकत्र वापरले जातात.

समजा file मध्ये header आहे.

आपल्याला फक्त Math आणि Science columns पाहायचे आहेत.

फक्त पहिल्या दोन students चा preview हवा आहे.

Result integer हवा आहे.

PYTHON
import numpy as np

scores = np.loadtxt(
    "marks_with_header.csv",
    delimiter=",",
    skiprows=1,
    usecols=(1, 2),
    max_rows=2,
    dtype=np.int64
)

print(scores)

Expected Output#

TEXT
[[85 90]
 [78 88]]

या एका statement मध्ये:

  • delimiter="," → comma-separated values समजल्या
  • skiprows=1 → header वगळला
  • usecols=(1, 2) → Math आणि Science columns घेतले
  • max_rows=2 → दोन data rows घेतल्या
  • dtype=np.int64 → integer array तयार केला

या parameters चा combination समजणे हे फक्त syntax लक्षात ठेवण्यापेक्षा जास्त महत्त्वाचे आहे.

16. Common Parsing Error — Numeric नसलेली Value#

np.loadtxt() simple structured data साठी strict आहे.

समजा numeric column मध्ये अशी row आली:

102,absent,88

आपण floating-point किंवा integer data load करत असू तर absent हा valid number नाही.

अशावेळी parsing fail होऊ शकते.

Common Mistake

File extension .csv आहे म्हणून file आपोआप valid numeric CSV आहे असे समजू नका. Actual file content तपासा.

जर file मध्ये missing values, mixed text आणि numbers किंवा irregular formatting असेल तर np.loadtxt() प्रत्येक वेळी योग्य tool असेलच असे नाही.

17. Common Column-Count Error#

समजा file अशा प्रकारची आहे:

Row Raw content
1 101,85,90
2 102,78
3 103,92,95

पहिल्या row मध्ये तीन values आहेत.

दुसऱ्या row मध्ये फक्त दोन values आहेत.

जर आपण सर्व columns load करण्याचा प्रयत्न केला तर rows ची structure consistent नाही.

np.loadtxt() ला सामान्यतः प्रत्येक loaded row मध्ये compatible number of values अपेक्षित असतात. Official documentation देखील सर्व values load करण्यासाठी rows मध्ये समान number of values आवश्यक असल्याचे नमूद करते.

हा error का महत्त्वाचा आहे?#

NumPy array rectangular structure मध्ये असतो.

2D array मध्ये प्रत्येक row ला consistent number of columns लागतात.

एका row मध्ये तीन values आणि दुसऱ्या row मध्ये दोन values असतील तर clean 2D numeric structure तयार करणे शक्य होत नाही.

18. Wrong delimiter मुळे Parsing Error#

File:

101,85,90

पण code:

PYTHON
data = np.loadtxt("marks.csv")

इथे comma delimiter सांगितलेला नाही.

Default parsing whitespace शोधत आहे.

म्हणून 101,85,90 हे expected numeric fields म्हणून parse होणार नाही.

Correct approach:

PYTHON
data = np.loadtxt(
    "marks.csv",
    delimiter=","
)

जेव्हा parsing error येतो तेव्हा सर्वप्रथम file चा actual separator तपासा.

19. Analysis आधी Loaded Data Validate करा#

File successfully load झाली म्हणजे data analysis साठी योग्यच आहे असे नाही.

आपण काही basic checks करायला हवेत.

1. Shape तपासा#

PYTHON
print(data.shape)

Expected rows आणि columns आले आहेत का ते पाहा.

2. Number of Dimensions तपासा#

PYTHON
print(data.ndim)

आपल्याला 2D dataset अपेक्षित असताना 1D result आला आहे का ते लगेच समजू शकते.

3. Data Type तपासा#

PYTHON
print(data.dtype)

Expected numeric type मिळाला आहे का ते पाहा.

4. Invalid Numerical Values तपासा#

Floating-point data मध्ये NaN किंवा infinity सारख्या special values असू शकतात.

np.isfinite() प्रत्येक value finite आहे का हे तपासण्यास मदत करते.

PYTHON
import numpy as np

data = np.loadtxt(
    "sensor_values.csv",
    delimiter=","
)

print("Shape:", data.shape)
print("Dimensions:", data.ndim)
print("All values finite:", np.isfinite(data).all())

जर file मध्ये तीन rows आणि दोन valid numeric columns असतील:

Expected Output#

TEXT
Shape: (3, 2)
Dimensions: 2
All values finite: True

True म्हणजे सगळ्या loaded values finite आहेत.

हे छोटं validation पुढच्या analysis मध्ये चुकीचे assumptions जाण्यापासून वाचवू शकते.

20. Practical Validation Pattern#

Job-oriented code मध्ये data load केल्यानंतर आपल्याला expected structure माहित असेल तर तो verify करणे चांगली सवय आहे.

PYTHON
import numpy as np

data = np.loadtxt(
    "sensor_values.csv",
    delimiter=",",
    ndmin=2
)

if data.shape[1] != 2:
    raise ValueError("Expected exactly 2 columns")

if not np.isfinite(data).all():
    raise ValueError("Data contains non-finite values")

print("Data is ready for analysis")

Expected Output#

TEXT
Data is ready for analysis

या code मध्ये दोन assumptions validate केल्या:

पहिली — प्रत्येक row मध्ये दोन columns पाहिजेत.

दुसरी — values finite असल्या पाहिजेत.

दोन्ही conditions योग्य असतील तरच analysis पुढे नेला जातो.

Key Idea

Data loading आणि data validation या दोन वेगळ्या गोष्टी आहेत. File read झाली म्हणजे data logically correct आहे याची हमी मिळत नाही.

21. np.loadtxt() कधी योग्य आहे?#

np.loadtxt() विशेषतः उपयोगी आहे जेव्हा:

  • file text-based आहे
  • data मुख्यतः numerical आहे
  • rows आणि columns regular आहेत
  • delimiter स्पष्ट आहे
  • missing किंवा malformed values फारशा नाहीत
  • आपल्याला थेट NumPy array हवा आहे

Clean numerical files साठी हे simple आणि effective solution आहे.

22. Common Mistakes#

1. CSV साठी delimiter विसरणे#

Wrong:

PYTHON
data = np.loadtxt("marks.csv")

Comma-separated file असल्यास:

PYTHON
data = np.loadtxt(
    "marks.csv",
    delimiter=","
)

2. Header skip न करणे#

Header numeric नसल्यास parsing fail होऊ शकते.

योग्य parameter:

PYTHON
skiprows=1

3. usecols मध्ये 1-based indexing समजणे#

usecols=(1, 2) म्हणजे first आणि second columns नाहीत.

ते second आणि third columns आहेत.

पहिला column index 0 आहे.

4. File clean आहे असे assume करणे#

Column counts आणि numeric values तपासल्याशिवाय मोठा analysis सुरू करू नका.

5. 1D result पाहून घाबरणे#

Single column load केल्यास (n,) result मिळू शकतो.

2D structure आवश्यक असेल तर ndmin=2 विचारात घ्या.

6. dtype blindly force करणे#

Actual file data शी incompatible dtype दिल्यास parsing fail होऊ शकते.

23. Hands-On Check#

Requirement

तुमच्याकडे sales.csv आहे.

त्याची पहिली line header आहे.

बाकी columns आहेत:

product_id,quantity,price

Your Task

NumPy code लिहा ज्यामध्ये:

  • comma delimiter वापरला जाईल
  • header skip केला जाईल
  • फक्त quantity आणि price columns load केले जातील
  • जास्तीत जास्त पहिल्या 5 data rows load केल्या जातील
  • result किमान 2D ठेवला जाईल
  • शेवटी shape आणि dtype print केले जातील

24. Interview Preparation#

What is numpy.loadtxt() used for?Show Answer

numpy.loadtxt() is used to read simply formatted text-based numerical data and convert it into a NumPy array. It supports controls such as delimiter selection, data type specification, row skipping, column selection, row limits, comments, and minimum dimensions.

Key Points:

  • Reads numerical text data
  • Returns a NumPy ndarray
  • Best suited to regular, consistently formatted files
  • Supports parameters such as delimiter, dtype, skiprows, usecols, and max_rows

Why interviewer asks this:

हे प्रश्न candidate ला basic NumPy data-ingestion workflow समजतो का हे तपासण्यासाठी विचारले जाऊ शकते.


What is the difference between skiprows and usecols in numpy.loadtxt()?Show Answer

skiprows controls how many lines are ignored from the beginning of the input, while usecols controls which columns are extracted from the remaining data. usecols uses zero-based column indexes.

Key Points:

  • skiprows operates on beginning lines
  • usecols selects columns
  • Column indexes start at 0
  • Both parameters can be used together

Why interviewer asks this:

हे दोन parameters beginner अनेकदा confuse करतो. Interviewer ला candidate parameter चा purpose समजून वापरतो का ते पाहायचे असते.

25. या Chapter मधून काय लक्षात ठेवायचे?#

  • np.loadtxt() clean numerical text data NumPy array मध्ये load करते.
  • Whitespace-separated data साठी default behavior पुरेसे असू शकते.
  • CSV साठी सामान्यतः delimiter="," द्यावा लागतो.
  • dtype result चा numerical data type नियंत्रित करतो.
  • skiprows सुरुवातीच्या lines वगळतो.
  • usecols specific columns निवडतो आणि indexing 0 पासून सुरू होते.
  • max_rows किती data rows load करायच्या ते नियंत्रित करतो.
  • Default # comments parsing मधून ignore होतात.
  • Single column load केल्यास 1D array मिळू शकतो.
  • ndmin=2 result किमान 2D ठेवण्यास मदत करतो.
  • Analysis आधी shape, ndim, dtype आणि data validity तपासणे चांगली सवय आहे.
  • Parsing error आल्यास delimiter, header, numeric values आणि column counts तपासा.
Summary

File load करण्याचे syntax लक्षात ठेवणे पुरेसे नाही. File ची structure समजून योग्य parsing parameters निवडणे आणि loaded array validate करणे हेच reliable data-analysis workflow चे खरे उद्दिष्ट आहे.

Interactive learning

Practice lab

Apply this chapter with guided activities, immediate feedback, explanations, and retry.

Practice loads when this section enters view.