Python: slicing a multi-dimensional array

If you use numpy, this is easy: or if you want the 0’s, You’ll get the same result. *note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different “name”. Another way, if you’re working with lists of lists*: (Note that the 0’s here are unnecessary: [arr[i][:2] for i in range(2)] would … Read more

Combine two columns of text in pandas dataframe

If both columns are strings, you can concatenate them directly: If one (or both) of the columns are not string typed, you should convert it (them) first, Beware of NaNs when doing this! If you need to join multiple string columns, you can use agg: Where “-” is the separator.

How do I clear all variables in the middle of a Python script?

The following sequence of commands does remove every name from the current module: I doubt you actually DO want to do this, because “every name” includes all built-ins, so there’s not much you can do after such a total wipe-out. Remember, in Python there is really no such thing as a “variable” — there are objects, of many … Read more

Python subprocess.Popen “OSError: [Errno 12] Cannot allocate memory”

As a general rule (i.e. in vanilla kernels), fork/clone failures with ENOMEM occur specifically because of either an honest to God out-of-memory condition (dup_mm, dup_task_struct, alloc_pid, mpol_dup, mm_init etc. croak), or because security_vm_enough_memory_mm failed you while enforcing the overcommit policy. Start by checking the vmsize of the process that failed to fork, at the time of the fork attempt, and then compare to the amount of free memory (physical and swap) as it … Read more

Python string class like StringBuilder in C#?

There is no one-to-one correlation. For a really good article please see Efficient String Concatenation in Python: Building long strings in the Python progamming language can sometimes result in very slow running code. In this article I investigate the computational performance of various string concatenation methods. TLDR the fastest method is below. It’s extremely compact, and … Read more