text
stringlengths
4
1.08k
how to remove multiple indexes from a list at the same time?,del my_list[2:6]
convert a datetime object `dt` to microtime,time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0
how to capture the entire string while using 'lookaround' with chars in regex?,"re.findall('(b+a)+b+', mystring)"
open file with a unicode filename?,open('someUnicodeFilename\u03bb')
django set default form values,form = JournalForm(initial={'tank': 123})
set utc offset by 9 hrs ahead for date '2013/09/11 00:17',dateutil.parser.parse('2013/09/11 00:17 +0900')
inserting an element before each element of a list,[item for sublist in l for item in sublist]
how to do a regex replace with matching case?,"re.sub('\\bfoo\\b', cased_replacer('bar'), 'this is Foo', flags=re.I)"
find array corresponding to minimal values along an axis in another array,"np.tile(np.arange(y), x)"
remove all data inside parenthesis in string `item`,"item = re.sub(' \\(\\w+\\)', '', item)"
"copy 2d array into 3rd dimension, n times (python)","c = np.array([1, 2, 3])"
python string replacement with % character/**kwargs weirdness,'%%%s%%' % 'PLAYER_ID'
finding the first list element for which a condition is true,"next((e for e in mylist if my_criteria(e)), None)"
convert a string to preexisting variable names,print(eval('self.post.id'))
how to add group labels for bar charts in matplotlib?,plt.show()
how can i check a python unicode string to see that it *actually* is proper unicode?,""""""""""""".decode('utf8')"
return the column for value 38.15 in dataframe `df`,"df.ix[:, (df.loc[0] == 38.15)].columns"
create file path from variables,"os.path.join('/my/root/directory', 'in', 'here')"
how to add unicode character before a string? [python],print(type('{}'.format(word)))
how to find duplicate elements in array using for loop in python?,[i for i in y if y[i] > 1]
clear terminal in python,os.system('cls' if os.name == 'nt' else 'clear')
python: extract numbers from a string,"[int(s) for s in re.findall('\\b\\d+\\b', ""he33llo 42 I'm a 32 string 30"")]"
check if all elements in list `mylist` are the same,len(set(mylist)) == 1
how to filter rows of pandas dataframe by checking whether sub-level index value within a list?,df[df.index.levels[0].isin([int(i) for i in stk_list])]
python - remove dictionary from list if key is equal to value,a = [x for x in a if x['link'] not in b]
convert unicode codepoint to utf8 hex,"chr(int('fd9b', 16)).encode('utf-8')"
string splitting in python,s.split('s')
sqlalchemy: a better way for update with declarative?,session.query(User).filter_by(id=123).update({'name': 'Bob Marley'})
replace the single quote (') character from a string,"re.sub(""'"", '', ""A single ' char"")"
"sorting a list of dot-separated numbers, like software versions","['1.0.0', '1.0.2', '1.0.12', '1.1.2', '1.3.3']"
python: how to create a file .txt and record information in it,file.close()
python - concatenate a string to include a single backslash,"""""""INTERNET\\jDoe"""""""
how can i strip the file extension from a list full of filenames?,lst = [os.path.splitext(x)[0] for x in accounts]
how would one add a colorbar to this example?,"plt.figure(figsize=(5, 6))"
"how to split but ignore separators in quoted strings, in python?","re.split(';(?=(?:[^\'""]|\'[^\']*\'|""[^""]*"")*$)', data)"
how to access all dictionaries within a dictionary where a specific key has a particular value,list([x for x in list(all_dicts.values()) if x['city'] == 'bar'])
get the context of a search by keyword 'my keywords' in beautifulsoup `soup`,k = soup.find(text=re.compile('My keywords')).parent.text
convert a row in pandas into list,"df.apply(lambda x: x.tolist(), axis=1)"
python pandas: how to move one row to the first row of a dataframe?,df.set_index('a')
windows path in python,"os.path.join('C:', 'meshes', 'as')"
python pandas pivot table,"df.pivot_table('Y', rows='X', cols='X2')"
save xlsxwriter file in 'app/smth1/smth2/expenses01.xlsx' path and assign to variable `workbook`,workbook = xlsxwriter.Workbook('app/smth1/smth2/Expenses01.xlsx')
removing non-breaking spaces from strings using python,"myString = myString.replace('\xc2\xa0', ' ')"
get all indexes of a letter `e` from a string `word`,"[index for index, letter in enumerate(word) if letter == 'e']"
split string `word to split` into a list of characters,list('Word to Split')
adding a scatter of points to a boxplot using matplotlib,"plot(x, y, 'r.', alpha=0.2)"
split elements of a list in python,myList = [i.split('\t')[0] for i in myList]
most pythonic way to fit a variable to a range?,"result = min(max_value, max(min_value, result))"
how to use popen to run backgroud process and avoid zombie?,"signal.signal(signal.SIGCHLD, signal.SIG_IGN)"
how do i import modules in pycharm?,__init__.py
python string and integer concatenation,[('string' + str(i)) for i in range(11)]
finding whether a list contains a particular numpy array,"any(np.array_equal(np.array([[0, 0], [0, 0]]), x) for x in my_list)"
extract usercertificate from pkcs7 envelop in python,certificat = signers[0]
finding the index value of the smallest number in a list?,n.index(min(n))
how to read a csv file in reverse order in python,"print(', '.join(row))"
how to make good reproducible pandas examples,"df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B'])"
simple way of creating a 2d array with random numbers (python),"np.random.random((N, N))"
convert a string of integers `x` separated by spaces to a list of integers,x = [int(i) for i in x.split()]
json to model a class using django,"{'username': 'clelio', 'name': 'Clelio de Paula'}"
run function 'sudsmove' simultaneously,threading.Thread(target=SudsMove).start()
python: how to normalize a confusion matrix?,C / C.astype(np.float).sum(axis=1)
is there a way to reopen a socket?,"sck.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)"
python merging two lists with all possible permutations,"[list(zip(a, p)) for p in permutations(b)]"
python - how to cut a string in python?,s[:s.rfind('&')]
converting from a string to boolean in python?,str2bool('0')
how to use the mv command in python with subprocess,"subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)"
combine or join numpy arrays,"[(0, 0), (0, 1), (1, 0), (1, 1)]"
convert timestamp since epoch to datetime.datetime,"time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(1346114717972 / 1000.0))"
dijkstra's algorithm in python,"{'E': 2, 'D': 1, 'G': 2, 'F': 4, 'A': 4, 'C': 3, 'B': 0}"
python argparse - optional append argument with choices,"parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')"
how to convert a date string to a datetime object?,"datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')"
finding index of maximum element from python list,"from functools import reduce
reduce(lambda a, b: [a, b], [1, 2, 3, 4])"
how to iterate and update documents with pymongo?,cursor = collection.find({'$snapshot': True})
extract digits in a simple way from a python string,"map(int, re.findall('\\d+', s))"
how to pass multiple values for a single url parameter?,request.GET.getlist('urls')
"python, matplotlib, subplot: how to set the axis range?","pylab.ylim([0, 1000])"
how to sort a dataframe in python pandas by two or more columns?,"df1.sort(['a', 'b'], ascending=[True, False])"
convert array `x` into a correlation matrix,np.corrcoef(x)
sort a set `s` by numerical value,"sorted(s, key=float)"
how to count occurences at the end of the list,"print(list_end_counter([1, 2, 1, 1, 1, 1, 1, 1]))"
sort order of lists in multidimensional array in python,"test = sorted(test, key=lambda x: len(x) if type(x) == list else 1)"
python: how to convert a list of dictionaries' values into int/float from string?,"[dict([a, int(x)] for a, x in b.items()) for b in list]"
using multiple indicies for arrays in python,test_rec[(test_rec.age == 1) & (test_rec.sex == 1)]
how to remove positive infinity from numpy array...if it is already converted to a number?,"np.array([fnan, pinf, ninf]) < 0"
how to copy files to network path or drive using python,"shutil.copyfile('foo.txt', 'P:\\foo.txt')"
plot smooth line with pyplot,plt.show()
is there a way to set all values of a dictionary to zero?,{x: (0) for x in string.printable}
convert list of tuples to multiple lists in python,"map(list, zip(*[(1, 2), (3, 4), (5, 6)]))"
insert 0s into 2d array,"array([[-1, -1], [0, 0], [1, 1]])"
python: intersection indices numpy array,"numpy.argwhere(numpy.in1d(a, b))"
"python - how do i convert ""an os-level handle to an open file"" to a file object?",f.write('foo')
forcing elements in a numpy array to be within a specified range,"numpy.clip(x, 0, 255)"
how can i insert null data into mysql database with python?,"cursor.execute('INSERT INTO table (`column1`) VALUES (%s)', (value,))"
trim whitespace (including tabs) in `s` on the right side,s = s.rstrip()
how to initialize nested dictionaries in python,my_tree['a']['b']['c']['d']['e'] = 'whatever'
accessing model field attributes in django,MyModel._meta.get_field('foo').verbose_name
converting a string to list in python,"x = map(int, '0,1,2'.split(','))"
pandas get position of a given index in dataframe,base = df.index.get_loc(18)
group dictionary key values in python,mylist.sort(key=itemgetter('mc_no'))