text
stringlengths
4
1.08k
(Django) how to get month name?,today.strftime('%B')
join list of lists in python,[j for i in x for j in i]
join list of lists in python,print(list(itertools.chain.from_iterable(a)))
Convert Date String to Day of Week,"datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')"
Convert Date String to Day of Week,"datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%a')"
delete a list element by value,a.remove('b')
delete a list element by value,a.remove(c)
delete a list element by value,a.remove(6)
delete a list element by value,a.remove(6)
delete a list element by value,"if (c in a):
a.remove(c)"
Python re.findall print all patterns,"re.findall('(?=(a.*?a))', 'a 1 a 2 a 3 a 4 a')"
Outer product of each column of a 2D array to form a 3D array - NumPy,"np.einsum('ij,kj->jik', X, X)"
Getting the last element of a list,some_list[(-1)]
Getting the last element of a list,some_list[(-2)]
gets the nth-to-last element,some_list[(- n)]
Getting the last element of a list,alist[(-1)]
Getting the last element of a list,astr[(-1)]
Create a list of integers with duplicate values in Python,"print([u for v in [[i, i] for i in range(5)] for u in v])"
Create a list of integers with duplicate values in Python,"[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]"
Create a list of integers with duplicate values in Python,[(i // 2) for i in range(10)]
Fastest way to remove first and last lines from a Python string,s[s.find('\n') + 1:s.rfind('\n')]
Is there a Python dict without values?,{(x ** 2) for x in range(100)}
How to zip lists in a list,"zip(*[[1, 2], [3, 4], [5, 6]])"
How to zip lists in a list,"zip(*[[1, 2], [3, 4], [5, 6]])"
python http request with token,"requests.get('https://www.mysite.com/', auth=('username', 'pwd'))"
get a new string from the 3rd character to the end of the string,x[2:]
substring a string,x[:2]
substring a string,x[:(-2)]
substring a string,x[(-2):]
substring a string,x[2:(-2)]
reversing a string,some_string[::(-1)]
selecting alternate characters,'H-e-l-l-o- -W-o-r-l-d'[::2]
substring a string,s = s[beginning:(beginning + LENGTH)]
Terminating a Python script,sys.exit()
Terminating a Python script,quit()
Terminating a Python script,sys.exit('some error message')
Transform unicode string in python,"data['City'].encode('ascii', 'ignore')"
get current CPU and RAM usage,"psutil.cpu_percent()
psutil.virtual_memory()"
get current CPU and RAM usage,"pid = os.getpid()
py = psutil.Process(pid)
memoryUse = (py.memory_info()[0] / (2.0 ** 30))"
get current CPU and RAM usage,"print((psutil.cpu_percent()))
print((psutil.virtual_memory()))"
"Pandas read_csv expects wrong number of columns, with ragged csv file","pd.read_csv('D:/Temp/tt.csv', names=list('abcdef'))"
First non-null value per row from a list of Pandas columns,df.stack().groupby(level=0).first()
format strings and named arguments in Python,"""""""{0} {1}"""""".format(10, 20)"
format strings and named arguments in Python,"""""""{1} {ham} {0} {foo} {1}"""""".format(10, 20, foo='bar', ham='spam')"
How to convert strings numbers to integers in a list?,changed_list = [(int(f) if f.isdigit() else f) for f in original_list]
Add items to a dictionary of lists,"dict(zip(keys, zip(*data)))"
Python: Converting from ISO-8859-1/latin1 to UTF-8,apple.decode('iso-8859-1').encode('utf8')
How do you remove the column name row from a pandas DataFrame?,"df.to_csv('filename.csv', header=False)"
"how to get around ""Single '}' encountered in format string"" when using .format and formatting in printing","print('{0}:<15}}{1}:<15}}{2}:<8}}'.format('1', '2', '3'))"
"Python list of dicts, get max value index","max(ld, key=lambda d: d['size'])"
Format() in Python Regex,"""""""{0}\\w{{2}}b{1}\\w{{2}}quarter"""""".format('b', 'a')"
How to use 'User' as foreign key in Django 1.5,"user = models.ForeignKey('User', unique=True)"
Regex match even number of letters,re.compile('^([^A]*)AA([^A]|AA)*$')
Combining NumPy arrays,"b = np.concatenate((a, a), axis=0)"
How to custom sort an alphanumeric list?,"sorted(l, key=lambda x: x.replace('0', 'Z'))"
Plot logarithmic axes with matplotlib in python,ax.set_yscale('log')
Access environment variables,os.environ['HOME']
Access environment variables,os.environ['HOME']
Access environment variables,print(os.environ)
Access environment variables,os.environ
Access environment variables,print(os.environ.get('KEY_THAT_MIGHT_EXIST'))
Access environment variables,"print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))"
Access environment variables,"print(os.environ.get('HOME', '/home/username/'))"
How to split a string within a list to create key-value pairs in Python,print(dict([s.split('=') for s in my_list]))
finding index of an item closest to the value in a list that's not entirely sorted,"min(enumerate(a), key=lambda x: abs(x[1] - 11.5))"
How to use lxml to find an element by text?,"e = root.xpath('.//a[contains(text(),""TEXT A"")]')"
How to use lxml to find an element by text?,"e = root.xpath('.//a[starts-with(text(),""TEXT A"")]')"
How to use lxml to find an element by text?,"e = root.xpath('.//a[text()=""TEXT A""]')"
Python: an efficient way to slice a list with a index list,c = [b[i] for i in index]
Multiplication of 1d arrays in numpy,"np.dot(a[:, (None)], b[(None), :])"
Multiplication of 1d arrays in numpy,"np.outer(a, b)"
Execute a file with arguments in Python shell,"subprocess.call(['./abc.py', arg1, arg2])"
Pandas: Fill missing values by mean in each group faster than transfrom,df[['value']].fillna(df.groupby('group').transform('mean'))
Python regex alternative for join,"re.sub('(.)(?=.)', '\\1-', s)"
Python regex alternative for join,"re.sub('(?<=.)(?=.)', '-', str)"
Index of element in Numpy array,"i, j = np.where(a == value)"
Finding the most frequent character in a string,print(collections.Counter(s).most_common(1)[0])
How to match beginning of string or character in Python,"float(re.findall('(?:^|_)' + par + '(\\d+\\.\\d*)', dir)[0])"
How to match beginning of string or character in Python,"re.findall('[^a]', 'abcd')"
How to get a list of variables in specific Python module?,print([item for item in dir(adfix) if not item.startswith('__')])
Get the first element of each tuple in a list in Python,[x[0] for x in rows]
Get the first element of each tuple in a list in Python,res_list = [x[0] for x in rows]
How to repeat Pandas data frame?,"pd.concat([x] * 5, ignore_index=True)"
How to repeat Pandas data frame?,pd.concat([x] * 5)
Sorting JSON in python by a specific value,"sorted_list_of_keyvalues = sorted(list(ips_data.items()), key=item[1]['data_two'])"
JSON to pandas DataFrame,pd.read_json(elevations)
Generate random numbers with a given (numerical) distribution,"numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])"
Find maximum value of a column and return the corresponding row values using Pandas,df.loc[df['Value'].idxmax()]
Finding recurring patterns in a string,"re.findall('^(.+?)((.+)\\3+)$', '42344343434')[0][:-1]"
convert binary string to numpy array,"np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='<f4')"
convert binary string to numpy array,"np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='>f4')"
How to use variables in SQL statement in Python?,"cursor.execute('INSERT INTO table VALUES (?, ?, ?)', (var1, var2, var3))"
How to use variables in SQL statement in Python?,"cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))"
How to use variables in SQL statement in Python?,"cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))"
pandas split string into columns,"df['stats'].str[1:-1].str.split(',', expand=True).astype(float)"