text
stringlengths
4
1.08k
how to convert a numpy 2d array with object dtype to a regular 2d array of floats,"np.array(arr[:, (1)], dtype=[('', np.float)] * 3).view(np.float).reshape(-1, 3)"
hash map in python,"streetno = dict({'1': 'Sachine Tendulkar', '2': 'Dravid'})"
drop all duplicate rows in python pandas,"df.drop_duplicates(subset=['A', 'C'], keep=False)"
multiple inputs with mrjob,sdb.close()
how can i implement multiple url parameters in a tornado route?,tornado.ioloop.IOLoop.instance().start()
"create a dictionary from string `e` separated by `-` and `,`","dict((k, int(v)) for k, v in (e.split(' - ') for e in s.split(',')))"
"in python's argparse module, how can i disable printing subcommand choices between curly brackets?",parser.parse_args()
most efficient way to split strings in python,"re.split('\\||<>', input)"
using extensions with selenium (python),driver.quit()
constructing a python set from a numpy matrix,y = numpy.unique(x)
find rows with non zero values in a subset of columns in pandas dataframe,"df.loc[(df.loc[:, (df.dtypes != object)] != 0).any(1)]"
pandas - replacing column values,"data['sex'].replace([0, 1], ['Female', 'Male'], inplace=True)"
create django admin intermediate page,"admin.site.register(Person, PersonAdmin)"
create new list `result` by splitting each item in list `words`,"result = [item for word in words for item in word.split(',')]"
how to sort list of strings by count of a certain character?,l.sort(key=lambda x: x.count('+'))
how can i split a string into tokens?,"print([i for i in re.split('(\\d+|\\W+)', 'x+13.5*10x-4e1') if i])"
getting the circumcentres from a delaunay triangulation generated using matplotlib,plt.gca().set_aspect('equal')
comparing values in a python dict of lists,"{k: [lookup[n] for n in v] for k, v in list(my_dict.items())}"
how do i sort a list of strings in python?,"sorted(mylist, key=cmp_to_key(locale.strcoll))"
how to call an element in an numpy array?,"print(arr[1, 1])"
python pexpect sendcontrol key characters,id.sendline('')
how to invert colors of an image in pygame?,pygame.display.flip()
python pandas datetime.time - datetime.time,df.applymap(time.isoformat).apply(pd.to_timedelta)
accessing orientdb from python,python - -version
python - sort a list of dics by value of dict`s dict value,"sorted(persons, key=lambda x: x['passport']['birth_info']['date'])"
python - getting list of numbers n to 0,"list(range(N, -1, -1)) is better"
sorting a list of dicts by dict values,"sorted(a, key=dict.values, reverse=True)"
how to create a manhattan plot with matplotlib in python?,ax.set_xlabel('Chromosome')
plotting histograms from grouped data in a pandas dataframe,"df.reset_index().pivot('index', 'Letter', 'N').hist()"
how to convert a string to a function in python?,raise ValueError('invalid input')
sort query set by number of characters in a field `length` in django model `mymodel`,MyModel.objects.extra(select={'length': 'Length(name)'}).order_by('length')
convert datetime.date `dt` to utc timestamp,"timestamp = (dt - datetime(1970, 1, 1)).total_seconds()"
matplotlib colorbar formatting,"plt.rcParams['text.latex.preamble'].append('\\mathchardef\\mhyphen=""2D')"
how can i call vim from python?,"call(['vim', 'hello.txt'])"
how to detect a sign change for elements in a numpy array,"array([0, 0, 1, 0, 0, 1, 0])"
change first line of a file in python,"shutil.copyfileobj(from_file, to_file)"
using a variable in xpath in python selenium,"driver.find_element_by_xpath(""//option[@value='"" + state + ""']"").click()"
python: lambda function in list comprehensions,[(lambda x: x * x)(x) for x in range(10)]
how do you make the linewidth of a single line change as a function of x in matplotlib?,plt.show()
sort list `mylist` in alphabetical order,mylist.sort(key=str.lower)
updating the x-axis values using matplotlib animation,plt.show()
change string list to list,"ast.literal_eval('[1,2,3]')"
capturing emoticons using regular expression in python,"re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)', s)"
multiindex from array in pandas with non unique data,"group_position(df['Z'], df['A'])"
writing a list of sentences to a single column in csv with python,writer.writerows([val])
get last three digits of an integer,int(str(x)[-3:])
python list comprehension - simple,[(x * 2 if x % 2 == 0 else x) for x in a_list]
how to get process's grandparent id,os.popen('ps -p %d -oppid=' % os.getppid()).read().strip()
cannot import sqlite with python 2.6,sys.path.append('/your/dir/here')
how to add the second line of labels in matplotlib plot,plt.show()
how can i compare two lists in python and return matches,"[i for i, j in zip(a, b) if i == j]"
how to run a python unit test with the atom editor?,unittest.main()
how can i break up this long line in python?,"""""""This is the first line of my text which will be joined to a second."""""""
how do you split a list into evenly sized chunks?,"[l[i:i + n] for i in range(0, len(l), n)]"
how to embed a python interpreter in a pyqt widget,app.exec_()
getting the first item item in a many-to-many relation in django,Group.objects.get(id=1).members.filter(is_main_user=True)[0]
merge the elements in a list `lst` sequentially,"[''.join(seq) for seq in zip(lst, lst[1:])]"
when and how to use python's rlock,self.changeB()
technique to remove common words(and their plural versions) from a string,"['long', 'string', 'text']"
python: sum values in a dictionary based on condition,sum(v for v in list(d.values()) if v > 0)
how to write a gstreamer plug-in in cython,initgstreamer()
coordinates of box of annotations in matplotlib,bbox_data = ax.transData.inverted().transform(bbox)
combine two pandas dataframes with the same index,"pd.merge(df1, df2, left_index=True, right_index=True, how='outer')"
data cleanup that requires iterating over pandas.dataframe 3 rows at a time,"data = pd.DataFrame({'x': [1, 2, 3, 0, 0, 2, 3, 0, 4, 2, 0, 0, 0, 1]})"
get required fields from document in mongoengine?,"[k for k, v in User._fields.items() if v.required]"
how to join list in python but make the last separator different?,"','.join(my_list[:-1]) + '&' + my_list[-1]"
extracting words between delimiters [] in python,"re.findall('\\[([^\\]]*)\\]', str)"
numpy repeat for 2d array,"res = np.zeros((arr.shape[0], m), arr.dtype)"
how do i download a file using urllib.request in python 3?,f.write(g.read())
prettier default plot colors in matplotlib,plt.style.use('seaborn-dark-palette')
python: run a process and kill it if it doesn't end within one hour,time.sleep(interval)
regex matching 5-digit substrings not enclosed with digits,"re.findall('\\b\\d{5}\\b', 'Helpdesk-Agenten (m/w) Kennziffer: 12966')"
rotating a two-dimensional array in python,"original = [[1, 2], [3, 4]]"
print multiple arguments 'name' and 'score'.,"print('Total score for {} is {}'.format(name, score))"
pandas changing cell values based on another cell,"df.fillna(method='ffill', inplace=True)"
populating a sqlite3 database from a .txt file with python,c.execute('SELECT * FROM politicians').fetchall()
how to set python version by default in freebsd?,PYTHON_DEFAULT_VERSION = 'python3.2'
how to determine pid of process started via os.system,proc.terminate()
remove duplicate dict in list in python,"[{'a': 123, 'b': 1234}, {'a': 3222, 'b': 1234}]"
comparing values in two lists in python,[(x[i] == y[i]) for i in range(len(x))]
extract only alphabetic characters from a string `your string`,""""""" """""".join(re.split('[^a-zA-Z]*', 'your string'))"
get sql headers from numpy array in python,"[('a', '|O4'), ('b', '|O4'), ('c', '|O4')]"
element-wise operations of matrix in python,"[[(i * j) for i, j in zip(*row)] for row in zip(matrix1, matrix2)]"
regex match and replace multiple patterns,"print('\n'.join([x.rsplit(None, 1)[0] for x in target.strip().split('\n')]))"
how to add title to subplots in matplotlib?,ax.set_title('Title for second plot')
python/django: getting random articles from huge table,MyModel.objects.order_by('?')[:10]
how do i slice a string every 3 indices?,"return [str[start:start + num] for start in range(0, len(str), num)]"
filling continuous pandas dataframe from sparse dataframe,"ts.reindex(pd.date_range(min(date_index), max(date_index)))"
finding the index of an item given a list containing it in python,"['foo', 'bar', 'baz'].index('bar')"
duplicate items in legend in matplotlib?,"ax.plot(x, y, label='Representatives' if i == 0 else '')"
python: elegant way of creating a list of tuples?,"[(x + tuple(y)) for x, y in zip(zip(a, b), c)]"
get a sum of 4d array `m`,M.sum(axis=0).sum(axis=0)
python heatmap from 3d coordinates,plt.show()
python logging typeerror,logging.info('test')
how to get values from a map and set them into a numpy matrix row?,"[map(dict.get, list(range(1, 6))) for _ in range(10)]"
"python unicode string stored as '\u84b8\u6c7d\u5730' in file, how to convert it back to unicode?",print('\\u84b8\\u6c7d\\u5730'.decode('unicode-escape'))
how to strip all whitespace from string,"s.replace(' ', '')"
check if 2 arrays have at least one element in common?,any(x in set(b) for x in a)
character reading from file in python,f.close()
how to repeat individual characters in strings in python,""""""""""""".join(map(lambda x: x * 7, 'map'))"