text
stringlengths
4
1.08k
"numpy array set ones between two values, fast","array([0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0])"
python: simplest way to get list of values from dict?,list(d.values())
"python, running command line tools in parallel","subprocess.call('start command -flags arguments', shell=True)"
how to create similarity matrix in numpy python?,np.corrcoef(x)
selenium webdriver: how do i find all of an element's attributes?,driver.get('https://stackoverflow.com')
how does the axis parameter from numpy work?,"e.shape == (3, 2, 2)"
how to add a line parallel to y axis in matplotlib?,plt.show()
how to redirect 'print' output to a file using python?,f.close()
python regex alternative for join,"re.sub('(?<=\\w)(?=\\w)', '-', str)"
creating sets of tuples in python,"mySet = set((x, y) for x in range(1, 51) for y in range(1, 51))"
convert date object `dateobject` into a datetime object,"datetime.datetime.combine(dateobject, datetime.time())"
resizing and stretching a numpy array,"np.repeat(a, [2, 2, 1], axis=0)"
find href value that has string 'follow?page' inside it,"print(soup.find('a', href=re.compile('.*follow\\?page.*')))"
convert string to hex in python,"int('0x77', 16)"
get count of rows in each series grouped by column 'col5' and column 'col2' of dataframe `df`,"df.groupby(['col5', 'col2']).size().groupby(level=1).max()"
convert unicode with utf-8 string as content to str,print(content.encode('latin1').decode('utf8'))
unique values within pandas group of groups,"df.groupby(['country', 'gender'])['industry'].unique()"
pandas dataframe: how to parse integers into string of 0s and 1s?,df.column_A.apply(to_binary)
python: extract numbers from a string,"re.findall('\\b\\d+\\b', ""he33llo 42 I'm a 32 string 30"")"
dot notation string manipulation,s.split('.')[-1]
convert string to md5,hashlib.md5('fred'.encode('utf')).hexdigest()
how to calculate percentage of sparsity for a numpy array/matrix?,np.isnan(a).sum()
syntax for creating a dictionary into another dictionary in python,"d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}"
pandas: replacing column values in dataframe,"w['female'] = w['female'].map({'female': 1, 'male': 0})"
sorting a list of tuples `list_of_tuples` where each tuple is reversed,"sorted(list_of_tuples, key=lambda tup: tup[::-1])"
duplicate items in legend in matplotlib?,"handles, labels = ax.get_legend_handles_labels()"
sort a list of lists `l` by index 2 of the inner list,l.sort(key=(lambda x: x[2]))
python pandas - how to filter multiple columns by one value,"df[(df.iloc[:, -12:] == -1).any(axis=1)]"
get all indexes of boolean numpy array where boolean value `mask` is true,numpy.where(mask)
find dictionary keys with duplicate values,"[key for key, values in list(rev_multidict.items()) if len(values) > 1]"
"sort a structured numpy array 'df' on multiple columns 'year', 'month' and 'day'.","df.sort(['year', 'month', 'day'])"
"split string `text` by the occurrences of regex pattern '(?<=\\?|!|\\.)\\s{0,2}(?=[a-z]|$)'","re.split('(?<=\\?|!|\\.)\\s{0,2}(?=[A-Z]|$)', text)"
in python how do i convert a single digit number into a double digits string?,print('{0}'.format('5'.zfill(2)))
get current utc time,datetime.utcnow()
how to remove an element from a set?,"[set(['a', '']), set(['', 'b'])]"
most pythonic way to convert a list of tuples,[list(t) for t in zip(*list_of_tuples)]
python - locating the position of a regex match in a string?,"re.search('is', String).start()"
efficient loop over numpy array,np.sum(a)
"to read line from file in python without getting ""\n"" appended at the end",line = line.rstrip('\n')
generate a list from a pandas dataframe `df` with the column name and column values,df.values.tolist()
get output from process `p1`,p1.communicate()[0]
check the status code of url `url`,"r = requests.head(url)
return (r.status_code == 200)"
check if list item contains items from another list,[i for e in bad for i in my_list if e in i]
check whether file `file_path` exists,os.path.exists(file_path)
how to perform a 'one-liner' assignment on all elements of a list of lists in python,"[[1, -2], [3, -2]]"
how to check if a character is upper-case in python?,print(all(word[0].isupper() for word in words))
sort a list based on dictionary values in python?,"sorted(trial_list, key=lambda x: trial_dict[x])"
check python version,sys.version
concurrency control in django model,"super(MyModel, self).save(*args, **kwargs)"
python: get last monday of july 2010,"datetime.datetime(2010, 7, 26, 0, 0)"
finding the indices of matching elements in list in python,"return [i for i, x in enumerate(lst) if x < a or x > b]"
how to convert est/edt to gmt?,dt.datetime.utcfromtimestamp(time.mktime(date.timetuple()))
python regex get string between two substrings,"re.findall(""api\\('(.*?)'"", ""api('randomkey123xyz987', 'key', 'text')"")"
"set labels `[1, 2, 3, 4, 5]` on axis x in plot `plt`","plt.xticks([1, 2, 3, 4, 5])"
how to decode a 'url-encoded' string in python,urllib.parse.unquote(urllib.parse.unquote(some_string))
"in python, how do i cast a class object to a dict",dict(my_object)
how can i run an external command asynchronously from python?,p.terminate()
django: detecting changes of a set of fields when a model is saved,"super(MyModel, self).save(*args, **kwargs)"
how to get multiple conditional operations after a pandas groupby?,return df.groupby('A').apply(my_func)
matplotlib axis label format,"ax1.xaxis.get_major_formatter().set_powerlimits((0, 1))"
change figure size to 3 by 4 in matplotlib,"plt.figure(figsize=(3, 4))"
add 1 hour and 2 minutes to time object `t`,"dt = datetime.datetime.combine(datetime.date.today(), t)"
disable dsusp in python,time.sleep(2)
string formatting options: pros and cons,"""""""My name is {surname}, {name} {surname}. I am {age}."""""".format(**locals())"
add field names as headers in csv constructor `writer`,writer.writeheader()
converting json date string to python datetime,"datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')"
get data of column 'a' and column 'b' in dataframe `df` where column 'a' is equal to 'foo',"df.loc[gb.groups['foo'], ('A', 'B')]"
how can i plot hysteresis in matplotlib?,"ax.plot_trisurf(XS, YS, ZS)"
fetch smilies matching regex pattern '(?::|;|=)(?:-)?(?:\\)|\\(|d|p)' in string `s`,"re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)', s)"
numpy - set values in structured array based on other values in structured array,"dtype([('x', '<i8'), ('y', 'S')])"
change legend font size with matplotlib.pyplot to 6,"plot.legend(loc=2, prop={'size': 6})"
python pandas - date column to column index,"df.reset_index(level=0, inplace=True)"
parsing a tweet to extract hashtags into an array in python,"re.findall('#(\\w+)', s)"
array indexing in numpy,"a[([i for i in range(a.shape[0]) if i != 1]), :, :]"
how to get the symbolic path instead of real path?,os.path.abspath('../link/file')
how to set xlim and ylim for a subplot in matplotlib,"ax2.set_ylim([0, 5])"
django rest framework: how to properly use the hyperlinkedmodelserializer url field in unit tests,"url = reverse('my_api.actor_resource', args={'id': actor.id})"
transforming the string representation of a dictionary into a real dictionary,"dict(map(int, x.split(':')) for x in s.split(','))"
solve for the least squares' solution of matrices `a` and `b`,"np.linalg.solve(np.dot(a.T, a), np.dot(a.T, b))"
"dynamically import a method in a file, from a string",importlib.import_module('abc.def.ghi.jkl.myfile.mymethod')
how can i do multiple substitutions using regex in python?,"re.sub('(.)', '\\1\\1', text.read())"
convert a 1d `a` array to a 2d array `b`,"B = np.reshape(A, (-1, 2))"
how to get environment from a subprocess in python,"subprocess.Popen('proc2', env=env)"
pandas: how to select by partial label in index,ds.loc['wiki':'wikj']
how do i convert datetime to date (in python)?,datetime.datetime.now().date()
terminate a python script from another python script,"os.kill(5383, signal.SIGKILL)"
replace part of a string in python?,"stuff.replace(' and ', '/')"
fastest way to remove all multiple occurrence items from a list?,"[(1, 3), (3, 4)]"
how to convert nested list of lists into a list of tuples in python 3.3?,[tuple(l) for l in nested_lst]
'pipelinedrdd' object has no attribute 'todf' in pyspark,rdd.toDF().show()
is there a way to use ribbon toolbars in tkinter?,root.mainloop()
convert unicode string to byte string,'\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0'.encode('latin-1')
convert a string `s` to its base-10 representation,"int(s.encode('hex'), 16)"
match regex pattern '\\$[0-9]+[^\\$]*$' on string '$1 off delicious $5 ham.',"re.match('\\$[0-9]+[^\\$]*$', '$1 off delicious $5 ham.')"
how to convert decimal string in python to a number?,Decimal('1.03')
python/matplotlib - is there a way to make a discontinuous axis?,ax.spines['right'].set_visible(False)
how do i save excel sheet as html in python?,xl.Workbooks.Open('C:\\Foo\\Bar.xlsx')
reverse sort dictionary `d` based on its values,"sorted(list(d.items()), key=lambda k_v: k_v[1], reverse=True)"
python pandas dataframe groupby size based on condition,"df.groupby(['id', 'date1']).apply(lambda x: (x['date1'] == x['date2']).sum())"