text stringlengths 4 1.08k |
|---|
python getting a list of value from list of dict,[x['value'] for x in list_of_dicts] |
removing pairs of elements from numpy arrays that are nan (or another value) in python,a[~(a == 5).any(1)] |
python tkinter text widget with auto & custom scroll,root.mainloop() |
throw an error window in python in windows,"ctypes.windll.user32.MessageBoxW(0, 'Error', 'Error', 0)" |
pandas reset index on series to remove multiindex,"s.reset_index().drop(1, axis=1)" |
pandas groupby: count the number of occurences within a time range for each group,df['cumsum'] = df['WIN1'].cumsum() |
summing elements in a list,"sum(map(int, l))" |
sorting a list of tuples by the addition of second and third element of the tuple,"sorted(a, key=lambda x: (sum(x[1:3]), x[0]))" |
"find where f(x) changes in a list, with bisection (in python)","binary_f(lambda v: v >= '4.2', ['1.0', '1.14', '2.3', '3.1', '4'])" |
"string split on new line, tab and some number of spaces",[s.strip() for s in data_string.splitlines()] |
"split string ""a;bcd,ef g"" on delimiters ';' and ','","""""""a;bcd,ef g"""""".replace(';', ' ').replace(',', ' ').split()" |
delete duplicate rows in django db,Some_Model.objects.filter(id__in=ids_list).delete() |
how can i parse json in google app engine?,obj = json.loads(string) |
redirect to a url which contains a 'variable part' in flask (python),"return redirect(url_for('dashboard', username='foo'))" |
valueerror: setting an array element with a sequence,"numpy.array([[1, 2], [2, 3, 4]])" |
python converting a tuple (of strings) of unknown length into a list of strings,"['text', 'othertext', 'moretext', 'yetmoretext']" |
pandas conditional creation of a series/dataframe column,"df['color'] = np.where(df['Set'] == 'Z', 'green', 'red')" |
how to scrape a website that requires login first with python,br.select_form(nr=1) |
removing data between double squiggly brackets with nested sub brackets in python,"re.sub('\\{\\{.*\\}\\} ', '', s)" |
selecting a specific row and column within pandas data array,df['StartDate'][2] |
capturing group with findall?,"re.findall('abc(de)fg(123)', 'abcdefg123 and again abcdefg123')" |
check if a list has one or more strings that match a regex,"[re.search('\\d{4}', s) for s in lst]" |
python add elements to lists within list if missing,"[[2, 3, 0], [1, 2, 3], [1, 0, 0]]" |
jinja parse datetime object `car.date_of_manufacture` to use format pattern `datetime`,{{car.date_of_manufacture | datetime}} |
how to print next year from current year in python,print(date.today().year + 1) |
prevent anti-aliasing for imshow in matplotlib,"imshow(array, interpolation='nearest')" |
how can i store binary values with trailing nulls in a numpy array?,"np.array([('abc\x00\x00',), ('de\x00\x00\x00',)], dtype='O')" |
moving x-axis to the top of a plot in matplotlib,"ax.tick_params(labelbottom='off', labeltop='on')" |
wildcard matching a string in python regex search,pattern = '6 of(.*)fans' |
select records of dataframe `df` where the sum of column 'x' for each value in column 'user' is 0,df.groupby('User')['X'].filter(lambda x: x.sum() == 0) |
how to convert a tuple to a string in python?,emaillist = '\n'.join([item[0] for item in queryresult]) |
dynamic method in python,"x, y = map(os.getpid, ('process1', 'process2'))" |
python: return the index of the first element of a list which makes a passed function true,"next((i for i, v in enumerate(l) if is_odd(v)))" |
numpy: get index of smallest value based on conditions,"np.argwhere(a[:, (1)] == -1)[np.argmin(a[a[:, (1)] == -1, 0])]" |
open document with default application in python,os.system('open ' + filename) |
python convert string literal to float,"total = sum(map(float, s.split(',')))" |
os.getcwd() for a different drive in windows,os.chdir('l:\\') |
interleave list with fixed element,"[elem for x in list for elem in (x, 0)][:-1]" |
python: how to change (last) element of tuple?,"b = a[:-1] + (a[-1] * 2,)" |
python: get a dict from a list based on something inside the dict,"new_dict = dict((item['id'], item) for item in initial_list)" |
django - filter queryset by charfield value length,MyModel.objects.extra(where=['CHAR_LENGTH(text) > 254']) |
creating a custom spark rdd in python,assert rdd.squares().collect() == rdd.map(lambda x: x * x).collect() |
is there a generator version of `string.split()` in python?,"list(split_iter(""A programmer's RegEx test.""))" |
how to sort/ group a pandas data frame by class label or any specific column,df.sort_index() |
how to efficiently rearrange pandas data as follows?,"(df[cols] > 0).apply(lambda x: ' '.join(x[x].index), axis=1)" |
sorting a dictionary by a split key,"sorted(list(d.items()), key=lambda v: int(v[0].split('-')[0]))" |
how to use regex with optional characters in python?,"print(re.match('(\\d+(\\.\\d+)?)', '3434.35353').group(1))" |
programmatically sync the db in django,"management.call_command('syncdb', interactive=False)" |
how to customize the auth.user admin page in django crud?,"admin.site.register(User, UserAdmin)" |
what is a quick way to delete all elements from a list that do not satisfy a constraint?,[x for x in lst if fn(x) != 0] |
"in python, how to convert list of float numbers to string with certain format?",p = [tuple('{0:.2f}'.format(c) for c in b) for b in a] |
how do i sort a list of strings in python?,list.sort() |
subtract elements of list `list1` from elements of list `list2`,"[(x1 - x2) for x1, x2 in zip(List1, List2)]" |
how to make a window jump to the front?,root.lift() |
convert hex to binary,"bin(int('abc123efff', 16))[2:]" |
django middleware - how to edit the html of a django response object?,"response.content = response.content.replace('BAD', 'GOOD')" |
how to include a quote in a raw python string?,"""""""what""ev'er""""""" |
"how do i generate a random string (of length x, a-z only) in python?",""""""""""""".join(random.choice(string.lowercase) for x in range(X))" |
plot logarithmic axes with matplotlib,ax.set_yscale('log') |
python split function -avoids last empy space,my_str.rstrip(';').split(';') |
replace non-ascii characters in string `text` with a single space,"re.sub('[^\\x00-\\x7F]+', ' ', text)" |
scatterplot with xerr and yerr with matplotlib,plt.show() |
python: comparing two strings,"difflib.SequenceMatcher(None, a, b).ratio()" |
python split string based on regular expression,"re.split('\\s+', str1)" |
how can i place a table on a plot in matplotlib?,plt.show() |
remove all occurrences of several chars from a string,"re.sub('[ -.:]', '', ""'::2012-05-14 18:10:20.856000::'"")" |
how to format pubdate with python,"mytime.strftime('%a, %d %b %Y %H:%M:%S %z')" |
get a filtered list of files in a directory,"files = [f for f in os.listdir('.') if re.match('[0-9]+.*\\.jpg', f)]" |
proper way to use **kwargs in python,"self.val2 = kwargs.get('val2', 'default value')" |
"how to store data frame using pandas, python",df = pd.read_pickle(file_name) |
print to the same line and not a new line in python,sys.stdout.flush() |
python - numpy - deleting multiple rows and columns from an array,"np.count_nonzero(a[np.ix_([0, 3], [0, 3])])" |
sort dictionary of dictionaries by value,"sorted(list(statuses.items()), key=lambda x: getitem(x[1], 'position'))" |
"how to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/a '])" |
create a pandas dataframe from deeply nested json,res.drop_duplicates() |
iterate over a dictionary `d` in sorted order,"for (key, value) in sorted(d.items()): |
pass" |
python list-comprehension for words that do not consist solely of digits,[word for word in words if any(not char.isdigit() for char in word)] |
how to recognize whether a script is running on a tty?,sys.stdout.isatty() |
creating a socket restricted to localhost connections only,"socket.bind(('127.0.0.1', 80))" |
create pandas data frame `df` from txt file `filename.txt` with column `region name` and separator `;`,"df = pd.read_csv('filename.txt', sep=';', names=['Region Name'])" |
join list of lists in python,[j for i in x for j in i] |
move the last item in list `a` to the beginning,a = a[-1:] + a[:-1] |
how to write a unicode csv in python 2.7,self.writer.writerow([str(s).encode('utf-8') for s in row]) |
list the contents of a directory '/home/username/www/',os.listdir('/home/username/www/') |
create a file 'filename' with each tuple in the list `mylist` written to a line,"open('filename', 'w').write('\n'.join('%s %s' % x for x in mylist))" |
python : matplotlib annotate line break (with and without latex),plt.show() |
matplotlib subplot y-axis scale overlaps with plot above,plt.show() |
save matplotlib file to a directory,fig.savefig('Sub Directory/graph.png') |
python: converting from binary to string,"struct.pack('>I', 1633837924)" |
how to set utc offset for datetime?,dateutil.parser.parse('2013/09/11 00:17 +0900') |
python regex to remove all words which contains number,"re.sub('\\w*\\d\\w*', '', words).strip()" |
flask instanciation app = flask(),app = Flask(__name__) |
how do i create an opencv image from a pil image?,"cv.ShowImage('pil2ipl', cv_img)" |
combine two sequences into a dictionary,"dict(zip(keys, values))" |
delete column in pandas based on condition,"df = df.loc[:, ((df != 0).any(axis=0))]" |
"selecting element ""//li/label/input"" followed by text ""polishpottery"" with selenium webdriver `driver`","driver.find_element_by_xpath(""//li/label/input[contains(..,'polishpottery')]"")" |
iterating key and items over dictionary `d`,"for (letter, number) in list(d.items()): |
pass" |
creating a list by iterating over a dictionary,"['{}_{}'.format(k, v) for k, v in list(d.items())]" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.