2026-08-26 12:19
Status:
Tags: IBM IBM Full Stack Software Developer Professional Certificate IBM Python for Data Science, AI & Development Data Science Python Pandas Numpy Math Python Programming Linear Algebra
PDSAD - Module 4 - Working With Data in Python
==Reading and Writing Files with Open
-
Reading Files with Open:
- File Object python has a built in
openfunction that is used to basically create one of these, allowing you to read and write to a given file using code - You can open a file using something like
file1 = open("path/to/file/file.txt", "r"), withrbeing the mode for reading the file, and thenwfor writing to the file, and thenafor appending - You can do things like
file1.nameto get basic attributes of the file, like for example the name of the file itself, and not necessarily the content of the file - You can use
file.modeto see what mode the file is in - You need to close each file with
file1.close()so you do not leak any memory - Some lazy fucks though that writing close was way too much fucking work apparently, so instead they have something called
with open(path/to/file.txt) as file1:and then whatever code block you want to do with the file. - At which point, whenever that code block ends, I assume that the file is closed automatically, basically just for convenience
- You can output every single line inside of a file was a element in a list using the
file1.readlines()method which does just that, splitting them all up for you based on each line for easier reading - You can use
file1.readline()to read only one line at a time if that is what you would want to do - When giving a numbered argument to the
readlines(4)function, that would actually get the first 4 characters of the file and then allow you to read it from where, which I assume would let you just go character by character until you hit a space or something which is how you would figure out going word by word - WHICH IS DUMB, WHY IS THAT A THING, THEY SHOULD HAVE A FUNCTION FOR THAT, BUT THEY’RE TOO FUCKING LAZY TO TYPE IN THE CLOSE FUNCTION
- File Object python has a built in
-
Writing Files with Open:
- You can also write to files inside of python using the
openfunction with the previously mentionedwmode - This lets you create something like a file object, upon which you can then use something like
file1.write("Your Content")and write that data into the file, let it be known that I believe that this would overwrite any of the data inside of the file currently - This can also I believe be used to create a new file as well, with something like
open(/path/to/new/file.txt, w)with the strings in though, that would then actually create that new file, I could be wrong though - You can also use the
withkeyword and what not as well just as you would have inside of the file - I actually might be wrong, I guess that writing or using that above
write()function does not overwrite the entire contents of the file as it does in my own language, but actually seems to append to it somehow, which I mean fair enough - Hmmm, it seems that the
amethod or append is basically just going to open the file and in fact append to it like how write would, but the only difference is that it does not overwrite the entire file and what not, either way I would not be too worried about this (hopefully)
- You can also write to files inside of python using the
-
Writing Files with Open (The Reading):
| Mode | Syntax | Description |
|---|---|---|
| ‘r’ | ‘r’ | Read mode. Opens an existing file for reading. Raises an error if the file doesn’t exist. |
| ‘w’ | ‘w’ | Write mode. Creates a new file for writing. Overwrites the file if it already exists. |
| ‘a’ | ‘a’ | Append mode. Opens a file for appending data. Creates the file if it doesn’t exist. |
| ‘x’ | ‘x’ | Exclusive creation mode. Creates a new file for writing but raises an error if the file already exists. |
| ‘rb’ | ‘rb’ | Read binary mode. Opens an existing binary file for reading. |
| ‘wb’ | ‘wb’ | Write binary mode. Creates a new binary file for writing. |
| ‘ab’ | ‘ab’ | Append binary mode. Opens a binary file for appending data. |
| ‘xb’ | ‘xb’ | Exclusive binary creation mode. Creates a new binary file for writing but raises an error if it already exists. |
| ‘rt’ | ‘rt’ | Read text mode. Opens an existing text file for reading. (Default for text files) |
| ‘wt’ | ‘wt’ | Write text mode. Creates a new text file for writing. (Default for text files) |
| ‘at’ | ‘at’ | Append text mode. Opens a text file for appending data. (Default for text files) |
| ‘xt’ | ‘xt’ | Exclusive text creation mode. Creates a new text file for writing but raises an error if it already exists. |
| ‘r+’ | ‘r+‘ | Read and write mode. Opens an existing file for both reading and writing. |
| ‘w+’ | ‘w+‘ | Write and read mode. Creates a new file for reading and writing. Overwrites the file if it already exists. |
| ‘a+’ | ‘a+‘ | Append and read mode. Opens a file for both appending and reading. Creates the file if it doesn’t exist. |
| ‘x+’ | ‘x+‘ | Exclusive creation and read/write mode. Creates a new file for reading and writing but raises an error if it already exists. |
==Pandas
-
Pandas: Loading Data:
- Pandas is a popular library inside of python that is used for data analysis
- You can import it using
import pandaswhich gives you access to a bunch of different pre-built classes and functions that allow you to do a bunch of stuff with data - Some of the given things they mentioned in their chart are
read_csv(), Series(), DataFrame, & Values - You need to make sure that the library is also installed inside of whatever environment you are in so just use
pyor whatever the fuck the python package manager is to install your dependencies
-
A DataFrame is a two-dimensional, size-mutable, and potentially heterogeneous tabular data structure with labeled axes (rows and columns).
-
A Series is a one-dimensional labeled array, essentially a single column or row of data.
- You can open a
.csv, which is basically a file that is plain text and stores data in a table format with rows and columns usingdataframe = pandas.read_csv(/path/to/file.csv) - Some mother fuckers are SUPER lazy and do not want to type out the word pandas all the time, so they might important pandas as a shorter thing to make it easier, basically
import pandas as pdor whatever the fuck - Pandas allows you to work with data via the use of dataframes which you can convert something like a
.csvfile into a dataframe - This is the object that is returned inside of the
dataframe = pd.read_csv(csv_path)and gives you a bunch of different options for how you want to access the data inside of the dataframe - You can for example use
dataframe.head()to examine the first five rows of a data frame - Similarly, you can do something with
Excelwhere you just have thedataframe = pd.read_excel(xlsx_path)and then you can manipulate it the same way to get whatever data you want out of it - it seems to me like this is generally used to transform common storage methods of data into something that you can then process and access programmically
- A dataframe is made up of different rows and columns which each have a different head for the column as seen in the image above, and then each given row for each entry inside of this dataframe
- It looks to me to be very similar to something akin to the
sqlitedatabase tables where a column is a new attribute to a given object and the rows are the entries that hold those attributes - You can also actually create a dataframe yourself programmically using something like a dictionary, for which the code is actually shown above
- The keys would be the column labels, and then the lists would be the values for each of those column attributes for each row
- You can then cast the dictionary over to a dataframe using the
song_frames = pd.DataFrame(songs)function - It seems you can actually index the data inside of a data frame object similar to how you might do so using an array or list, with
newDataFrame=dataFrame['Column1, Column2, Colum3]which will COPY OVER the data found inside of those columns into a new dataframe as seen sort of in the image above - Notice that this can be done with either a single column of a dataframe, or with multiple columns
- If you wish to find a specific item, like not just a whole row or whole column, you can do so using the
iloc[rowIndex, columnIndex]which then lets you get a single item inside of the entire chart - Instead of just doing this with the pure numbers as shown in the images above, you can actually also do this with the name of the column and the number of the row, so for the above dataframe, you can use something like
dataframe.loc[0, 'Artist']:'Michael Jacksonto get a specific item, NOTICE IT ISlocNOTiloc loc (not iloc I guess)function can also be used whenever you have something that does not have an integer value for it’s row list, so day you make a new dataframe and then do something likedataframe_new.index = ['a', 'b', 'c']and so on, then you can still use thedf.loc['a', 'Artist']to get the given value at that place in the dataframe- You can also use the
z=dataframe.iloc[0:2, 0:3]in order to slice up your dataframe and then create a new one from that, letting you basically take out chunks of data at your leisure should you so choose to do so
-
Pandas: Working with and Saving Data:
-
-
Image you have millions of these blocks of different colors and you want to figure out how many given unique elements are in a given column inside of your dataframe
-
The thing is that
pandashas something calledunique()which can help you determine exactly that, the number of unique elements in a given data frame -
-
For the above example, say you want to find out how many actual unique values of years there are for the album release data
-
For this, you basically are able to use something akin to
df['Released'].unique()in order to get what I can assume is either a list or a dataframe holding only the unique items inside of that list -
-
Say for the above database, you want to create a new database for songs that would only contain songs released after the year 1980
-
To do this, you would have to look inside of the
releasedcolumn in the dataframe and then select every single row that you find that has a year greater than 1979 -
You can do something like
dataframe['Released]>1979which returns to you a list of boolean values for each of the given columns that meets that fact, first it would get the entire column that you wanted, and then go over each of the rows in that column to let you know which one is true in the comparison -
-
You can then basically create a new data frame out of this using
dataFrame1980 = songDataframe[songDataframe['Released']>1979]which basically what it does right, the inner most code would check over the entire released column and return it’s own list of boolean values. These boolean values are then given over to the given list in quest, which no longer really cares for what it is looking for, it just goes in the given order and then appends those rows over to the new dataframe -
You basically index the song dataframe using it’s own list of boolean values to create a brand new dataframe
-
You can then also actually save this new dataframe using the
df1.to_csv('new_songs.csv')method which as you can guess basically just converts the dataframe into a.csvformat and allows you to export it as a file for whatever purpose you would want to
-
-
Pandas (The Reading):
==Numpy in Python
-
One Dimensional Numpy:
-
Numpy is a scientific library inside of python used for mathematical computation
-
Numpy is also VERY fast and is pretty good for memory whenever it all comes into consideration, especially when considering that you are still basically using the slow shit that is python
-
Numpy is also the basis of pandas, and so they are somewhat similar, it is sort of the thing running under the hood of it all
-
How to create a Numpy array
- A python list is a container that lets you dynamically store different data types in a single variable
- Each element is associated with a single index, and can be found at an index with the
[]operator - A Numpy Array is similar to a list, but it is fixed in size, and each element is of the same type, so basically, shit ain’t a fucking list, its an array from C or C++ basically
- You can cast a python list to a numpy array using
import numpy as npand then obviously something likea = np.array([1, 2, 3, 4, 5]), and you can access it very same as you would a regular python list
-
The type of a numpy array is
type(a) = numpy.ndarray, and since each element inside of a numpy array is the exact same type, you can basically do something likea.dtype:dtype('int64')to get the data type of the elements in the array -
Fun fact, as it turns out with that little example, I would assume that python stores all of it’s data as doubles (8 bit data types) then instead of regular 4 bit integers, it might just be a numpy thing though
-
Basic Numpy Array Attributes
a=np.arra([0, 1, 2, 3, 4])a.sizeis the number of elements inside of the arraya.ndimrepresents the number of array dimensions, or the rank of the array, which i can assume is useful for things pertaining to linear algebraa.shapeindicates the size of the array in each dimension, so say you have something like a 2 D matrix that is 3 by 5, it would give you 3 by 5, for theaexample, the shape is just 5
-
You can also create a numpy array using float values like
a = np.array([1.2, 1.4, 1.6])and this would have a type ofa.dtype:dtype('float64) -
Check out Numpy’s Own Docs for more information
-
Indexing and Slicing Methods
- You can index the numpy array just like you would any other array just using
a[0] = 100or something like that to change the first element of the array - I assume that it would also be pretty easy to slice the array the exact same way that you would with python, so something like
a[0:4]would give you the first 4 elements of the entire array basically, like lists, you DO NOT COUNT THE LAST ELEMENT OF THE INDEX, but basically it works that way because of the whole arrays start at zero thing - You can also slice and assign new values using
a[3:5] = 300, 400to change each value
- You can index the numpy array just like you would any other array just using
-
Basic Operations done in data science
-
The basic operations that you can do in numpy on data are generally a bit smoother and less computationally intensive than they would be in regular python (how the fuck? I guess because they wrote it in C)
-
-
-
Vector Addition- oh yeah baby, linear algebra, basically vector addition is when you have a one dimensional matrix with only a single column and a bunch of rows. To add to vectors, you basically just add them in order to how the rows correspond to one another
-
To do this in regular python, you can use a list and then loop over each index and add them into a new list
-
In the above hand images you can see how this addition would work in terms of math, and the
tip-to-tailmethod where in which one vector (a point in space with a magnitude) is placed at the tip of another allowing them to point to a given spot in space which is where the addition value of them points, very neat 2 D and 3 D stuff -
-
Anyways as I said, you would need something akin to a for loop in order to do this in python because whenever you add two lists in python it just concatenates them. So instead, in numpy you can just do
u=np.array([1, 0]),v=np.array([0,1]), and then a simplez=u+vwhich is equal toz:array([1,1]), so basically clean addition of the matrix values -
-
I also them assume that this would work for things like subtraction, division, and multiplication, and I can assume that once you get to things like matrices with more than one dimension, it does the whole box multiplication for you as well
-
Which yes, I was in fact correct
-
-
-
This would also work well with scalars and what not which is once again just a linear algebra thing
-
-
The Dot Product is also something that you can perform on two given matrices or vectors inside of linear algebra, and is basically used to represent how similar two vectors are according to the video
-
You basically take the first values multiplied, add them to the second values multiplied, and then that is how similar the given vectors are
-
You can do this with the
np.dot(u,v)to perform dot multiplication on a series of of vectors or matrices (i assume so at least), which is once again very fast and very simple to do with numpy as opposed to just regular python -
Universal Functions are functions that operate on
ndarrays, and these are what seems to be some built in functions that are used for basic things with data -
So you can have something like
a=np.array([1, -1, 1, -1])and then have something likemeanA = a.mean()which would calculate the average of all of the elements in the array, which in the given case would be 0 -
There are a lot of different universal functions as well, like
max(), min(), etc -
-
Numpy also has a built in
np.pi, which I mean, isn’t too surprising, basically though the above hand just shows that you can apply entire operations to a given array inside of numpy, so if I wanted to find thenp.sin(x)where x was an entire vector or numpy array, then I can easily do so using exactly that syntax -
-
np.linspae(-2,2,num=5)is a useful mathematical function that is used for plotting mathematically functions, which basically plots out a given, evenly spaced number of values over a given interval -
So in the above hand example, you have a start point of -2, a end point of 2, and then a range of 5, where in which they’re are 5 total elements inclusive of the endpoints
-
-
The above hand code basically, whenever run inside of something like a juypter notebook, lets you actually plot this entire graph inside of a given cell or whatever the fuck and you can showcase the graph of sin this way if you wanted to
-
Obviously pretty useful for things like data that you customized yourself and what not
-
-
Matrix Mathematics:
-
Two Dimensional Numpy:
- Two Dimensional Arrays basically, you can have lists nested inside of lists inside of python, and these are naturally called nested lists or 2 D lists, there is no real limited to how nested a given list could be, and you can have VERY high dimensions of arrays
- Essentially, these 2 D lists are used to create Two Dimensional Numpy Arrays, which are also called matrices
- Note that you case them the exact same what that you would with a regular vector list as well, it’s just that for the sake of 2 dimensions that they people in the video drew them that way
- You can use
.ndimin order to obtain the number of axis that a single array has, or the number of dimensions that it is able to carry - It is basically the number of nested lists that exist within of the object
- Once again, you can have something like
shapewhich for the above hand matrix would return 3, 3 because it is a matrix with 3 rows and 3 columns - You can also use
sizefor the size of the ENTIRE array, or basically how many actual given number values would exist inside of the nested arrays that you have in the matrix, which is good for getting the total number of elements - You can index the two dimensional numpy array just how you would index a 2 D list in python, using the double
[][]operator with each on corresponding to a given row and then a given column - You can also obviously use a single
[]operator in order to get access to an entire row inside of your matrix that how you would with a 2 D list in python - You can also slice using numpy arrays, so
a[0,0:2]would give you the first 2 elements of the first row inside of the matrix, you have to be careful of course to not have an index out of bounds error though - You can also add in new arrays, and the process is basically the same as matrix addition, which is really the simply thing with matrices, and basically words the same as a given scalar but in the 4 different dimensions
- This is once again handled for you very will with just a simple
z = x + ywhere x and y are matrices (of I assume the same size? idk linear algebra fr), and this results in a third matrix of the added elements - This z matrix is the exact same size of matrices x and y
- Scalars are basically also just as simple where you basically scale every single element upwards by whatever the scalar value is, and you can just do this using
z = 2yinside of numpy, which is really handy honestly - Multiplication of two different arrays consists of basically a bit more of a fucked scenario, where in which you sort of have to flip multiply each row by each given column, and a good visual representation is to kind of flip the left hand side matrix counter clockwise one rotation and then have it move down and multiply out each time, with the addition of those products being the final element
- This is what I was actually thinking of, and you need to make sure that the number of rows in matrix A corresponds to the number of columns in matrix B
- You can perform this operation using the
np.dot(a, b)function inside of numpy - Oh shit apparently that is not what Hadar multiplication is where you basically just multiply them one to one, I was thinking of another kind of multiplication
- This one is pretty straight forward in that case, not as complicated as what I had imagined myself
-
Beginners Guide to Numpy (The Reading):
- Needed Text To close?
==Glossary
| Term | Definition |
|---|---|
| .csv file | A .csv (Comma-Separated Values) file is a plain text file format for storing tabular data, where each line represents a row and uses commas to separate values in different columns. |
| .txt file | A .txt (Text) file is a common file format that contains plain text without specific formatting, making it suitable for storing and editing textual data. |
| Append | To “append” means to add or attach something to the end of an existing object, typically used in the context of adding data to a file or elements to a data structure like a list in Python. |
| Attribute | An “attribute” in Python refers to a property or characteristic associated with an object, which can be accessed using dot notation. |
| Broadcasting in NumPy | Broadcasting in NumPy allows arrays with different shapes to be combined in element-wise operations by automatically extending smaller arrays to match the shape of larger ones, making operations more flexible. |
| Component | In NumPy, a “component” typically refers to a specific element or value within a multi-dimensional array, which can be accessed using indexing. |
| Computation | Computation in NumPy involves performing numerical operations on arrays and matrices, making it a powerful library for mathematical and scientific computing in Python. |
| Data analysis | Data analysis is the process of inspecting, cleaning, transforming, and interpreting data to discover useful information, draw conclusions, and support decision-making. |
| DataFrames | A DataFrames in Pandas is a two-dimensional, tabular data structure for storing and analyzing data, consisting of rows and columns. |
| Dependencies | Dependencies in Pandas are external libraries or modules, such as NumPy, that Pandas rely on for fundamental data manipulation and analysis functionality. |
| File attribute | File attributes generally refer to properties or metadata associated with files, which are managed at the operating system level. |
| File object | A “file object” in Python represents an open file, allowing reading from or writing to the file. |
| Grid | In Python, a “grid” typically refers to a two-dimensional structure composed of rows and columns, often used to represent data in a tabular format or for organizing objects in a coordinate system. |
| Hadamard Product | The Hadamard product is a mathematical operation that involves element-wise multiplication of two matrices or arrays of the same shape, producing a new matrix with each element being the product of the corresponding elements in the input matrices. |
| Importing pandas | To import Pandas in Python, you use the statement: import pandas as pd, which allows you to access Pandas functions and data structures using the abbreviation “pd.” |
| Index | In Python, an “index” typically refers to a position or identifier used to access elements within a sequence or data structure, such as a list or string. |
| Libraries | Libraries in Python are collections of pre-written code modules that provide reusable functions and classes to simplify and enhance software development. |
| Linspace | In Python, “linspace” refers to a NumPy function that generates an array of evenly spaced values within a specified range. |
| NumPy | NumPy in Python is a fundamental library for numerical computing that provides support for large, multi-dimensional arrays and matrices, as well as a variety of high-level mathematical functions to operate on these arrays. |
| One dimensional NumPy | A one-dimensional NumPy array is a linear data structure that stores elements in a single sequence, often used for numerical computations and data manipulation. |
| Open function | In Python, the “open” function is used to access and manipulate files, allowing you to read from or write to a specified file. |
| Pandas | Pandas is a popular Python library for data manipulation and analysis, offering data structures and tools for working with structured data like tables and time series. |
| Pandas library | Pandas library in Python refer to the various modules and functions within the Pandas library, which provides powerful data structures and data analysis tools for working with structured data. |
| Plotting Mathematical Functions | Plotting mathematical functions in Python involves using libraries like Matplotlib to create graphical representations of mathematical equations, aiding visualization, and analysis. |
| Shape | In NumPy, “shape” refers to an array’s dimensions (number of rows and columns), describing its size and structure. |
| Slicing | Slicing in NumPy entails extracting specific portions of an array by specifying a range of indices, enabling you to work with subsets of the data. |
| Two dimensional NumPy | A two-dimensional NumPy array is a structured data representation with rows and columns, resembling a matrix or table, ideal for various data manipulation and analysis tasks. |
| Universal Functions | Universal functions (ufuncs) in NumPy are functions that operate element-wise on arrays, providing efficient and vectorized operations for a wide range of mathematical and logical operations. |
| Vector addition | Vector addition in Python involves adding corresponding elements of two or more vectors, producing a new vector with the sum of their components. |
| Visualizations | Visualizations in Python refer to the creation of graphical representations, such as charts, plots, and graphs, to illustrate and communicate data and trends visually. |
==Summary
- Python uses the open() function and allows you to read and write files, providing access to the content within the file for reading. It also allows overwriting it for writing and specifies the file mode (for example, r for reading, w for writing, a for appending).
- To read a file, Python uses an open function along with r.
- Python uses the open with function to read and process a file attribute, that is, from open to close.
- In Python, you use the open method to edit or overwrite a file.
- To write a file, Python uses the open function along with w.
- In Python, “a” indicates that the program has appended to the file.
- In Python, “\n” signifies that the code should start on a new line.
- Python uses various methods to print lines from attributes.
- Pandas is a powerful Python library for data manipulation and analysis, providing data structures and functions to work with structured data like data frames and series.
- You import the file (panda) by using the import command followed by the file name.
- In Python, you use the as command to provide a shorter name for the file.
- In Pandas, you use a data frame (df) to specify the files to read.
- DataFrames consist of rows and columns.
- You can create new DataFrames by using the column or columns of a specific DataFrame.
- We can work with data in a DataFrames and save the results in different formats.
- In Python, you use the Unique method to determine unique elements in a column of the DataFrames.
- You use the inequality operator along with df to assign a Boolean value to the selected column in DataFrames.
- You save a new DataFrame as a different DataFrame, which may contain values from an earlier DataFrame.
- NumPy is a Python library for numerical and matrix operations, offering multidimensional array objects and a variety of mathematical functions to work with data efficiently.
- NumPy is a basis for Pandas.
- A NumPy array or ND array is similar to a list, usually of a fixed size with the same kind of element.
- A one-dimensional NumPy array is a linear sequence of elements with a single axis, like a traditional list, but optimized for numerical computations and array operations.
- You can access elements in a NumPy using an index.
- You use the attribute dtype to get the data type of the array elements.
- You use size and ndim to get the size and dimension of the array, respectively.
- You can use indexing and slicing methods in NumPy.
- Vector additions are widely used operations in Python.
- Representing vector addition with line segments or arrows is useful.
- NumPy codes work much faster, which is helpful with lots of data.
- You perform vector subtraction by replacing the addition sign with a negative sign.
- Multiplying an array by a scalar in Python entails multiplying each element of the array by the scalar value, leading to a new array in which each element scales by the scalar.
- Hadamard product refers to the element-wise multiplication of two arrays of the same shape, resulting in a new array where each element is the product of the corresponding elements in the input arrays.
- The dot product in Python is the sum of the element-wise products of two arrays, often used for vector and matrix operations to find the scalar result of multiplying corresponding elements and summing them.
- When working with NumPy, it is common to utilize libraries like Matplotlib to create graphs and visualizations from numerical data stored in NumPy arrays.
- A two-dimensional NumPy array is a grid-like structure with rows and columns suitable for representing data as a matrix or a table for numerical computations.
- In NumPy, “shape” refers to an array’s dimensions (number of rows and columns), indicating its size and structure.
- You use the attribute “size” to obtain the size of an array.
- You use rectangular attributes to access the various elements in an array.
- You use a scalar to multiply elements in NumPy.
References
Check out Numpy’s Own Docs for more information
































