text
stringlengths 4
1.08k
|
|---|
how to split text without spaces into list of words?,"print(find_words('tableprechaun', words=set(['tab', 'table', 'leprechaun'])))"
|
python list comprehension to produce two values in one iteration,"[((i // 2) ** 2 if i % 2 else i // 2) for i in range(2, 20)]"
|
how to alphabetically sort array of dictionaries on single key?,"sorted(my_list, key=operator.itemgetter('name', 'age', 'other_thing'))"
|
how can i splice a string?,t = s[:1] + 'whatever' + s[6:]
|
how to get python interactive console in current namespace?,code.interact(local=locals())
|
get the cartesian product of a series of lists?,"[(a, b, c) for a in [1, 2, 3] for b in ['a', 'b'] for c in [4, 5]]"
|
sunflower scatter plot using matplotlib,plt.title('sunflower plot')
|
python json encoding,"{'apple': 'cat', 'banana': 'dog'}"
|
remove non-ascii characters from a string using python / django,"""""""1 < 4 & 4 > 1"""""""
|
python lists with scandinavic letters,"['Hello', 'w\xc3\xb6rld']"
|
finding the index of a string in a tuple,tup.index('string2')
|
block mean of numpy 2d array,"np.mean(a, axis=1)"
|
produce a string that is suitable as unicode literal from string 'm\\n{ampersand}m\\n{apostrophe}s','M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.encode().decode('unicode-escape')
|
how to perform element-wise multiplication of two lists in python?,"[(a * b) for a, b in zip(lista, listb)]"
|
sorting a list of dictionaries based on the order of values of another list,listTwo.sort(key=lambda x: order_dict[x['eyecolor']])
|
how can i get part of regex match as a variable in python?,p.match('lalalaI want this partlalala').group(1)
|
pythonic way to create a long multi-line string,s = 'this is a verylong string toofor sure ...'
|
sorting list 'x' based on values from another list 'y',"[x for y, x in sorted(zip(Y, X))]"
|
pandas: counting unique values in a dataframe,pd.value_counts(d.values.ravel())
|
extract all the values of a specific key named 'values' from a list of dictionaries,results = [item['value'] for item in test_data]
|
applying functions to groups in pandas dataframe,df.groupby('type').apply(lambda x: np.mean(np.log2(x['v'])))
|
python list of tuples to list of int,y = [i[0] for i in x]
|
how to extend pywavelets to work with n-dimensional data?,"pywt.dwtn([[1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 7, 8], [7, 8, 9, 10]], 'db1')"
|
format strings and named arguments in python,"""""""{0} {1}"""""".format(10, 20)"
|
how to connect to remote server with paramiko without a password?,"ssh.connect(IP[0], username=user[0], pkey=mykey)"
|
unpack elements of list `i` as arguments into function `foo`,foo(*i)
|
"matplotlib - labelling points (x,y) on a line with a value z",plt.show()
|
replace all characters in a string with asterisks,word = ['*'] * len(word)
|
flask : how to architect the project with multiple apps?,app.run(debug=True)
|
get the value with the maximum length in each column in array `foo`,[max(len(str(x)) for x in line) for line in zip(*foo)]
|
python: logging typeerror: not all arguments converted during string formatting,"logging.info('date=%s', date)"
|
python - crontab to run a script,main()
|
limit the number of sentences in a string,""""""" """""".join(re.split('(?<=[.?!])\\s+', phrase, 2)[:-1])"
|
convert a unicode 'andr\xc3\xa9' to a string,""""""""""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9').decode('utf8')"
|
how to remove lines in a matplotlib plot,ax.lines.pop(0)
|
fastest way to find the magnitude (length) squared of a vector field,"np.einsum('...j,...j->...', vf, vf)"
|
how would i go about playing an alarm sound in python?,os.system('beep')
|
python: sorting items in a dictionary by a part of a key?,"lambda item: (item[0].rsplit(None, 1)[0], item[1])"
|
is it possible to plot timelines with matplotlib?,ax.spines['left'].set_visible(False)
|
controlling alpha value on 3d scatter plot using python and matplotlib,plt.show()
|
pandas dataframe to list of dictionaries,df.to_dict('index')
|
how to create a density plot in matplotlib?,plt.show()
|
sort a list of tuples `a` by the sum of second and third element of each tuple,"sorted(a, key=lambda x: (sum(x[1:3]), x[0]), reverse=True)"
|
sort a list of tuples alphabetically and by value,"sorted(temp, key=itemgetter(1), reverse=True)"
|
"append `date` to list value of `key` in dictionary `dates_dict`, or create key `key` with value `date` in a list if it does not exist","dates_dict.setdefault(key, []).append(date)"
|
print float `a` with two decimal points,print(('{0:.2f}'.format(a)))
|
pythonic way to insert every 2 elements in a string,"""""""-"""""".join(a + b for a, b in zip(t, t))"
|
sort list of nested dictionaries `yourdata` in reverse order of 'key' and 'subkey',"yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)"
|
simple way of creating a 2d array with random numbers (python),[[random.random() for x in range(N)] for y in range(N)]
|
pair each element in list `it` 3 times into a tuple,"zip(it, it, it)"
|
mean line on top of bar plot with pandas and matplotlib,plt.show()
|
how do i create a csv file from database in python?,csv_writer.writerows(cursor)
|
convert string to binary in python,print(' '.join(['{0:b}'.format(x) for x in a_bytes]))
|
how to print like printf in python3?,"print('a={:d}, b={:d}'.format(f(x, n), g(x, n)))"
|
convert nested list `x` into a flat list,[j for i in x for j in i]
|
run a pivot with a multi-index `year` and `month` in a pandas data frame,"df.pivot_table(values='value', index=['year', 'month'], columns='item')"
|
python check if any element in a list is a key in dictionary,"any([True, False, False])"
|
filtering a pandas dataframe without removing rows,"df.where((df > df.shift(1)).values & (df.D == 1)[:, (None)], np.nan)"
|
how do i turn a dataframe into a series of lists?,df.T.apply(tuple).apply(list)
|
convert string to binary in python,""""""" """""".join(map(bin, bytearray(st)))"
|
finding streaks in pandas dataframe,df.groupby('loser').apply(f)
|
escaping quotes in string,"replace('""', '\\""')"
|
how to add extra key-value pairs to a dict() constructed with a generator argument?,"dict(((h, h * 2) for h in range(5)), foo='foo', **{'bar': 'bar'})"
|
how can i split and parse a string in python?,print(mycollapsedstring.split(' '))
|
how can i convert an rgb image into grayscale in python?,img.save('greyscale.png')
|
"multiply all items in a list `[1, 2, 3, 4, 5, 6]` together","from functools import reduce
|
reduce(lambda x, y: x * y, [1, 2, 3, 4, 5, 6])"
|
convert a dictionary `dict` into a list with key and values as list items.,[y for x in list(dict.items()) for y in x]
|
check if string `a` is an integer,a.isdigit()
|
"create datetime object from ""16sep2012""","datetime.datetime.strptime('16Sep2012', '%d%b%Y')"
|
converting a float to a string without rounding it,print(len(str(decimal.Decimal('0.1'))))
|
change data type of data in column 'grade' of dataframe `data_df` into float and then to int,data_df['grade'] = data_df['grade'].astype(float).astype(int)
|
sort a list of integers `keys` where each value is in string format,keys.sort(key=lambda x: [int(y) for y in x.split('.')])
|
different levels of logging in python,logger.setLevel(logging.DEBUG)
|
"rearrange the columns 'a','b','x','y' of pandas dataframe `df` in mentioned sequence 'x' ,'y','a' ,'b'","df = df[['x', 'y', 'a', 'b']]"
|
python code for counting number of zero crossings in an array,"sum(1 for i in range(1, len(a)) if a[i - 1] * a[i] < 0)"
|
"get the size of a list `[1,2,3]`","len([1, 2, 3])"
|
matplotlib: continuous colormap fill between two lines,plt.show()
|
transparency for poly3dcollection plot in matplotlib,plt.show()
|
"set circle markers on plot for individual points defined in list `[1,2,3,4,5,6,7,8,9,10]` created by range(10)","plt.plot(list(range(10)), linestyle='--', marker='o', color='b')"
|
google app engine - request class query_string,self.request.get('var_name')
|
how to use pandas to group pivot table results by week?,"df.resample('w', how='sum', axis=1)"
|
how to remove gaps between subplots in matplotlib?,"plt.subplots_adjust(wspace=0, hspace=0)"
|
how to set font size of matplotlib axis legend?,"plt.setp(legend.get_title(), fontsize='xx-small')"
|
how to extract variable name and value from string in python,ast.literal_eval(ata.split('=')[1].strip())
|
"find rows matching `(0,1)` in a 2 dimensional numpy array `vals`","np.where((vals == (0, 1)).all(axis=1))"
|
python: finding the last index of min element?,"min(list(range(len(values))), key=lambda i: (values[i], -i))"
|
"in python, how would i sort a list of strings where the location of the string comparison changes?","a.sort(key=lambda x: x.split('-', 2)[-1])"
|
parse string '2015/01/01 12:12am' to datetime object using format '%y/%m/%d %i:%m%p',"datetime.strptime('2015/01/01 12:12am', '%Y/%m/%d %I:%M%p')"
|
"can you create a python list from a string, while keeping characters in specific keywords together?","re.findall('car|bus|[a-z]', s)"
|
how do i check if a string exists within a string within a column,df[self.target].str.contains(t).any()
|
plot categorical data in series `df` with kind `bar` using pandas and matplotlib,df.groupby('colour').size().plot(kind='bar')
|
resizing window doesn't resize contents in tkinter,"root.grid_rowconfigure(0, weight=1)"
|
sort datetime objects `birthdays` by `month` and `day`,"birthdays.sort(key=lambda d: (d.month, d.day))"
|
"trimming ""\n"" from string `mystring`",myString.strip('\n')
|
addition of list and numpy number,"[1, 2, 3] + np.array([3])"
|
individual alpha values in scatter plot / matplotlib,plt.show()
|
a good data model for finding a user's favorite stories,"UserFavorite.get_by_name(user_id, parent=a_story)"
|
how do you get the process id of a program in unix or linux using python?,os.getpid()
|
regex. match words that contain special characters or 'http://',"re.sub('(http://\\S+|\\S*[^\\w\\s]\\S*)', '', a)"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.