Getting key with maximum value in dictionary?
max(stats, key=stats.get)
max(stats, key=stats.get)
You could use: with open(‘data.txt’, ‘r’) as file: data = file.read().replace(‘\n’, ”) Or if the file content is guaranteed to be one-line with open(‘data.txt’, ‘r’) as file: data = file.read().rstrip()
If you have several versions of Python installed, /usr/bin/env will ensure the interpreter used is the first one on your environment’s $PATH. The alternative would be to hardcode something like #!/usr/bin/python; that’s ok, but less flexible. In Unix, an executable file that’s meant to be interpreted can indicate what interpreter to use by having a … Read more
In all officially maintained versions of Python, the simplest approach is to use the subprocess.check_output function: >>> subprocess.check_output([‘ls’, ‘-l’]) b’total 0\n-rw-r–r– 1 memyself staff 0 Mar 14 11:04 files\n’ check_output runs a single program that takes only arguments as input.1 It returns the result exactly as printed to stdout. If you need to write input … Read more
In Python 2 (and Python 3) you can do: number = 1 print(“%02d” % (number,)) Basically % is like printf or sprintf (see docs). For Python 3.+, the same behavior can also be achieved with format: number = 1 print(“{:02d}”.format(number)) For Python 3.6+ the same behavior can be achieved with f-strings: number = 1 print(f”{number:02d}”)
You can use df.loc[i], where the row with index i will be what you specify it to be in the dataframe. >>> import pandas as pd >>> from numpy.random import randint >>> df = pd.DataFrame(columns=[‘lib’, ‘qty1’, ‘qty2’]) >>> for i in range(5): >>> df.loc[i] = [‘name’ + str(i)] + list(randint(10, size=2)) >>> df lib qty1 … Read more
The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method … Read more
There are two types of site-packages directories, global and per user. Global site-packages (“dist-packages”) directories are listed in sys.path when you run: python -m site For a more concise list run getsitepackages from the site module in Python code: python -c ‘import site; print(site.getsitepackages())’ Caution: In virtual environments getsitepackages is not available with older versions … Read more
You can get the values as a list by doing: list(my_dataframe.columns.values) Also you can simply use (as shown in Ed Chum’s answer): list(my_dataframe)
To get a new reversed list, apply the reversed function and collect the items into a list: >>> xs = [0, 10, 20, 40] >>> list(reversed(xs)) [40, 20, 10, 0] To iterate backwards through a list: >>> xs = [0, 10, 20, 40] >>> for x in reversed(xs): … print(x) 40 20 10 0