text
stringlengths 4
1.08k
|
|---|
splitting integer in python?,[int(i) for i in str(number)]
|
moving x-axis to the top of a plot in matplotlib,plt.show()
|
python: one-liner to perform an operation upon elements in a 2d array (list of lists)?,[[int(j) for j in i] for i in a]
|
how to read windows environment variable value in python?,os.getenv('MyVar')
|
array in php and dict in python are the same?,"['Code', 'Reference', 'Type', 'Amount']"
|
"graphing multiple types of plots (line, scatter, bar etc) in the same window",plt.show()
|
how to replace the characters in strings with '#'s by using regex in python,"re.sub('\\w', '#', s)"
|
how can i create a random number that is cryptographically secure in python?,[cryptogen.random() for i in range(3)]
|
gzip a file in python,f.close()
|
django - how to sort objects alphabetically by first letter of name field,my_words = Wiki.objects.order_by('word')
|
select only specific columns 'a' and 'c' from a dataframe 'data' with multiindex columns,"data.loc[:, ([('one', 'a'), ('one', 'c'), ('two', 'a'), ('two', 'c')])]"
|
lambda returns lambda in python,"curry = lambda f, a: lambda x: f(a, x)"
|
"tkinter: set stringvar after <key> event, including the key pressed",root.mainloop()
|
how to convert beautifulsoup.resultset to string,"str.join('\n', map(str, result))"
|
how do i merge a list of dicts into a single dict?,dict(j for i in L for j in list(i.items()))
|
python sorting two lists,"[list(x) for x in zip(*sorted(zip(list1, list2), key=itemgetter(0)))]"
|
"slicing of a numpy 2d array, or how do i extract an mxm submatrix from an nxn array (n>m)?","x[1::2, 1::2]"
|
matplotlib plot with variable line width,plt.show()
|
sort a multidimensional list `a` by second and third column,"a.sort(key=operator.itemgetter(2, 3))"
|
how to select cells greater than a value in a multi-index pandas dataframe?,df[(df <= 2).all(axis=1)]
|
deleting rows with python in a csv file,writer.writerow(row)
|
python regular expression match all 5 digit numbers but none larger,"re.findall('\\D(\\d{5})\\D', s)"
|
python : how to append new elements in a list of list?,a = [[]] * 3
|
writing string 'text to write\n' to file `f`,f.write('text to write\n')
|
django self-referential foreign key,parentId = models.ForeignKey('self')
|
python check if all elements of a list are the same type,"all(isinstance(x, int) for x in lst)"
|
convert a 3d array `img` of dimensions 4x2x3 to a 2d array of dimensions 3x8,"img.transpose(2, 0, 1).reshape(3, -1)"
|
create block diagonal numpy array from a given numpy array,"np.kron(np.eye(n), a)"
|
find all occurrences of a substring in python,"[m.start() for m in re.finditer('(?=tt)', 'ttt')]"
|
convert list `lst` of tuples of floats to list `str_list` of tuples of strings of floats in scientific notation with eight decimal point precision,str_list = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in lst]
|
sort list of strings by integer suffix in python,"sorted(the_list, key=lambda x: int(x.split('_')[1]))"
|
how to get column by number in pandas?,"df.loc[:, ('b')]"
|
python: convert format string to regular expression,return ''.join(parts)
|
breaking a string in python if a number is 5 digit long or longer,"s = re.split('[0-9]{5,}', string)[0].strip()"
|
how can i get all the plain text from a website with scrapy?,xpath('//body//text()').re('(\\w+)')
|
"python, trying to get input from subprocess?",sys.stdout.flush()
|
flask sqlalchemy many-to-many insert data,db.session.commit()
|
python regex: match a string with only one instance of a character,"re.match('\\$[0-9]+[^\\$]*$', '$1 off delicious $5 ham.')"
|
sort a string in lexicographic order python,"sorted(sorted(s), key=str.upper)"
|
how to traverse a genericforeignkey in django?,Foo.objects.filter(Q(bar_x__name='bar x') | Q(bar_y__name='bar y'))
|
how do i create a csv file from database in python?,"writer.writerow(['mary', '3 main st', '704', 'yada'])"
|
how can i remove all instances of an element from a list in python?,"[x for x in a if x != [1, 1]]"
|
how to plot data against specific dates on the x-axis using matplotlib,plt.show()
|
how do you remove the column name row from a pandas dataframe?,"df.to_csv('filename.csv', header=False)"
|
get tuples of the corresponding elements from lists `lst` and `lst2`,"[(x, lst2[i]) for i, x in enumerate(lst)]"
|
how to access httprequest from urls.py in django,"return super(MyListView, self).dispatch(request, *args, **kwargs)"
|
latex citation in matplotlib legend,plt.savefig('fig.pgf')
|
how to configure logging to syslog in python?,my_logger.setLevel(logging.DEBUG)
|
rename multiple files in python,"os.rename(file, 'year_{}'.format(file.split('_')[1]))"
|
how to sort a tuple with lambda,"sorted(l, key=lambda i: hypot(i[0] - pt[0], i[1] - pt[1]))"
|
python pandas: replace values multiple columns matching multiple columns from another dataframe,"df_merged = pd.merge(df1, df2, how='inner', on=['chr', 'pos'])"
|
permutations with repetition in python,"sorted(itertools.product((0, 1), repeat=3), key=lambda x: sum(x))"
|
get the ascii value of a character u'a' as an int,ord('\u3042')
|
how can i compare a unicode type to a string in python?,'MyString' == 'MyString'
|
shorter way to write a python for loop,"d.update((b, a[:, (i)]) for i, b in enumerate(a))"
|
"get sum of values of columns 'y1961', 'y1962', 'y1963' after group by on columns ""country"" and ""item_code"" in dataframe `df`.","df.groupby(['Country', 'Item_Code'])[['Y1961', 'Y1962', 'Y1963']].sum()"
|
valueerror: setting an array element with a sequence,"numpy.array([1.2, 'abc'], dtype=object)"
|
python: regular expression search pattern for binary files (half a byte),pattern = re.compile('[@-O]')
|
easy way to convert a unicode list to a list containing python strings?,[x.encode('UTF8') for x in EmployeeList]
|
reshape pandas dataframe from rows to columns,df2.groupby('Name').apply(tgrp).unstack()
|
sort lists in the list `unsorted_list` by the element at index 3 of each list,unsorted_list.sort(key=lambda x: x[3])
|
how to print decimal values in python,gpb = float(eval(input()))
|
pandas: apply function to dataframe that can return multiple rows,"df.groupby('class', group_keys=False).apply(f)"
|
find the index of sub string 'a' in string `str`,str.find('a')
|
how to dynamically assign values to class properties in python?,"setattr(self, attr, group)"
|
how to extract a substring from inside a string in python?,"print(re.search('AAA(.*?)ZZZ', 'gfgfdAAA1234ZZZuijjk').group(1))"
|
removing pairs of elements from numpy arrays that are nan (or another value) in python,~np.isnan(a).any(1)
|
how to sort a scipy array with order attribute when it does not have the field names?,"np.argsort(y, order=('x', 'y'))"
|
combine two pandas dataframes with the same index,"pandas.concat([df1, df2], axis=1)"
|
sorting python list based on the length of the string,"print(sorted(xs, key=len))"
|
python - datetime of a specific timezone,print(datetime.datetime.now(EST()))
|
how do i create a new file on a remote host in fabric (python deployment tool)?,run('mv app.wsgi.template app.wsgi')
|
what does a for loop within a list do in python?,myList = [i for i in range(10)]
|
how to save xlsxwriter file in certain path?,workbook = xlsxwriter.Workbook('demo.xlsx')
|
python get most recent file in a directory with certain extension,"newest = max(glob.iglob('upload/*.log'), key=os.path.getctime)"
|
convert sets to frozensets as values of a dictionary,"d.update((k, frozenset(v)) for k, v in d.items())"
|
write xml file using lxml library in python,"str = etree.tostring(root, pretty_print=True)"
|
print list of unicode chars without escape characters,"print('[' + ','.join(""'"" + str(x) + ""'"" for x in s) + ']')"
|
execute shell script from python with variable,"subprocess.call(['test.sh', str(domid)])"
|
how do i assign a dictionary value to a variable in python?,"my_dictionary = {'foo': 10, 'bar': 20}"
|
copying one file's contents to another in python,"shutil.copy('file.txt', 'file2.txt')"
|
how to read a file in other directory in python,"x_file = open(os.path.join(direct, '5_1.txt'), 'r')"
|
print first key value in an ordered counter,"next((key, value) for key, value in list(c.items()) if value > 1)"
|
downloading file to specified location with selenium and python,"driver.find_element_by_xpath(""//a[contains(text(), 'DEV.tgz')]"").click()"
|
reindex sublevel of pandas dataframe multiindex,df['Measurements'] = df.reset_index().groupby('Trial').cumcount()
|
how to query an hdf store using pandas/python,"pd.read_hdf('test.h5', 'df', where='A=[""foo"",""bar""] & B=1')"
|
splitting a string into words and punctuation,"re.findall(""[\\w']+|[.,!?;]"", ""Hello, I'm a string!"")"
|
control a print format when printing a list in python,"print('[%s]' % ', '.join('%.3f' % val for val in list))"
|
make a flat list from list of lists `sublist`,[item for sublist in l for item in sublist]
|
apply functions `mean` and `std` to each column in dataframe `df`,"df.groupby(lambda idx: 0).agg(['mean', 'std'])"
|
how to create a ssh tunnel using python and paramiko?,ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
pandas: how to drop self correlation from correlation matrix,corrs = df.corr()
|
how to add column to numpy array,"b = numpy.append(a, numpy.zeros([len(a), 1]), 1)"
|
how to get the index of a maximum element in a numpy array along one axis,a.argmax(axis=0)
|
format a date object `str_data` into iso fomrat,"datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()"
|
insert 77 to index 2 of list `x`,"x.insert(2, 77)"
|
reading data into numpy array from text file,"data = numpy.loadtxt(yourFileName, skiprows=n)"
|
norm along row in pandas,"df.apply(lambda x: np.sqrt(x.dot(x)), axis=1)"
|
adding element to a dictionary in python?,"print((name, 'has been sorted into', ransport))"
|
"terminating a python script with error message ""some error message""",sys.exit('some error message')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.