TIL: Learning Python Pandas
Having to learn how to process data for work, so started working with pandas tonight. I’d used it in an online course a while back, but honestly I’ve forgotten everything about it. So I started tonight by taking note of everything that I needed to be able to do and looking into how to do it. Here’s what I learned from my searching.
Things that I need to be able to do
Import from csv into memory
To create a dataframe from a csv, you can use the following:
|
|
If you have a different delimiter than a comma, you can use the sep
parameter:
|
|
Notice the escape character before the delimiter character.
With no headers, you need to add the following:
|
|
That will give you something like the following:
|
|
Calculate the min for a column
Assuming that you know the column you want to take the min of, you’ll use the column number as an index to the dataframe. For example, just using the index gives you all the column values:
|
|
You can then take the df[i]
format and tag it with the .min()
method to give you the min value:
|
|
Calculate the max for a column
Same as with the .min()
, only we’re switching out for the .max()
method:
|
|
Calculate the average for a column
Second grade fun fact: mean = average. Evidently I lost that knowledge over the years.
Same as min and max:
|
|
Fun side note… use describe()
You can use the describe()
method a dataframe to get a whole bunch of info on all of your numeric columns super quickly. See the following:
|
|
Calculate the 95th percentile of a column
You can calculate percentiles by using the quantile()
method. This takes in some fractional value and returns that percentile. For example, to get the 95th, you’d use .95
:
|
|
Calculate the 99th percentile of a column
Same as the previous, only using .99
:
|
|
Filter by column value
Already explained above, but all you need to do is index on the dataframe with either the column header name or the index number:
|
|
Turn a column into a list
Surprise, there’s another built in method to handle this too. Using the tolist()
method, you can turn a specific column into a list:
|
|
Compare csv lengths (whatever that term is in pandas)
Another method, count()
, is your friend:
|
|
However, this is potentially dangerous as it will only count rows where non NaN values are present. In that case, you can use shape[0]
:
|
|
Still ToDo
- Merge two csv by value in column
- Generate graphs 💚