├── examples ├── nih_2019.gzip ├── zip_geo.gzip └── dataframe_nih_2019.ipynb ├── .gitignore ├── .editorconfig ├── lib ├── find_notebook_directories.sh ├── find_recent_notebooks.sh ├── find_all_notebook_tags.sh ├── remove_cell_outputs.sh ├── find_in_notebook_tags.sh └── find_in_notebook_source.sh ├── README.md ├── LICENSE └── kapitsa /examples/nih_2019.gzip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gitjeff05/kapitsa/HEAD/examples/nih_2019.gzip -------------------------------------------------------------------------------- /examples/zip_geo.gzip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gitjeff05/kapitsa/HEAD/examples/zip_geo.gzip -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | **/.ipynb_checkpoints/* 3 | public/* 4 | .config/ 5 | .ipython/ 6 | .jupyter/ 7 | .local/ 8 | .npm/ 9 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | indent_size = 2 7 | indent_style = space 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /lib/find_notebook_directories.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Search directory recursively and return paths containing 4 | # notebook files (.ipynb) 5 | 6 | find_notebook_directories() { 7 | 8 | # default to the current directory 9 | local CURRENT_DIRECTORY="$PWD" 10 | local SEARCH_DIRECTORY="${1:-$CURRENT_DIRECTORY}" 11 | 12 | # run find if valid directory 13 | if [[ -d "$SEARCH_DIRECTORY" ]]; then 14 | 15 | dir="${SEARCH_DIRECTORY%/}" 16 | # find .ipynb files and ignore checkpoints directory 17 | # return all paths that contain .ipynb files. 18 | 19 | # If the second argument is unset, then 20 | # assume script is called from command line: 21 | # (e.g., find_notebook_directories "path") 22 | if [[ -z "$2" ]]; then 23 | 24 | find "$dir" -name "*.ipynb" \ 25 | \! -path "*ipynb_checkpoints*" | 26 | grep -o "\(.*\)/" | 27 | sort -u 28 | # If second argument was set, we assume 29 | # the parent script will do the sorting. 30 | # This is because it may make multiple calls if 31 | # user has kapitsa configured to search 32 | # multiple directories and sorting should then be done 33 | # all at once in parent script 34 | else 35 | find "$dir" -name "*.ipynb" \ 36 | \! -path "*ipynb_checkpoints*" 37 | fi 38 | 39 | else 40 | echo "Directory ${SEARCH_DIRECTORY} is not valid." >&2 41 | return 1 42 | fi 43 | } 44 | -------------------------------------------------------------------------------- /lib/find_recent_notebooks.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Search directory recursively and return paths containing 4 | # notebook files (.ipynb) 5 | 6 | find_recent_notebooks() { 7 | 8 | # default to the current directory 9 | local CURRENT_DIRECTORY="$PWD" 10 | local SEARCH_DIRECTORY="${1:-$CURRENT_DIRECTORY}" 11 | 12 | declare -a flags 13 | flags=(-f "%Sm %N" -t "%FT%T %a, %d %b %Y %T %z") 14 | 15 | # run find if valid directory 16 | if [[ -d "$SEARCH_DIRECTORY" ]]; then 17 | 18 | # remove trailing slash 19 | dir="${SEARCH_DIRECTORY%/}" 20 | 21 | # Both statements below recursively find .ipynb files 22 | # and ignore checkpoints directory. They are different 23 | # depending on whether the script was called from the 24 | # command line or another script. 25 | 26 | # If the second argument is unset, then 27 | # assume script is called from command line: 28 | # (e.g., find_recent_notebooks "path") 29 | # Note: this is probably not common. 30 | if [[ -z "$2" ]]; then 31 | find "${dir}" -name "*.ipynb" \ 32 | \! -path "*ipynb_checkpoints*" -mtime -60d \ 33 | -print0 | xargs -0 stat "${flags[@]}" | 34 | sort -k1,19 -r | 35 | cut -c 21- 36 | # If second argument was set, we assume 37 | # the parent script will do the sorting. 38 | # This is because it may make multiple calls if 39 | # user has kapitsa configured to search 40 | # multiple directories and sorting should then be done 41 | # all at once in parent script 42 | else 43 | find "${dir}" -name "*.ipynb" \ 44 | \! -path "*ipynb_checkpoints*" -mtime -"${2}" \ 45 | -print0 | xargs -0 stat "${flags[@]}" 46 | fi 47 | 48 | else 49 | echo "Directory ${SEARCH_DIRECTORY} is not valid." >&2 50 | return 1 51 | fi 52 | } 53 | -------------------------------------------------------------------------------- /lib/find_all_notebook_tags.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2020-present Jeff Laiosa 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # ------------------------------------------------- 18 | # find_all_notebook_tags.sh - Find all tags used. 19 | # ------------------------------------------------- 20 | find_all_notebook_tags() { 21 | 22 | local SEARCH_DIRECTORY 23 | 24 | SEARCH_DIRECTORY="${1}" 25 | 26 | local code_cells_with_tags 27 | 28 | # Get a list of all the files to iterate over 29 | local array 30 | array=() 31 | 32 | local tag_collection='[]' 33 | 34 | # Build an array of files to search. 35 | while IFS= read -r -d $'\0'; do 36 | array+=("$REPLY") 37 | done < <(find "$SEARCH_DIRECTORY" -name '*.ipynb' \! -path "*ipynb_checkpoints*" -prune -print0) 38 | 39 | # iterate over array of files 40 | for i in "${array[@]}"; do 41 | 42 | # all cells of cell_type 'code' and that have a tags array. 43 | code_cells_with_tags="$(jq -r '.cells | 44 | map( 45 | select( (.cell_type == "code") and 46 | (.metadata.tags | type == "array") ) 47 | ) | [ .[] | .metadata.tags ] | flatten' <"${i}")" 48 | 49 | # append array to entire tag collection 50 | tag_collection="$(echo "${tag_collection}" | jq -r --argjson foo "$code_cells_with_tags" '. + $foo')" 51 | 52 | done 53 | 54 | # return flattened array. 55 | echo "$tag_collection" 56 | } 57 | -------------------------------------------------------------------------------- /lib/remove_cell_outputs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2020-present Jeff Laiosa 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # ------------------------------------------------- 18 | # remove_cell_outputs.sh - Remove cell output from a file 19 | # This is intended to clear out clutter that makes file 20 | # sizes larger and makes diffing more complex. 21 | # ------------------------------------------------- 22 | 23 | # Define a few colors for output 24 | # https://misc.flogisoft.com/bash/tip_colors_and_formatting#terminals_compatibility 25 | CL_DEF="\033[39m\033[49m" 26 | CL_YEL="\033[33m\033[49m" 27 | CL_RED="\033[31m" 28 | 29 | remove_cell_outputs() { 30 | local FILE 31 | local BASE 32 | local DIR 33 | local TMP_FILE 34 | local output 35 | FILE="${1}" 36 | 37 | BASE=${FILE##*/} #=> "foo.cpp" (basepath) 38 | DIR=${FILE%$BASE} #=> "/path/to/" (dirpath) 39 | TMP_FILE="${DIR}_tmp_${BASE}" 40 | 41 | # Make sure the user passed in a valid file. 42 | if [[ ! -f "$FILE" ]]; then 43 | echo "You must pass a file" 44 | return 1 45 | fi 46 | 47 | # Request confirmation of file overwrite. 48 | # echo -e 49 | # local response 50 | # read -r "response?Continue? [y/N] " 51 | # echo "" 52 | echo -e "This command will attempt to remove the ${CL_YEL}outputs${CL_DEF} and ${CL_YEL}execution_count${CL_DEF} from all notebook cells. ${CL_RED}Make sure you backup your work before proceeding${CL_DEF}." 53 | echo -n "Proceed? [y\N]" 54 | read -r response 55 | 56 | 57 | # If user confirms, continue 58 | if [[ $response =~ ^[Yy]$ ]]; then 59 | # Set output to new .ipynb file with outputs removed from cells 60 | # Next lines explained 61 | # 1. Use identity operator to get entire object. Use addition operator to "merge" object on right into object on left. 62 | # 2. Use pipe to pass output to map function -- which iterates over each cell. 63 | # Also use identity/addition pattern to merge new object into old one. 64 | # 3. If cell type is code, use new object with empty outputs and null execution count 65 | # 4. Use $FILE as input 66 | output="$(jq -r --indent 1 '. + { "cells": .cells 67 | | map(. + 68 | (if .cell_type == "code" then { "outputs": [], "execution_count": null } else {} end) 69 | ) }' "${FILE}")" 70 | # Write output to tmp file 71 | printf "%s" "${output}" > "${TMP_FILE}" 72 | # Copy over original file 73 | # This is why we ask for confirmation! 74 | cp "${TMP_FILE}" "${FILE}" 75 | # Remove tmp file. 76 | rm "${TMP_FILE}" 77 | fi 78 | 79 | } 80 | -------------------------------------------------------------------------------- /lib/find_in_notebook_tags.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2020-present Jeff Laiosa 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # ------------------------------------------------- 18 | # find_in_notebook_tags.sh - Searches directories recursively and returns cell source of 19 | # notebook (.ipynb) files where tags match input 20 | # ------------------------------------------------- 21 | 22 | # Define a few colors for output 23 | # https://misc.flogisoft.com/bash/tip_colors_and_formatting#terminals_compatibility 24 | CL_DEF="\033[39m\033[49m" 25 | CL_YEL="\033[33m\033[49m" 26 | 27 | find_in_notebook_tags() { 28 | 29 | local SEARCH_DIRECTORY 30 | local SEARCH_STRING 31 | 32 | SEARCH_DIRECTORY="${1}" 33 | SEARCH_STRING="${2}" 34 | 35 | local code_cells_with_tags 36 | local num_code_cells_with_tags 37 | local cells_matching_on_search 38 | local num_cells_matching_search 39 | # Get a list of all the files to iterate over 40 | local array 41 | array=() 42 | 43 | # Build an array of files to search. 44 | while IFS= read -r -d $'\0'; do 45 | array+=("$REPLY") 46 | done < <(find "$SEARCH_DIRECTORY" -name '*.ipynb' \! -path "*ipynb_checkpoints*" -prune -print0) 47 | 48 | # iterate over array of files 49 | for i in "${array[@]}"; do 50 | 51 | # all cells of cell_type 'code' and that have a tags array. 52 | code_cells_with_tags="$(jq -r '.cells | 53 | try map( 54 | select( (.cell_type == "code") and 55 | (.metadata.tags | type == "array") ) 56 | ) | [ .[] | { source: .source, tags: .metadata.tags } ]' <"${i}")" 57 | 58 | # number of code cells with tags 59 | num_code_cells_with_tags=$(printf "%s" "$code_cells_with_tags" | jq '. | length') 60 | 61 | # If there was a match, print the results 62 | if [[ "${num_code_cells_with_tags}" -gt 0 ]]; then 63 | 64 | # find the match 65 | cells_matching_on_search=$(printf "%s" "$code_cells_with_tags" | jq -r --arg foo "$SEARCH_STRING" '. | map(select( .tags | join(" ") | test($foo, "imx") )) | [ .[] | { source, tags: .tags | join(" ") } ]') 66 | 67 | # number of cells found that match on search string 68 | num_cells_matching_search="$(printf "%s" "$cells_matching_on_search" | jq '. | length')" 69 | 70 | # If found matching cells, print out results. 71 | if [[ "$num_cells_matching_search" -gt 0 ]]; then 72 | echo "${i}" 73 | echo -e "Found ${CL_YEL}$num_cells_matching_search${CL_DEF} matches on ${CL_YEL}$SEARCH_STRING${CL_DEF}" 74 | printf "%s" "$cells_matching_on_search" | jq '.' 75 | fi 76 | 77 | fi 78 | 79 | done 80 | 81 | } 82 | -------------------------------------------------------------------------------- /lib/find_in_notebook_source.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2020-present Jeff Laiosa 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # ------------------------------------------------- 18 | # find_in_notebook_source.sh - Searches directory recursively and returns 19 | # cells where source matches input. 20 | # ------------------------------------------------- 21 | 22 | # Define a few colors for output 23 | # https://misc.flogisoft.com/bash/tip_colors_and_formatting#terminals_compatibility 24 | CL_DEF="\033[39m\033[49m" 25 | CL_YEL="\033[33m\033[49m" 26 | 27 | find_in_notebook_source() { 28 | local SEARCH_DIRECTORY 29 | local CURRENT_DIRECTORY 30 | 31 | # default to the current directory 32 | CURRENT_DIRECTORY="$PWD" 33 | SEARCH_DIRECTORY="${1:-$CURRENT_DIRECTORY}" 34 | 35 | SEARCH_STRING="$2" 36 | 37 | # if function is called directly, ensure the search string is supplied 38 | if [[ -z "$SEARCH_STRING" ]]; then 39 | echo "You must supply a path as the first argument and a string to search as the second. For example:" 40 | echo "find_in_notebook_source . \"DataFrame\"" 41 | echo "find_in_notebook_source . \"(pandas|numpy)\"" 42 | echo "find_in_notebook_source . \"(?=.*read_csv)(?=.*parse_dates)\"" 43 | return 1 44 | fi 45 | 46 | # Check if valid directory 47 | if [[ -d "$SEARCH_DIRECTORY" ]]; then 48 | 49 | # find .ipynb files and ignore checkpoints directory 50 | # return all paths that contain .ipynb files. 51 | 52 | local cells_matching_on_search 53 | local num_cells_matching_search 54 | 55 | # Get a list of all the files to iterate over 56 | local array 57 | array=() 58 | 59 | # Build an array of files to search. 60 | while IFS= read -r -d $'\0'; do 61 | array+=("$REPLY") 62 | done < <(find "$SEARCH_DIRECTORY" -name '*.ipynb' \! -path "*ipynb_checkpoints*" -prune -print0) 63 | 64 | # iterate over array of files 65 | for i in "${array[@]}"; do 66 | 67 | # find files matching on search string 68 | cells_matching_on_search="$(jq -r --arg foo "$SEARCH_STRING" '.cells 69 | | map( 70 | select( (.cell_type == "code" ) and 71 | ( .source | join(" ") | test($foo, "imx") ) ) 72 | ) | [ .[] | { source: .source } ]' <"$i")" 73 | 74 | # number of cells matching 75 | num_cells_matching_search="$(printf "%s" "$cells_matching_on_search" | jq '. | length')" 76 | 77 | # if found cells, print them out along with filename. 78 | if [[ "$num_cells_matching_search" -gt 0 ]]; then 79 | echo -e "Found ${CL_YEL}$num_cells_matching_search${CL_DEF} matching cells in ${CL_YEL}$i${CL_DEF}" 80 | printf "%s" "$cells_matching_on_search" | jq . 81 | fi 82 | 83 | done 84 | 85 | else 86 | echo "Directory ${SEARCH_DIRECTORY} is not valid." >&2 87 | return 1 88 | fi 89 | } 90 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # KAPITSA (v0.1.9) 2 | 3 | Kapitsa logo 4 | 5 | ## Search your Jupyter notebooks. 6 | 7 | ## Motivation 8 | 9 | As the number of projects grow, it becomes difficult to keep notebooks organized and searchable on your local machine. 10 | 11 | [See blog post for for how this project got started and the tools behind it.](https://www.optowealth.com/blog/better-way-to-search-your-notebooks). 12 | 13 | ## Solution 14 | 15 | Kapitsa is a simple, minimally configured command line program that provides a centralized way to search and keep track of your notebooks. Users simply configure paths where they keep their notebooks. Kapitsa provides convenience methods do do the following: 16 | 17 | 1. **Search Code** - Query your notebooks' source. 18 | 2. **Search Tags** - Query your notebooks' cell tags. 19 | 3. **List Recent** - List notebooks you have worked on recently. 20 | 4. **List Directories** - View all directories on your system that contain notebooks. 21 | 22 | ## Benefits & Use Cases 23 | 24 | Providing the ability to search *your* notebooks and any notebooks on your machine makes finding code examples easier. Search all notebooks on your local machine -- that means notebooks you pulled from Github, too. 25 | 26 | ### Use Cases: 27 | 28 | 1. Have you ever solved some complex problem and thought bookmarking the solution for later would be beneficial? With Kapitsa, you just tag the cell with a relevant `"keyword"` and find it later with `kapitsa tags "keyword"`. 29 | 30 | 2. Having trouble remembering how to use some API in [_insert library here_]? Just run `kapitsa search "function"` to search your notebooks for all cells containing `function` in their source. 31 | 32 | 3. Where was that notebook you worked on 2 weeks ago? Running `kapitsa recent` will jog your memory. 33 | 34 | # API 35 | 36 | | Command | Description | 37 | | ------------------------------ | -------------------------------------------------------------------------| 38 | | kapitsa search regex [-p path] | Search notebook source. | 39 | | kapitsa tags regex [-v] | Search notebook cell tags. | 40 | | kapitsa list [path] | List all paths containing .ipynb files. | 41 | | kapitsa recent [num_days] | List recently modified notebooks (default last 60 days) | 42 | | kapitsa list-tags [path] | List all defined tags. | 43 | | kapitsa clear notebook | Remove cell outputs and execution_count from code cells in notebook | 44 | | kapitsa [help\|h] | Print help info. | 45 | 46 | 47 | # Quick Examples 48 | 49 | | Command | Description | 50 | | -------------------------------------- | -------------------------------------------------------------------------| 51 | | kapitsa list . | Lists all paths in current directory containing .ipynb files | 52 | | kapitsa search "join" | Print cells matching "join" | 53 | | kapitsa search "(join\|concat)" | Print cells matching on "join" or "concat" | 54 | | kapitsa tags "(pandas\|where)" | Print cells with tags "pandas" or "where" | 55 | | kapitsa tags "(?=.*where)(?=.*loc)" | Print cells with tags "where" and "loc" | 56 | 57 | # Verbose Examples 58 | 59 | ## Find notebook cells matching "*join*". 60 | 61 | ```bash session 62 | > kapitsa search "join" 63 | ``` 64 | 65 | ```jsonc 66 | Found 2 matching cells in /Users/Me/File.ipynb 67 | [ 68 | { 69 | "source": [ 70 | "df = df.join(zip_codes.loc[:, ['Zip', 'Latitude', 'Longitude']].set_index('Zip'), on='ZIPCODE')" 71 | ] 72 | }, 73 | { 74 | "source": [ 75 | "# join two dataframes on the original dataframes' column. Index must be set appropriately on second df.\n", 76 | "us = us.join(zips_to_coords.loc[:, ['Zip', 'Lat', 'Long']].set_index('Zip'), on='ZIPCODE')" 77 | ] 78 | } 79 | ] 80 | ... 81 | ``` 82 | 83 | ## Find cells matching "series" **OR** "dataframe". 84 | 85 | ```bash session 86 | > kapitsa search "series|dataframe" 87 | ``` 88 | 89 | ## Find cells matching "pandas" **AND** "numpy". 90 | 91 | ```bash session 92 | > kapitsa search "(?=.*pandas)(?=.*regex)" 93 | ``` 94 | 95 | *Note: The above command does seem ridiculously complex for an `and` statement. Perhaps there is a better way. For now, I wanted the users to have complete control over the argument passed to `jq` to do the search.* 96 | 97 | ## Have a quick glance to see what notebooks you have worked on recently: 98 | 99 | ```bash session 100 | > kapitsa recent 101 | ``` 102 | 103 | ```bash 104 | Thu, 05 Mar 2020 17:05:29 -0500 /Users/Me/Github/States/train/Population.ipynb 105 | Wed, 04 Mar 2020 11:42:24 -0500 /Users/Me/Github/Class/examples/Intro-To-Pandas.ipynb 106 | Mon, 24 Feb 2020 22:58:51 -0500 /Users/Me/Projects/BigTime/train/Marketing-Plan.ipynb 107 | ``` 108 | ## Print out a list of all paths containing notebook files: 109 | 110 | ```bash session 111 | > kapitsa list 112 | ``` 113 | 114 | ```bash 115 | /Users/Me/Github/kapitsa/examples/ 116 | /Users/Me/Projects/Classifiers/train/awards-grants/ 117 | /Users/Me/Projects/Classifiers/train/noaa/ 118 | /Users/Me/Tutorials/DeepLearning/Fish 119 | ``` 120 | 121 | 122 | # Setup and install 123 | 124 | ## Dependencies 125 | 126 | Users must have [jq >= jq-1.6](https://stedolan.github.io/jq/) installed because you need something to parse notebook documents (.ipynb) which are json. 127 | 128 | ## Clone the repo. 129 | 130 | ```bash session 131 | > git clone https://github.com/gitjeff05/kapitsa 132 | > cd kapitsa && chmod u+rx kapitsa # Make `kapitsa` executable by the user. 133 | ``` 134 | 135 | ## Create `.kapitsa` configuration file. 136 | 137 | ```bash session 138 | > echo '{"path":"$HOME/Github/kapitsa"}' > ~/.kapitsa # separate paths by ":" 139 | ``` 140 | 141 | ## Create an environment variable, `KAPITSA` that points to your config file. 142 | 143 | ```bash session 144 | > export KAPITSA=$HOME/.kapitsa # add to your .bash_profile 145 | ``` 146 | ## Source kapitsa 147 | 148 | ```bash session 149 | > . ./kapitsa # add to your .bash_profile 150 | ``` 151 | # Test that everything is working: 152 | 153 | ```bash session 154 | > kapitsa list 155 | ``` 156 | If you get a list of paths then you are good to go. Add more paths (separated by ':') to the path key in `.kapitsa` config file. 157 | 158 | # Get Help 159 | 160 | ```bash session 161 | > kapitsa help 162 | ``` 163 | 164 | Open a ticket for bug reports or feature requests. 165 | 166 | 167 | # Testing and compatibility: 168 | 169 | Kapitsa has been tested on the following platforms. 170 | 171 | - [x] GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin19) 172 | - [x] zsh 5.7.1 (x86_64-apple-darwin18.2.0) 173 | - [x] GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu) 174 | 175 | If Kapitsa is not working for you, please open a pull request with as much information as possible so we can try to get it working. 176 | 177 | # Advanced queries 178 | 179 | Under the hood Kapitsa uses [jq regular expressions (PCRE)](https://stedolan.github.io/jq/manual/#RegularexpressionsPCRE) through the `test` method. Anything you can pass to jq's `test` method should also be valid for Kapitsa. Please open a ticket if you find any functionality missing. 180 | 181 | # File Hierarchy 182 | 183 | ```bash session 184 | > tree -L 2 185 | . 186 | ├── LICENSE 187 | ├── README.md 188 | ├── examples 189 | │   ├── dataframe_nih_2019.ipynb 190 | │   ├── nih_2019.gzip 191 | │   └── zip_geo.gzip 192 | ├── kapitsa 193 | └── lib 194 | ├── find_in_notebook_source.sh 195 | ├── find_in_notebook_tags.sh 196 | ├── find_notebook_directories.sh 197 | └── find_recent_notebooks.sh 198 | 199 | 2 directories, 10 files 200 | ``` 201 | Note that any of the files in `lib` are meant to be run on their own or through kapitsa. 202 | 203 | # Notes on implementation 204 | 205 | This program is meant to be minimal and portable. Most of the functionality is through `find` and `jq`. I have not included comprehensive install scripts that would do a lot of the setup for you (e.g., editing `.bash_profile` or adding files to your `$HOME` directory). Users should be at least somewhat familiar with the command line (i.e., knowledge of `.bash_profile` (or similar), `alias` and `chmod`). Anyone can read the contents of `kapitsa` and know that it simply reads some files and produces an output. Please [open an issue](https://github.com/gitjeff05/kapitsa/issues) to file a bug or request a feature. 206 | 207 | # Security 208 | 209 | I have done my best to ensure that this code can do no harm. The primary use of this script is to read files and output the results. It does not write to directories or publish anything it finds. It does not track your usage. It makes no network requests at all. I encourage you to check the source code and [open an issue](https://github.com/gitjeff05/kapitsa/issues) to alert the author of any security vulnerabilities. 210 | 211 | # Future Ideas 212 | 213 | - A default set of examples for some languages/frameworks (e.g., python, pandas, numpy, scikit) 214 | - Caching cell metadata to make searches faster 215 | - Fetching metadata and source from remote locations. Users could essentially "subscribe" to other authors' preferred examples the same way bash users borrow shell configurations (.dotfiles) from authors. 216 | - A JupyterLab extension to facilitate the search right inside of JupyterLab. 217 | - Ability to build cheat sheets based on tags. 218 | 219 | # License 220 | 221 | Licensed under the Apache License, Version 2.0 222 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /kapitsa: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2020-present Jeff Laiosa 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # ------------------------------------------------- 18 | # kapitsa - This is the main program and 19 | # provides search and query capabilities 20 | # to the local environment defined by: 21 | # 1. KAPITSA environment variable 22 | # 2. .kapitsa config file 23 | # ------------------------------------------------- 24 | 25 | # Define a few colors for output 26 | # https://misc.flogisoft.com/bash/tip_colors_and_formatting#terminals_compatibility 27 | CL_DEF="\033[39m\033[49m" 28 | CL_RED="\033[31m" 29 | CL_CYA="\033[36m\033[49m" 30 | CL_YEL="\033[33m\033[49m" 31 | 32 | ####################################### 33 | # kapitsa config info 34 | ####################################### 35 | print_config_info() { 36 | echo -e "Kapitsa uses a json configuration file to know where to search for .ipynb files.\nThe value of \"path\" in the ${CL_CYA}.kapitsa${CL_DEF} config file must point to a valid path." 37 | echo "Multiple paths are allowed but must be separated by a colon (:)" 38 | echo -e "Only absolute paths or paths using the ${CL_CYA}\$HOME${CL_DEF} environment variable are valid.\n" 39 | echo -e "For example \"${CL_CYA}\$HOME/path/to/dir:/Users/everyone/notebooks${CL_DEF}\" is valid" 40 | echo -e "while \"${CL_CYA}\$NOTEBOOKS/dir:/Users/everyone/notebooks${CL_DEF}\" is not because \$NOTEBOOKS is not allowed.\n" 41 | echo "{\"path\":\"\$HOME/projects:\$HOME/github\"}" | jq . 42 | } 43 | 44 | ####################################### 45 | # kapitsa env var check 46 | ####################################### 47 | check_kapitsa_env_variable() { 48 | if [ -z "$KAPITSA" ]; then 49 | echo -e "${CL_RED}Error:${CL_DEF} 'KAPITSA' env variable not set. Set ${CL_CYA}KAPITSA${CL_DEF} to the path of your ${CL_CYA}.kapitsa${CL_DEF} config file." 50 | printf 'Either run the following or manually add it to %s/.bash_profile (or similar)\n\n' "$HOME" 51 | echo -e "${CL_CYA}export${CL_DEF} KAPITSA=\"\$HOME/.kapitsa\"\n" 52 | print_config_info 53 | return 1 54 | else 55 | return 0 56 | fi 57 | } 58 | 59 | ####################################### 60 | # kapitsa config check 61 | # Ensure KAPTISA env var points to a file and 62 | # that the file has a "path" key with a string value. 63 | ####################################### 64 | check_kapitsa_config() { 65 | # Make sure $KAPITSA is pointing to a file. 66 | if [ ! -f "$KAPITSA" ]; then 67 | echo -e "${CL_RED}Error${CL_DEF}: Could not find ${CL_CYA}.kapitsa${CL_DEF} configuration file at ${CL_CYA}$KAPITSA${CL_DEF}.\n" 68 | print_config_info 69 | return 1 70 | fi 71 | # Make sure the json file has a path key and that it is a string 72 | if [ ! "$(jq '. | select(.path|type=="string")' <"$KAPITSA")" ]; then 73 | echo -e "${CL_RED}Error${CL_DEF}: Invalid or missing required key \"path\" in json file.\n" 74 | print_config_info 75 | return 1 76 | fi 77 | } 78 | 79 | ####################################### 80 | # kapitsa help info - 81 | ####################################### 82 | kapitsa_help() { 83 | echo -e "\nKapitsa Help:\n" 84 | echo -e "${CL_CYA}kapitsa ${CL_RED}search regex [-p path]${CL_DEF} Search cell source." 85 | echo -e "${CL_CYA}kapitsa ${CL_RED}tags regex [-v]${CL_DEF} Search cell tags [-verbose mode]." 86 | echo -e "${CL_CYA}kapitsa ${CL_RED}list [path]${CL_DEF} List all paths containing .ipynb files." 87 | echo -e "${CL_CYA}kapitsa ${CL_RED}recent [days]${CL_DEF} List recently modified notebooks in the past num_days (default is 60)." 88 | echo -e "${CL_CYA}kapitsa ${CL_RED}list-tags [path]${CL_DEF} List all defined tags." 89 | echo -e "${CL_CYA}kapitsa ${CL_RED}clear notebook_path${CL_DEF} Remove cell outputs and execution_count from code cells.\n" 90 | echo -e "By default Kapitsa searches all paths defined in ${CL_CYA}.kapitsa${CL_DEF} config file.\n" 91 | echo -e "Examples\n" 92 | echo -e "${CL_CYA}kapitsa ${CL_RED}list .${CL_DEF} Lists all paths in current directory containing .ipynb files" 93 | echo -e "${CL_CYA}kapitsa ${CL_RED}search \"join\" ${CL_DEF} Print cells matching \"join\"" 94 | echo -e "${CL_CYA}kapitsa ${CL_RED}search \"(join|concat)\" ${CL_DEF} Print cells matching on \"join\" or \"concat\"" 95 | echo -e "${CL_CYA}kapitsa ${CL_RED}tags \"(pandas|where)\" ${CL_DEF} Print cells with tags \"pandas\" or \"where\"" 96 | echo -e "${CL_CYA}kapitsa ${CL_RED}tags \"(?=.*where)(?=.*loc)\"${CL_DEF} Print cells with tags \"where\" and \"loc\"\n" 97 | } 98 | 99 | ####################################### 100 | # kapitsa settings - 101 | # Ensure KAPTISA env variable is set and points to a config file. 102 | ####################################### 103 | check_settings() { 104 | local path_list 105 | check_kapitsa_env_variable && check_kapitsa_config 106 | # Get a list of paths on separate lines 107 | path_list=$(jq '.path' <"$KAPITSA" | tr -d '[][:space:]"' | tr ':' '\n') 108 | # If path contains $HOME, ensure that it is defined 109 | if [[ $path_list =~ "\$HOME" ]]; then 110 | if [ -z "${HOME}" ]; then 111 | printf "You specified \$HOME in your \"path\" but your \$HOME environment variable is not set.\n\n" 112 | printf "\"path\": \"%s\"\n\n" "$(jq '.path' <"$KAPITSA" | tr -d '[][:space:]"')" 113 | print_config_info 114 | return 1 115 | fi 116 | fi 117 | } 118 | 119 | ####################################### 120 | # kapitsa paths - get the paths defined 121 | # in the configuration file. 122 | ####################################### 123 | get_kapitsa_paths() { 124 | # Get a list of paths on separate lines 125 | path_list=$(jq '.path' <"$KAPITSA" | tr -d '[][:space:]"' | tr ':' '\n') 126 | # replace string $HOME with expanded shell variable $HOME 127 | paths="${path_list//\$HOME/$HOME}" 128 | echo "$paths" 129 | } 130 | 131 | ####################################### 132 | # kapitsa search - searches all of the paths 133 | # in the config paths. If optional path is provided, 134 | # limit search to that path. 135 | # Arguments: 136 | # search_string [-p path] 137 | ####################################### 138 | kapitsa_search() { 139 | 140 | local search_string 141 | local path_list 142 | local paths 143 | 144 | # (todo jeff) zsh & bash arguments ordering 145 | # search string that was passed in 146 | search_string="$1" 147 | 148 | # Get a list of paths on separate lines 149 | path_list=$(jq '.path' <"$KAPITSA" | tr -d '[][:space:]"' | tr ':' '\n') 150 | 151 | # replace string $HOME with expanded shell variable $HOME 152 | paths="${path_list//\$HOME/$HOME}" 153 | 154 | # Run the search on each directory specified 155 | while IFS= read -r directory; do 156 | 157 | # break out if directory is not valid 158 | if [ ! -d "$directory" ]; then 159 | echo -e "${CL_YEL}Warning${CL_DEF}: $directory not a valid directory. Make sure your ${CL_CYA}.kapitsa${CL_DEF} config file contains a valid directory." 160 | break 161 | fi 162 | 163 | find_in_notebook_source "${directory}" "${search_string}" 164 | 165 | done <<< "$paths" 166 | 167 | } 168 | 169 | ####################################### 170 | # kapitsa search tags - searches all of the paths 171 | # in the config paths for tags matching input 172 | ####################################### 173 | kapitsa_search_tags() { 174 | 175 | local search_string 176 | local path_list 177 | local paths 178 | 179 | search_string="$1" 180 | verbose="$2" 181 | 182 | # Run the search on each directory specified 183 | while IFS= read -r directory; do 184 | if [[ "$verbose" == "verbose" ]]; then 185 | echo "Searching $directory" 186 | fi 187 | # break out if directory is not valid 188 | if [ ! -d "$directory" ]; then 189 | echo -e "${CL_YEL}Warning${CL_DEF}: $directory not a valid directory. Make sure your ${CL_CYA}.kapitsa${CL_DEF} config file contains a valid directory." 190 | break 191 | fi 192 | 193 | find_in_notebook_tags "${directory}" "${search_string}" 194 | 195 | done < <(get_kapitsa_paths) 196 | 197 | } 198 | 199 | ####################################### 200 | # kapitsa list all tags - searches all of the paths 201 | # in the config paths and lists all tags 202 | ####################################### 203 | kapitsa_list_all_tags() { 204 | 205 | local tags 206 | local tags_in_dir 207 | tags='[]' 208 | local local_dir="$1" 209 | 210 | if [[ -n "$local_dir" ]]; then 211 | 212 | # break out if directory is not valid 213 | if [ ! -d "$local_dir" ]; then 214 | echo -e "${CL_YEL}Warning${CL_DEF}: $local_dir not a valid directory." 215 | return 216 | fi 217 | 218 | tags_in_dir="$(find_all_notebook_tags "${local_dir}")" 219 | 220 | # Get array as space separated output 221 | local space_sep_out 222 | space_sep_out=$(echo "${tags_in_dir}" | jq -r '. | flatten | unique | @sh') 223 | 224 | # Build an array 225 | local lines 226 | IFS=' ' read -r -A lines <<<"$space_sep_out" 227 | 228 | if [[ "${#lines[@]}" -gt 0 ]]; then 229 | echo -e "Found ${CL_YEL}${#lines[@]}${CL_DEF} tags in ${CL_YEL}${local_dir}${CL_DEF}" 230 | else 231 | echo -e "${CL_YEL}No tags found.${CL_DEF}" 232 | return 233 | fi 234 | 235 | printf '%s\n' "${lines[@]}" 236 | return 237 | fi 238 | 239 | # Run the search on each directory specified 240 | while IFS= read -r directory; do 241 | 242 | # break out if directory is not valid 243 | if [ ! -d "$directory" ]; then 244 | echo -e "${CL_YEL}Warning${CL_DEF}: $directory not a valid directory. Make sure your ${CL_CYA}.kapitsa${CL_DEF} config file contains a valid directory." 245 | break 246 | fi 247 | 248 | tags_in_dir="$(find_all_notebook_tags "${directory}")" 249 | tags="$(echo "${tags}" | jq -r --argjson foo "$tags_in_dir" '. + $foo')" 250 | 251 | done < <(get_kapitsa_paths) 252 | 253 | # Get array as space separated output 254 | local space_sep_out 255 | space_sep_out=$(echo "${tags}" | jq -r '. | flatten | unique | @sh') 256 | 257 | # Build an array 258 | local lines 259 | IFS=' ' read -r -A lines <<<"$space_sep_out" 260 | 261 | if [[ "${#lines[@]}" -gt 0 ]]; then 262 | echo -e "Found ${CL_YEL}${#lines[@]}${CL_DEF} tags across all directories" 263 | else 264 | echo -e "${CL_YEL}No tags found.${CL_DEF}" 265 | return 266 | fi 267 | 268 | printf '%s\n' "${lines[@]}" 269 | } 270 | 271 | ####################################### 272 | # kapitsa is the entry point 273 | # Arguments: 274 | # [help|list|recent|search|tags|list-tags|clear] 275 | ####################################### 276 | kapitsa() { 277 | # The command passed to kapitsa [list|search|help] 278 | local option 279 | 280 | # check settings to make sure env variable is set 281 | # and config file is set 282 | check_settings 283 | 284 | # set option to 1st argument 285 | option="$1" 286 | 287 | # if [help|h|-h|-help] print help info 288 | if [[ "$option" == "help" ]] || [[ "$option" == "h" ]] || [[ "$option" == "-h" ]] || [[ "$option" == "-help" ]]; then 289 | 290 | kapitsa_help 291 | 292 | # list notebooks 293 | elif [[ "$option" == "list" ]] || [[ "$option" == "l" ]]; then 294 | # list all paths containing notebooks 295 | local kapitsa_paths 296 | local all_dirs 297 | local all 298 | local nbs 299 | kapitsa_paths=$(get_kapitsa_paths) 300 | 301 | if [[ -z "$2" ]]; then 302 | # Run the search on each directory specified 303 | echo -e "Searching default paths: \n${kapitsa_paths}\n" 304 | all_dirs=() 305 | while IFS= read -r directory; do 306 | nbs=$(find_notebook_directories "${directory}" 1) 307 | while IFS=$'\n' read -r line; do all_dirs+=("$line"); done <<<"$nbs" 308 | done <<<"$kapitsa_paths" 309 | 310 | all=$( 311 | IFS=$'\n' 312 | echo "${all_dirs[*]}" 313 | ) 314 | all_directories=() 315 | while IFS=$'\n' read -r line; do all_directories+=("$line"); done < <(echo "$all" | 316 | grep -o "\(.*\)/" | 317 | sort -u) 318 | echo "$( 319 | IFS=$'\n' 320 | echo "${all_directories[*]}" 321 | )" 322 | echo -e "\nFound ${#all_directories[@]} directories containing notebooks." 323 | else 324 | # call ./lib/find_notebook_directories to get a list of directories 325 | # containing .ipynb files 326 | local notebooks 327 | local array 328 | local count 329 | echo -e "Searching path ${2}\n" 330 | notebooks=$(find_notebook_directories "$2") 331 | 332 | # build an array from the results 333 | array=() 334 | while IFS=$'\n' read -r line; do array+=("$line"); done <<<"$notebooks" 335 | 336 | # count members of array 337 | count="${#array[@]}" 338 | 339 | # This is for bash/zsh interop. 340 | # For some reason 0th element is always unset in both bash/zsh 341 | # 1st element is set if array has > 0 members 342 | # However, passing current path "." results in the 0th member being set 343 | # (todo jeff): more testing around this 344 | if [[ -z "${array[1]}" ]] && [[ -z "${array[0]}" ]]; then 345 | count=0 346 | fi 347 | 348 | echo "$notebooks" 349 | echo -e "\nFound ${count} directories containing notebooks." 350 | fi 351 | 352 | elif [[ "$option" == "recent" ]] || [[ "$option" == "r" ]]; then 353 | # list recently modified files 354 | local kapitsa_paths 355 | local all_files 356 | local all 357 | local nbs 358 | # default to 60 days or override with 2nd arg 359 | local DEFAULT_DAYS=60 360 | local number_days="${2:-$DEFAULT_DAYS}" 361 | 362 | kapitsa_paths=$(get_kapitsa_paths) 363 | 364 | # Run the search on each directory specified 365 | all_files=() 366 | while IFS= read -r directory; do 367 | nbs=$(find_recent_notebooks "${directory}" "${number_days}") 368 | while IFS=$'\n' read -r line; do all_files+=("$line"); done <<<"$nbs" 369 | done <<<"$kapitsa_paths" 370 | 371 | # sort and format list 372 | all=$( 373 | IFS=$'\n' 374 | echo "${all_files[*]}" 375 | ) 376 | echo "$all" | 377 | sort -k1,19 -r | 378 | cut -c 21- 379 | 380 | # search notebooks 381 | elif [[ "$option" == "search" ]] || [[ "$option" == "s" ]]; then 382 | 383 | local args 384 | local search_arguments 385 | 386 | args=("$@") 387 | search_arguments=("${args[@]:1}") 388 | 389 | if [[ "${#search_arguments[@]}" -eq 1 ]]; then 390 | 391 | # Only the search regex was passed. Do default search across config paths 392 | kapitsa_search "${2}" 393 | 394 | elif [[ "${#search_arguments[@]}" -eq 3 ]]; then 395 | 396 | # Three arguments supplied. User is trying to supply a path to search 397 | 398 | # Check to make sure 2nd arg was the '-p' flag 399 | if [[ "${3}" != "-p" ]]; then 400 | echo -e "Incorrect argument order. Optional third argument must be -p followed by a valid path.\n" 401 | kapitsa_help 402 | return 1 403 | fi 404 | 405 | # Pass arguments to find_in_notebook_source 406 | find_in_notebook_source "${4}" "${2}" 407 | 408 | else 409 | 410 | echo -e "Incorrect number of arguments\n" 411 | kapitsa_help 412 | return 1 413 | 414 | fi 415 | 416 | elif [[ "$option" == "tags" ]] || [[ "$option" == "t" ]]; then 417 | 418 | if [[ "$3" == "-v" ]]; then 419 | kapitsa_search_tags "${2}" "verbose" 420 | else 421 | kapitsa_search_tags "${2}" 422 | fi 423 | 424 | elif [[ "$option" == "list-tags" ]] || [[ "$option" == "lt" ]]; then 425 | 426 | kapitsa_list_all_tags "${2}" 427 | 428 | elif [[ "$option" == "clear" ]]; then 429 | 430 | remove_cell_outputs "${2}" 431 | 432 | else 433 | echo -e "Incorrect arguments\n" 434 | kapitsa_help 435 | return 1 436 | fi 437 | 438 | } 439 | 440 | # Main is run when we source ./kapitsa. 441 | # It then sources the other functions in lib 442 | main() { 443 | # check settings to make sure env variable is set 444 | # and config file is set 445 | check_settings 446 | 447 | # Get the current directory of the script. 448 | # https://stackoverflow.com/questions/59895/how-can-i-get-the-source-directory-of-a-bash-script-from-within-the-script-itsel/56264110#56264110 449 | [ -n "$ZSH_VERSION" ] && curr_dir=$(dirname "${(%):-%x}") || curr_dir=$(dirname "${BASH_SOURCE[0]:-$0}") 450 | 451 | # create array of libraries to source 452 | local libraries 453 | libraries=('find_notebook_directories' 'find_in_notebook_source' 'find_recent_notebooks' 'find_in_notebook_tags' 'remove_cell_outputs' 'find_all_notebook_tags') 454 | 455 | # source libraries 456 | for i in "${libraries[@]}"; do 457 | shell_script="${curr_dir}/lib/$i.sh" 458 | if [[ -r "$shell_script" ]] && [[ -f "$shell_script" ]]; then 459 | # shellcheck source=lib/find_notebooks.sh 460 | # shellcheck disable=SC1091 461 | . "$shell_script" 462 | fi 463 | done 464 | } 465 | 466 | main "$@" 467 | -------------------------------------------------------------------------------- /examples/dataframe_nih_2019.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Overview\n", 8 | "\n", 9 | "This notebook goes through the pandas API using some practical examples. It is by no means exhaustive.\n", 10 | "\n", 11 | "# Motivation\n", 12 | "\n", 13 | "Searching old code and online documentation for how previous problems were solved is time consuming. Keeping a living document and tagging cells with keywords can help bring about solutions faster." 14 | ] 15 | }, 16 | { 17 | "cell_type": "code", 18 | "execution_count": null, 19 | "metadata": {}, 20 | "outputs": [], 21 | "source": [ 22 | "%matplotlib inline\n", 23 | "import pandas as pd\n", 24 | "import numpy as np\n", 25 | "import matplotlib\n", 26 | "\n", 27 | "import locale\n", 28 | "locale.setlocale(locale.LC_ALL, 'en_US.UTF8')" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": {}, 34 | "source": [ 35 | "# [Raise on chained assignment](https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#indexing-view-versus-copy)" 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": null, 41 | "metadata": { 42 | "tags": [ 43 | "raise", 44 | "chained", 45 | "mutate" 46 | ] 47 | }, 48 | "outputs": [], 49 | "source": [ 50 | "# notebooks should begin with this so we do not accidentally mutate the original dataframe\n", 51 | "pd.set_option('mode.chained_assignment','raise')" 52 | ] 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "metadata": {}, 57 | "source": [ 58 | "# First, lets read in the data with `read_csv`:\n", 59 | "\n", 60 | "NIH data for 2019 was imported from [exporter.nih.gov](https://exporter.nih.gov/ExPORTER_Catalog.aspx?sid=5&index=0). An [explanation of the fields](https://exporter.nih.gov/about.aspx) is helpful for analysis. We took a random sample of 15k rows so this demo could be lightweight.\n", 61 | "\n", 62 | "- Explicitly pass `header=0` to be able to replace existing column names.\n", 63 | "- pass `dtype={ 'ORG_ZIPCODE': 'str'}` to prevent this column from being inferred as an int" 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": null, 69 | "metadata": { 70 | "tags": [ 71 | "read_csv", 72 | "csv", 73 | "dates", 74 | "import", 75 | "dataframe", 76 | "pandas" 77 | ] 78 | }, 79 | "outputs": [], 80 | "source": [ 81 | "column_names=[\"ID\",\"ACTIVITY\",\"IC\",\"ORG_CITY\",\"ORG_COUNTRY\",\"ORG_DEPT\",\"ORG_NAME\",\"ORG_STATE\",\"ORG_ZIPCODE\",\"PROJECT_START\",\"PROJECT_END\",\"PROJECT_TITLE\",\"DIRECT_COST_AMT\",\"TOTAL_COST\"]\n", 82 | "df = pd.read_csv('./nih_2019.gzip', header=0, names=column_names, parse_dates=[\"PROJECT_START\",\"PROJECT_END\"], compression='gzip', dtype={ 'ORG_ZIPCODE': 'str'}, encoding=\"ISO-8859-1\")" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": null, 88 | "metadata": {}, 89 | "outputs": [], 90 | "source": [ 91 | "df.head()" 92 | ] 93 | }, 94 | { 95 | "cell_type": "markdown", 96 | "metadata": {}, 97 | "source": [ 98 | "# Lets say we only want to examine US awards.\n", 99 | "\n", 100 | "Always use **`copy()`** whenever you assign a **variable to a slice** of your dataframe **when that slice could be used for anything other than just reading**. This way we will avoid any embarrassing [warnings/exceptions regarding setting view on copy](https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy). " 101 | ] 102 | }, 103 | { 104 | "cell_type": "code", 105 | "execution_count": null, 106 | "metadata": { 107 | "tags": [ 108 | "copy", 109 | "loc", 110 | "pandas", 111 | "boolean" 112 | ] 113 | }, 114 | "outputs": [], 115 | "source": [ 116 | "# Always use `copy()` whenever you assign a variable to a slice of your dataframe when that slice could be used for anything other than just reading.\n", 117 | "us = df.loc[df['ORG_COUNTRY'] == 'UNITED STATES'].copy()" 118 | ] 119 | }, 120 | { 121 | "cell_type": "markdown", 122 | "metadata": {}, 123 | "source": [ 124 | "# Now those zip codes are going to be used later to lookup latitude/longitude. Make sure they contain only digits" 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": null, 130 | "metadata": { 131 | "tags": [ 132 | "pandas", 133 | "str", 134 | "contains", 135 | "regex" 136 | ] 137 | }, 138 | "outputs": [], 139 | "source": [ 140 | "# Find rows that contain any non-digit in column\n", 141 | "not_okay_zips = us.loc[us['ORG_ZIPCODE'].str.contains('\\D', regex=True), ['ID', 'ORG_CITY', 'ORG_NAME', 'ORG_STATE', 'ORG_ZIPCODE', 'TOTAL_COST']]" 142 | ] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "execution_count": null, 147 | "metadata": { 148 | "tags": [ 149 | "items", 150 | "iteration", 151 | "series" 152 | ] 153 | }, 154 | "outputs": [], 155 | "source": [ 156 | "def highlight_columns(val, match_strings_list):\n", 157 | " v = 'background-color: %s; font-weight: %s;' % ('#ff677d', 'bold')\n", 158 | " t = 'font-weight: normal'\n", 159 | " if (val.name in match_strings_list):\n", 160 | " return [v for i in val.items()]\n", 161 | " else:\n", 162 | " return [t for i in val.items()]" 163 | ] 164 | }, 165 | { 166 | "cell_type": "markdown", 167 | "metadata": {}, 168 | "source": [ 169 | "# Sometimes highlighting a column is helpful" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": null, 175 | "metadata": { 176 | "tags": [ 177 | "style", 178 | "apply", 179 | "pandas" 180 | ] 181 | }, 182 | "outputs": [], 183 | "source": [ 184 | "# highlight a column by using style.apply and passing a function\n", 185 | "not_okay_zips.head().style.apply(highlight_columns, match_strings_list=['ORG_ZIPCODE'])" 186 | ] 187 | }, 188 | { 189 | "cell_type": "markdown", 190 | "metadata": {}, 191 | "source": [ 192 | "# Oh no, `20,707,359,` does not look like a valid zip code.\n", 193 | "\n", 194 | "## Since we just have one baddie, lets correct it using `.loc` -- passing a boolean array and a single column label, `ORG_ZIPCODE`." 195 | ] 196 | }, 197 | { 198 | "cell_type": "code", 199 | "execution_count": null, 200 | "metadata": { 201 | "tags": [ 202 | "dataframe", 203 | "set" 204 | ] 205 | }, 206 | "outputs": [], 207 | "source": [ 208 | "us.loc[us['ID'] == 10055828, 'ORG_ZIPCODE'] = '20707' # Would have got SettingWithCopyError if we did not use `copy()` above when assigning a slice of `df` to `us`" 209 | ] 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "metadata": {}, 214 | "source": [ 215 | "# Whew, better. \n", 216 | "\n", 217 | "## Wait, what about length? Zip codes should only be 5 or 9 characters. It's probably fine, but lets just check really quick:" 218 | ] 219 | }, 220 | { 221 | "cell_type": "code", 222 | "execution_count": null, 223 | "metadata": { 224 | "tags": [ 225 | "str", 226 | "dataframe", 227 | "pandas", 228 | "style", 229 | "apply" 230 | ] 231 | }, 232 | "outputs": [], 233 | "source": [ 234 | "us.loc[~(us['ORG_ZIPCODE'].str.len() == 5) & ~(us['ORG_ZIPCODE'].str.len() == 9)].head().style.apply(highlight_columns, match_strings_list=['ORG_ZIPCODE'])" 235 | ] 236 | }, 237 | { 238 | "cell_type": "markdown", 239 | "metadata": {}, 240 | "source": [ 241 | "# Yikes, that cannot be right. Fret not, we will smote and vanish these dragons!\n", 242 | "\n", 243 | "## Looks like the data came with leading zeros pre-stripped from the `ORG_ZIPCODE` column. That is going to make joining a little harder so lets go ahead and fix these.\n", 244 | "\n", 245 | "# Pad the zips with `len() < 5` first" 246 | ] 247 | }, 248 | { 249 | "cell_type": "code", 250 | "execution_count": null, 251 | "metadata": { 252 | "tags": [ 253 | "justify", 254 | "rjust" 255 | ] 256 | }, 257 | "outputs": [], 258 | "source": [ 259 | "is_len_less_five = us['ORG_ZIPCODE'].str.len() < 5\n", 260 | "us.loc[is_len_less_five, 'ORG_ZIPCODE'] = [s.rjust(5, '0')[:5] for idx, s in us.loc[is_len_less_five, 'ORG_ZIPCODE'].items()]" 261 | ] 262 | }, 263 | { 264 | "cell_type": "markdown", 265 | "metadata": {}, 266 | "source": [ 267 | "# Pad the zips with `len() > 5` next." 268 | ] 269 | }, 270 | { 271 | "cell_type": "code", 272 | "execution_count": null, 273 | "metadata": {}, 274 | "outputs": [], 275 | "source": [ 276 | "is_len_gt_five = us['ORG_ZIPCODE'].str.len() > 5\n", 277 | "us.loc[(is_len_gt_five), 'ORG_ZIPCODE'] = [s.rjust(9, '0')[:5] for idx, s in us.loc[(is_len_gt_five), 'ORG_ZIPCODE'].items()]" 278 | ] 279 | }, 280 | { 281 | "cell_type": "markdown", 282 | "metadata": {}, 283 | "source": [ 284 | "# Lets see if those dragons are gone?!?" 285 | ] 286 | }, 287 | { 288 | "cell_type": "code", 289 | "execution_count": null, 290 | "metadata": {}, 291 | "outputs": [], 292 | "source": [ 293 | "us.loc[~((us['ORG_ZIPCODE'].str.len() == 5) | (us['ORG_ZIPCODE'].str.len() == 9))].size == 0" 294 | ] 295 | }, 296 | { 297 | "cell_type": "markdown", 298 | "metadata": {}, 299 | "source": [ 300 | "# Import ZIP to GEO data\n", 301 | "\n", 302 | "The zip/geo data was [downloaded from ODS](https://public.opendatasoft.com/explore/dataset/us-zip-code-latitude-and-longitude/export/?dataChart=eyJxdWVyaWVzIjpbeyJjb25maWciOnsiZGF0YXNldCI6InVzLXppcC1jb2RlLWxhdGl0dWRlLWFuZC1sb25naXR1ZGUiLCJvcHRpb25zIjp7fX0sImNoYXJ0cyI6W3siYWxpZ25Nb250aCI6dHJ1ZSwidHlwZSI6ImNvbHVtbiIsImZ1bmMiOiJBVkciLCJ5QXhpcyI6ImxhdGl0dWRlIiwic2NpZW50aWZpY0Rpc3BsYXkiOnRydWUsImNvbG9yIjoiI0ZGNTE1QSJ9XSwieEF4aXMiOiJzdGF0ZSIsIm1heHBvaW50cyI6NTAsInNvcnQiOiIifV0sInRpbWVzY2FsZSI6IiIsImRpc3BsYXlMZWdlbmQiOnRydWUsImFsaWduTW9udGgiOnRydWV9&location=3,43.19717,-48.51562&basemap=jawg.streets) (Open Data Share)" 303 | ] 304 | }, 305 | { 306 | "cell_type": "code", 307 | "execution_count": null, 308 | "metadata": { 309 | "tags": [ 310 | "dtype", 311 | "read_csv" 312 | ] 313 | }, 314 | "outputs": [], 315 | "source": [ 316 | "zips_to_coords = pd.read_csv('./zip_geo.gzip', sep=';', compression='gzip', dtype={'Zip': 'str'}, encoding=\"ISO-8859-1\")" 317 | ] 318 | }, 319 | { 320 | "cell_type": "markdown", 321 | "metadata": {}, 322 | "source": [ 323 | "# Lets make sure there are no dups" 324 | ] 325 | }, 326 | { 327 | "cell_type": "code", 328 | "execution_count": null, 329 | "metadata": { 330 | "tags": [ 331 | "duplicated" 332 | ] 333 | }, 334 | "outputs": [], 335 | "source": [ 336 | "zips_to_coords[zips_to_coords.duplicated('Zip')]" 337 | ] 338 | }, 339 | { 340 | "cell_type": "markdown", 341 | "metadata": {}, 342 | "source": [ 343 | "# Wait, there are some coordinates missing. We need to append to the dataframe" 344 | ] 345 | }, 346 | { 347 | "cell_type": "code", 348 | "execution_count": null, 349 | "metadata": { 350 | "tags": [ 351 | "append", 352 | "dataframe" 353 | ] 354 | }, 355 | "outputs": [], 356 | "source": [ 357 | "# append an array of series to a dataframe\n", 358 | "zip_cols = zips_to_coords.columns\n", 359 | "zips_to_add = [pd.Series(['94158', 37.77244949, -122.39166260], index=zip_cols),\n", 360 | " pd.Series(['10065', 40.76429569, -73.96246150], index=zip_cols)]\n", 361 | "zips_to_coords = zips_to_coords.append(zips_to_add, ignore_index=True)" 362 | ] 363 | }, 364 | { 365 | "cell_type": "code", 366 | "execution_count": null, 367 | "metadata": {}, 368 | "outputs": [], 369 | "source": [ 370 | "zips_to_coords[zips_to_coords.duplicated('Zip', keep='first')]" 371 | ] 372 | }, 373 | { 374 | "cell_type": "markdown", 375 | "metadata": {}, 376 | "source": [ 377 | "# Oh I was wrong, those did not need to be added. Lets remove:" 378 | ] 379 | }, 380 | { 381 | "cell_type": "code", 382 | "execution_count": null, 383 | "metadata": { 384 | "tags": [ 385 | "drop_duplicates", 386 | "pandas", 387 | "dataframe" 388 | ] 389 | }, 390 | "outputs": [], 391 | "source": [ 392 | "# drop duplicates in place\n", 393 | "zips_to_coords.drop_duplicates(subset=\"Zip\", inplace=True)" 394 | ] 395 | }, 396 | { 397 | "cell_type": "code", 398 | "execution_count": null, 399 | "metadata": {}, 400 | "outputs": [], 401 | "source": [ 402 | "zips_to_coords[zips_to_coords.duplicated('Zip', keep='first')].size == 0" 403 | ] 404 | }, 405 | { 406 | "cell_type": "markdown", 407 | "metadata": {}, 408 | "source": [ 409 | "# Whew. That was glorious. Now lets merge these dataframes so we can get lat/long on our `us` dataframe" 410 | ] 411 | }, 412 | { 413 | "cell_type": "code", 414 | "execution_count": null, 415 | "metadata": { 416 | "tags": [ 417 | "join", 418 | "dataframe", 419 | "pandas" 420 | ] 421 | }, 422 | "outputs": [], 423 | "source": [ 424 | "# join two dataframes on the original dataframes' column. Index must be set appropriately on second df.\n", 425 | "us = us.join(zips_to_coords.loc[:, ['Zip', 'Latitude', 'Longitude']].set_index('Zip'), on='ORG_ZIPCODE')" 426 | ] 427 | }, 428 | { 429 | "cell_type": "code", 430 | "execution_count": null, 431 | "metadata": { 432 | "tags": [ 433 | "style", 434 | "apply", 435 | "pandas" 436 | ] 437 | }, 438 | "outputs": [], 439 | "source": [ 440 | "us.iloc[:5, [0,14,15]].style.apply(highlight_columns, match_strings_list=['Longitude', 'Latitude'])" 441 | ] 442 | }, 443 | { 444 | "cell_type": "markdown", 445 | "metadata": {}, 446 | "source": [ 447 | "## Lets examine top administering agencies" 448 | ] 449 | }, 450 | { 451 | "cell_type": "code", 452 | "execution_count": null, 453 | "metadata": {}, 454 | "outputs": [], 455 | "source": [ 456 | "us['IC'].value_counts()[:5]" 457 | ] 458 | }, 459 | { 460 | "cell_type": "markdown", 461 | "metadata": {}, 462 | "source": [ 463 | "## Note that value_counds is a shortcut for `groupby()` and `count()`:\n", 464 | "\n", 465 | "Only `value_counts()` automatically sorts the list though." 466 | ] 467 | }, 468 | { 469 | "cell_type": "code", 470 | "execution_count": null, 471 | "metadata": { 472 | "tags": [ 473 | "groupby" 474 | ] 475 | }, 476 | "outputs": [], 477 | "source": [ 478 | "us.groupby('IC').IC.count().sort_values(ascending=False)[:5]" 479 | ] 480 | }, 481 | { 482 | "cell_type": "markdown", 483 | "metadata": {}, 484 | "source": [ 485 | "### There are a lot of other cool things you can do with `groupby` when it is combined with the `agg` function.\n", 486 | "\n", 487 | "# Let's say we want to group cities together and get the sum and max direct cost:" 488 | ] 489 | }, 490 | { 491 | "cell_type": "code", 492 | "execution_count": null, 493 | "metadata": { 494 | "tags": [ 495 | "groupby", 496 | "agg" 497 | ] 498 | }, 499 | "outputs": [], 500 | "source": [ 501 | "us.groupby('ORG_CITY').DIRECT_COST_AMT.agg([sum, max]).sort_values(by=\"sum\", ascending=False)[:10]" 502 | ] 503 | }, 504 | { 505 | "cell_type": "markdown", 506 | "metadata": {}, 507 | "source": [ 508 | "## Lets say we are only interested in 3 NIH agencies." 509 | ] 510 | }, 511 | { 512 | "cell_type": "code", 513 | "execution_count": null, 514 | "metadata": {}, 515 | "outputs": [], 516 | "source": [ 517 | "nih_agencies = [{\n", 518 | " \"code\": \"AI\",\n", 519 | " \"name\": \"NIH National Institute of Allergy and Infectious Diseases (NIAID)\"\n", 520 | " }, {\n", 521 | " \"code\": \"GM\",\n", 522 | " \"name\": \"NIH National Institute of General Medical Sciences (NIGMS)\"\n", 523 | " }, {\n", 524 | " \"code\": \"CA\",\n", 525 | " \"name\": \"NIH National Cancer Institute (NCI)\"\n", 526 | " }]" 527 | ] 528 | }, 529 | { 530 | "cell_type": "code", 531 | "execution_count": null, 532 | "metadata": {}, 533 | "outputs": [], 534 | "source": [ 535 | "agency_list = [obj['code'] for obj in nih_agencies]" 536 | ] 537 | }, 538 | { 539 | "cell_type": "markdown", 540 | "metadata": {}, 541 | "source": [ 542 | "# Create `agc` which contains only grants from AI, GM, CA" 543 | ] 544 | }, 545 | { 546 | "cell_type": "code", 547 | "execution_count": null, 548 | "metadata": {}, 549 | "outputs": [], 550 | "source": [ 551 | "%%time\n", 552 | "agc = us.loc[us['IC'].isin(agency_list)].copy()" 553 | ] 554 | }, 555 | { 556 | "cell_type": "code", 557 | "execution_count": null, 558 | "metadata": {}, 559 | "outputs": [], 560 | "source": [ 561 | "agc.loc[:, 'TOTAL_COST'].sum()" 562 | ] 563 | }, 564 | { 565 | "cell_type": "markdown", 566 | "metadata": {}, 567 | "source": [ 568 | "## How many grant awards have no associated cost information?" 569 | ] 570 | }, 571 | { 572 | "cell_type": "code", 573 | "execution_count": null, 574 | "metadata": {}, 575 | "outputs": [], 576 | "source": [ 577 | "agc.loc[pd.isna(agc['DIRECT_COST_AMT']) & pd.isna(agc['TOTAL_COST'])].style.apply(highlight_columns, match_strings_list=['DIRECT_COST_AMT', 'TOTAL_COST'])" 578 | ] 579 | }, 580 | { 581 | "cell_type": "code", 582 | "execution_count": null, 583 | "metadata": { 584 | "tags": [ 585 | "groupby", 586 | "count", 587 | "index", 588 | "astype" 589 | ] 590 | }, 591 | "outputs": [], 592 | "source": [ 593 | "# Get a series and count the values grouped by year when column is datetime64[ns]\n", 594 | "project_start = agc.loc[:, \"PROJECT_START\"].groupby(agc.loc[:, \"PROJECT_START\"].dt.year).count()\n", 595 | "ps_series = pd.Series(project_start.values, project_start.index.astype('int64'), name=\"start\")" 596 | ] 597 | }, 598 | { 599 | "cell_type": "code", 600 | "execution_count": null, 601 | "metadata": {}, 602 | "outputs": [], 603 | "source": [ 604 | "project_end = agc.loc[:, \"PROJECT_END\"].groupby(agc.loc[:, \"PROJECT_END\"].dt.year).count()\n", 605 | "pe_series = pd.Series(project_end.values, project_end.index.astype('int64'), name=\"end\")" 606 | ] 607 | }, 608 | { 609 | "cell_type": "code", 610 | "execution_count": null, 611 | "metadata": { 612 | "tags": [ 613 | "style", 614 | "use", 615 | "matplotlib" 616 | ] 617 | }, 618 | "outputs": [], 619 | "source": [ 620 | "matplotlib.style.use('fivethirtyeight')" 621 | ] 622 | }, 623 | { 624 | "cell_type": "code", 625 | "execution_count": null, 626 | "metadata": { 627 | "tags": [ 628 | "dataframe", 629 | "plot", 630 | "series" 631 | ] 632 | }, 633 | "outputs": [], 634 | "source": [ 635 | "# Create a dataframe from array of series and plot\n", 636 | "pd.DataFrame([ps_series, pe_series]).T.plot(kind=\"bar\", width=1.0, figsize=(18, 4), title=\"Project Start and End Count by Year\")" 637 | ] 638 | }, 639 | { 640 | "cell_type": "code", 641 | "execution_count": null, 642 | "metadata": {}, 643 | "outputs": [], 644 | "source": [ 645 | "agc[['TOTAL_COST', 'DIRECT_COST_AMT']].describe()" 646 | ] 647 | }, 648 | { 649 | "cell_type": "code", 650 | "execution_count": null, 651 | "metadata": {}, 652 | "outputs": [], 653 | "source": [ 654 | "largest_awards = agc.loc[:, [\"ID\", \"IC\", \"ORG_CITY\", \"ORG_NAME\", \"PROJECT_TITLE\", \"TOTAL_COST\"]].sort_values(by=['TOTAL_COST'], ascending=False)" 655 | ] 656 | }, 657 | { 658 | "cell_type": "code", 659 | "execution_count": null, 660 | "metadata": {}, 661 | "outputs": [], 662 | "source": [ 663 | "largest_awards.head(10)" 664 | ] 665 | }, 666 | { 667 | "cell_type": "markdown", 668 | "metadata": {}, 669 | "source": [ 670 | "# What organizations receive the most awards?\n", 671 | "\n", 672 | "### Create a series with `value_counts()` that sorts the organizations by award count." 673 | ] 674 | }, 675 | { 676 | "cell_type": "code", 677 | "execution_count": null, 678 | "metadata": {}, 679 | "outputs": [], 680 | "source": [ 681 | "top_organizations = agc['ORG_NAME'].value_counts()" 682 | ] 683 | }, 684 | { 685 | "cell_type": "code", 686 | "execution_count": null, 687 | "metadata": {}, 688 | "outputs": [], 689 | "source": [ 690 | "top_organizations[0:10]" 691 | ] 692 | } 693 | ], 694 | "metadata": { 695 | "celltoolbar": "Tags", 696 | "kernelspec": { 697 | "display_name": "Python 3", 698 | "language": "python", 699 | "name": "python3" 700 | }, 701 | "language_info": { 702 | "codemirror_mode": { 703 | "name": "ipython", 704 | "version": 3 705 | }, 706 | "file_extension": ".py", 707 | "mimetype": "text/x-python", 708 | "name": "python", 709 | "nbconvert_exporter": "python", 710 | "pygments_lexer": "ipython3", 711 | "version": "3.7.6" 712 | }, 713 | "nteract": { 714 | "version": "nteract-on-jupyter@2.1.3" 715 | } 716 | }, 717 | "nbformat": 4, 718 | "nbformat_minor": 4 719 | } --------------------------------------------------------------------------------