If Python is interpreted, what are .pyc files?

I’ve been given to understand that Python is an interpreted language… This popular meme is incorrect, or, rather, constructed upon a misunderstanding of (natural) language levels: a similar mistake would be to say “the Bible is a hardcover book”. Let me explain that simile… “The Bible” is “a book” in the sense of being a … Read more

How to add a new column to an existing DataFrame?

Edit 2017 As indicated in the comments and by @Alexander, currently the best method to add the values of a Series as a new column of a DataFrame could be using assign: df1 = df1.assign(e=pd.Series(np.random.randn(sLength)).values) Edit 2015 Some reported getting the SettingWithCopyWarning with this code. However, the code still runs perfectly with the current pandas … Read more

Why do people write #!/usr/bin/env python on the first line of a Python script?

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

Running shell command and capturing the output

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

Display number with leading zeros

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}”)

Create a Pandas Dataframe by appending one row at a time

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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)