intent
stringlengths 4
183
| snippet
stringlengths 2
1k
|
---|---|
adding a string to a list | b.append(c) |
pandas: best way to select all columns starting with x | df.columns.map(lambda x: x.startswith('foo')) |
how to clip polar plot in pylab/pyplot | plt.show() |
is it possible to tune parameters with grid search for custom kernels in scikit-learn? | model.fit(X_train, y_train) |
how to make a log log histogram in python | plt.show() |
how do you get the current text contents of a qcombobox? | text = str(combobox1.currentText()) |
how to make python format floats with certain amount of significant digits? | """{0:.6g}""".format(3.539) |
is there a way to suppress printing that is done within a unit test? | unittest.main() |
python: how to sort a list of dictionaries by several values? | sorted(A, key=itemgetter('name', 'age')) |
in python, how to display current time in readable format | time.strftime('%l:%M%p %z on %b %d, %Y') |
extract elements at indices (1, 2, 5) from a list `a` | [a[i] for i in (1, 2, 5)] |
for loop in python | list(range(1, 11)) |
how to extract tuple values in pandas dataframe for use of matplotlib? | pd.pivot(index=df['B1'], columns=df.index, values=df['B2']).plot() |
count the number of true values associated with key 'success' in dictionary `d` | sum(1 if d['success'] else 0 for d in s) |
how do i read the first line of a string? | my_string.split('\n', 1)[0] |
creating link to an url of flask app in jinja2 template | {{url_for('static', filename='[filenameofstaticfile]')}} |
how do i set permissions (attributes) on a file in a zip file using python's zipfile module? | zipfile.writestr(zipinfo, '') |
how to get a list of all integer points in an n-dimensional cube using python? | list(itertools.product(list(range(-x, y)), repeat=dim)) |
how do i modify a single character in a string, in python? | print(''.join(a)) |
convert binary string '01010101111' to integer | int('01010101111', 2) |
a list as a key for pyspark's reducebykey | rdd.map(lambda k_v: (set(k_v[0]), k_v[1])).groupByKey().collect() |
python - differences between elements of a list | [(j - i) for i, j in zip(t[:-1], t[1:])] |
rearrange tuple of tuples in python | tuple(zip(*t)) |
taking the results of a bash command and using it in python | os.system('top -d 30 | grep %d > test.txt' % pid) |
how to unpack a dictionary of list (of dictionaries!) and return as grouped tuples? | [('A', 1, 2), ('B', 3, 4)] |
how do i print the content of a .txt file in python? | f.close() |
remove a specific column in numpy | np.delete(a, [1, 3], axis=1) |
django-piston: how can i get app_label + model_name? | instance.__class__.__name__ |
histogram in matplotlib, time on x-axis | ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%y')) |
setting path to firefox binary on windows with selenium webdriver | driver = webdriver.Firefox() |
pandas remove column by index | df = df.ix[:, 0:2] |
rename index of a pandas dataframe | df.ix['c', '3'] |
django - filter queryset by charfield value length | MyModel.objects.filter(text__regex='^.{254}.*') |
get keys and items of dictionary `d` as a list | list(d.items()) |
how to get every element in a list of list of lists? | [a for c in Cards for b in c for a in b] |
extracting a region from an image using slicing in python, opencv | cv2.cvtColor(img, cv2.COLOR_BGR2RGB) |
how to save pandas pie plot to a file | fig.savefig('~/Desktop/myplot.pdf') |
convert a list of strings to either int or float | [(float(i) if '.' in i else int(i)) for i in s] |
remove a level from a pandas multiindex | MultiIndex.from_tuples(index_3levels.droplevel('l3').unique()) |
python: how do i use itertools? | list(itertools.product(list(range(2)), repeat=3)) |
is there a way to split a string by every nth separator in python? | print(['-'.join(words[i:i + span]) for i in range(0, len(words), span)]) |
pandas subtract a row from dataframe `df2` from dataframe `df` | pd.DataFrame(df.values - df2.values, columns=df.columns) |
how can i get dict from sqlite query? | cur.execute('select 1 as a') |
correct code to remove the vowels from a string in python | """""".join([l for l in c if l not in vowels]) |
compare two columns using pandas | df2 = df.astype(float) |
how to create matplotlib colormap that treats one value specially? | plt.show() |
get last day of the first month in year 2000 | (datetime.date(2000, 2, 1) - datetime.timedelta(days=1)) |
combining rows in pandas | df.reset_index().groupby('city_id').sum() |
pandas + dataframe - select by partial string | df[df['A'].str.contains('hello')] |
how to get full path of current file's directory in python? | os.path.dirname(os.path.abspath(__file__)) |
additional empty elements when splitting a string with re.split | re.findall('\\w+=".*?"', comp) |
how do you select choices in a form using python? | form['favorite_cheese'] = ['brie'] |
get a list of all the duplicate items in dataframe `df` using pandas | pd.concat(g for _, g in df.groupby('ID') if len(g) > 1) |
how to get files in a directory, including all subdirectories | print(os.path.join(dirpath, filename)) |
fastest way to count number of occurrences in a python list | Counter({'1': 6, '2': 4, '7': 3, '10': 2}) |
python : how to remove duplicate lists in a list of list? | b.sort(key=lambda x: a.index(x)) |
lambda in python | f = lambda x, y: x + y |
technique to remove common words(and their plural versions) from a string | 'all', 'just', 'being', 'over', 'both', 'through', 'yourselves', 'its', 'before', 'herself', 'had', 'should', 'to', 'only', 'under', 'ours', 'has', 'do', 'them', 'his', 'very', 'they', 'not', 'during', 'now', 'him', 'nor', 'did', 'this', 'she', 'each', 'further', 'where', 'few', 'because', 'doing', 'some', 'are', 'our', 'ourselves', 'out', 'what', 'for', 'while', 'does', 'above', 'between', 't', 'be', 'we', 'who', 'were', 'here', 'hers', 'by', 'on', 'about', 'of', 'against', 's', 'or', 'own', 'into', 'yourself', 'down', 'your', 'from', 'her', 'their', 'there', 'been', 'whom', 'too', 'themselves', 'was', 'until', 'more', 'himself', 'that', 'but', 'don', 'with', 'than', 'those', 'he', 'me', 'myself', 'these', 'up', 'will', 'below', 'can', 'theirs', 'my', 'and', 'then', 'is', 'am', 'it', 'an', 'as', 'itself', 'at', 'have', 'in', 'any', 'if', 'again', 'no', 'when', 'same', 'how', 'other', 'which', 'you', 'after', 'most', 'such', 'why', 'a', 'off', 'i', 'yours', 'so', 'the', 'having', 'once' |
heap sort: how to sort? | sort() |
how to write unicode strings into a file? | f.write(s) |
create a regular expression object with a pattern that will match nothing | re.compile('a^') |
how can i order a list of connections | [4, 6, 5, 3, 7, 8], [1, 2] |
plotting within a for loop, with 'hold on' effect in matplotlib? | plt.show() |
create new column `a_perc` in dataframe `df` with row values equal to the value in column `a` divided by the value in column `sum` | df['A_perc'] = df['A'] / df['sum'] |
creating an empty list | list() |
converting from a string to boolean in python? | str2bool('1') |
how to iterate over time periods in pandas | s.resample('3M', how='sum') |
appending to dict of lists adds value to every key | d = {k: [] for k in keys} |
python convert list to dictionary | l = [['a', 'b'], ['c', 'd'], ['e']] |
display maximum output data of columns in dataframe `pandas` that will fit into the screen | pandas.set_option('display.max_columns', None) |
insert element in python list after every nth element | ['a', 'b', 'c', 'x', 'd', 'e', 'f', 'x', 'g', 'h', 'i', 'x', 'j'] |
sorting a list of dictionary values by date in python | list.sort(key=lambda item: item['date'], reverse=True) |
python pandas - how to flatten a hierarchical index in columns | pd.DataFrame(df.to_records()) |
how to plot a wav file | plt.show() |
how to multiply all integers inside list | l = list(map(lambda x: 2 * x, l)) |
reverse a string `a_string` | def reversed_string(a_string):
return a_string[::(-1)] |
how to add a new div tag in an existing html file after a h1 tag using python | htmlFile = open('path to html file').read() |
split a list `l` into evenly sized chunks `n` | [l[i:i + n] for i in range(0, len(l), n)] |
get the first element of each tuple in a list `rows` | [x[0] for x in rows] |
what is the best way to sort list with custom sorting parameters in python? | li1.sort(key=lambda x: not x.startswith('b.')) |
drawing a huge graph with networkx and matplotlib | plt.savefig('graph.pdf') |
print 'here is your checkmark: ' plus unicode character u'\u2713' | print('here is your checkmark: ' + '\u2713') |
list manipulation in python | var1, var2, var3 = (ll + [None] * 3)[:3] |
php to python pack('h') | binascii.hexlify('Dummy String') |
how to use applymap, lambda and dataframe together to filter / modify dataframe in python? | df.fillna('o') |
specifying and saving a figure with exact size in pixels | plt.savefig('myfig.png', dpi=1000) |
convert column of date objects in pandas dataframe to strings | df['A'].apply(lambda x: x.strftime('%d%m%Y')) |
how to use ax.get_ylim() in matplotlib | ax.axhline(1, color='black', lw=2) |
how do you check if a string contains only numbers - python | str.isdigit() |
adding calculated column(s) to a dataframe in pandas | d['A'][1:] < d['C'][:-1] |
most pythonic way to print *at most* some number of decimal places | format(f, '.2f').rstrip('0').rstrip('.') |
indexerror when trying to read_table with pandas | len(['DATE', 'TIME', 'DLAT', 'DLON', 'SLAT', 'SLON', 'SHGT', 'HGT', 'N', 'E']) |
slicing a multidimensional list | [x[0] for x in listD[2]] |
get a list of booleans `z` that shows wether the corresponding items in list `x` and `y` are equal | z = [(i == j) for i, j in zip(x, y)] |
how to give a pandas/matplotlib bar graph custom colors | df.plot(kind='bar', stacked=True, color=my_colors) |
changing line properties in matplotlib pie chart | plt.rcParams['line.color'] = 'white' |
how to swap a group of column headings with their values in pandas | df = df.assign(a5=['Foo', 'Bar', 'Baz']) |
convert scientific notation to decimal - python | print('Number is: %.8f' % float(a[0] / a[1])) |
adding new key inside a new key and assigning value in python dictionary | dic['Test'].update({'class': {'section': 5}}) |
how to get every single permutation of a string? | print([''.join(p) for i in range(1, len(s) + 1) for p in permutations(s, i)]) |