Useful Anaconda terminal commands

Create Anaconda environment: conda create –name MyEnv Activate virtual environment on Windows: activate MyEnv Install package conda install package-name Activate virtual environment on LINUX, macOS: source activate MyEnv Clone base Anaconda environment: conda create –name MyEnv –clone base Deactivate current environment: conda deactivate List all packages and versions installed in active environment: conda list Get … Read more

Select dataframe rows by specific column string values in Pandas

Hello, I’m back! 😎 Now the traditional method is this: df.loc[df[‘column_name’] == value] For string, and for numeric values this: df.loc[df[‘column_name’] == ‘string’] While it always work with numeric values, for string values sometimes it doesn’t work. It picks up a blank dataframe. I guess it’s something to do with encoding of the source where … Read more

Remove a list of unwanted items from another list with list comprehension

I love list comprehensions. I really do. And it’s time for list comprehensions! If you need to withhold all items from a list1 that are present in list2 – nothing else works better! There we go, beautiful & clean code: list1 = [‘banana’, ‘orange’, ‘apple’, ‘apple’, ‘lemon’, ‘strawberry’, ‘pineapple’, ‘melon’, ‘melon’, ‘peach’, ‘pear’] list2 = … Read more

Save Pandas Dataframe to .csv file

Best way is to use Panda’s to_csv() built-in function df.to_csv(‘filename’, index=False) Don’t forget to pass index=False as a second parameter if you don’t want index row saved as a column (in other words use it if you don’t want duplicated index when opening the file again). By the way, you can also withhold column names … Read more

Read and write files with ‘with’ statement in Python

I always keep forgetting how exactly with statement works with opening and reading the files in Python. path = ‘./path/filename.txt’ with open(path,’r’) as file: data = file.readlines() print(data) Or if you would like to avoid getting ‘\n’ after each line when using .readlines() you can use this instead: data = file.read().splitlines() Opening files with ‘with’ … Read more

How to iterate through dictionary in Python

First you might think in order to print dictionary values it’s enough to: for i in dict: print(i) But No. This way it’ll only print the keys. In order to print values next to the dictionary keys use: for key in dict: print(key, ‘-‘, dict[key])

TypeError: ‘int’ object is not iterable

For all noobs like me. If you get this error, you most probably doing one stupid thing like I did: where y2.shape[0] is just an integer. Remember, we can iterate only through lists or other sequences. When we would like to repeat a certain action X number of times we should do the following: If … Read more