text stringlengths 4 1.08k |
|---|
create a list containing all cartesian products of elements in list `a`,list(itertools.product(*a)) |
remove uppercased characters in string `s`,"re.sub('[^A-Z]', '', s)" |
convert string '2011221' into a DateTime object using format '%Y%W%w',"datetime.strptime('2011221', '%Y%W%w')" |
read file 'myfile' using encoding 'iso-8859-1',"codecs.open('myfile', 'r', 'iso-8859-1').read()" |
create a list containing elements from list `list` that are predicate to function `f`,[f(x) for x in list] |
regex matching 5-digit substrings not enclosed with digits in `s`,"re.findall('(?<!\\d)\\d{5}(?!\\d)', s)" |
create a list containing elements of list `a` if the sum of the element is greater than 10,[item for item in a if sum(item) > 10] |
convert currency string `dollars` to decimal `cents_int`,cents_int = int(round(float(dollars.strip('$')) * 100)) |
remove letters from string `example_line` if the letter exist in list `bad_chars`,""""""""""""".join(dropwhile(lambda x: x in bad_chars, example_line[::-1]))[::-1]" |
Creating an empty list `l`,l = [] |
Creating an empty list `l`,l = list() |
Creating an empty list,list() |
properly quit a program,sys.exit(0) |
add string `-` in `4th` position of a string `s`,s[:4] + '-' + s[4:] |
append 3 lists in one list,[[] for i in range(3)] |
Initialize a list of empty lists `a` of size 3,a = [[] for i in range(3)] |
request URL `url` using http header `{'referer': my_referer}`,"requests.get(url, headers={'referer': my_referer})" |
"set the y axis range to `0, 1000` in subplot using pylab","pylab.ylim([0, 1000])" |
convert a column of list in series `s` to dummies,pd.get_dummies(s.apply(pd.Series).stack()).sum(level=0) |
convert a hex string `x` to string,"y = str(int(x, 16))" |
check if string `a` is an integer,a.isdigit() |
function to check if a string is a number,isdigit() |
check if string `b` is a number,b.isdigit() |
pandas read comma-separated CSV file `s` and skip commented lines starting with '#',"pd.read_csv(StringIO(s), sep=',', comment='#')" |
"pandas: change all the values of a column 'Date' into ""int(str(x)[-4:])""",df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:])) |
sum a list of numbers `list_of_nums`,sum(list_of_nums) |
Get an item from a list of dictionary `lst` which has maximum value in the key `score` using lambda function,"max(lst, key=lambda x: x['score'])" |
BeautifulSoup find all tags with attribute 'name' equal to 'description',soup.findAll(attrs={'name': 'description'}) |
"remove all spaces from a string converted from dictionary `{'a': 1, 'b': 'as df'}`","str({'a': 1, 'b': 'as df'}).replace(': ', ':').replace(', ', ',')" |
convert dictionary `dict` into a string formatted object,"'{' + ','.join('{0!r}:{1!r}'.format(*x) for x in list(dct.items())) + '}'" |
concatenate items from list `parts` into a string starting from the second element,""""""""""""".join(parts[1:])" |
"insert a character ',' into a string in front of '+' character in second part of the string",""""""",+"""""".join(c.rsplit('+', 1))" |
delete all rows in a numpy array `a` where any value in a row is zero `0`,"a[np.all(a != 0, axis=1)]" |
extract only alphabetic characters from a string `your string`,""""""" """""".join(re.split('[^a-zA-Z]*', 'your string'))" |
Extract only characters from a string as a list,"re.split('[^a-zA-Z]*', 'your string')" |
get the union set from list of lists `results_list`,results_union = set().union(*results_list) |
get the union of values in list of lists `result_list`,return list(set(itertools.chain(*result_list))) |
check if a numpy array `a1` contains any element of another array `a2`,"np.any(np.in1d(a1, a2))" |
removing control characters from a string `s`,return ''.join(ch for ch in s if unicodedata.category(ch)[0] != 'C') |
Compare if each value in list `a` is less than respective index value in list `b`,"all(i < j for i, j in zip(a, b))" |
python selenium click on button '.button.c_button.s_button',driver.find_element_by_css_selector('.button.c_button.s_button').click() |
kill a process `make.exe` from python script on windows,os.system('taskkill /im make.exe') |
SQLAlchemy select records of columns of table `my_table` in addition to current date column,"print(select([my_table, func.current_date()]).execute())" |
remove duplicate characters from string 'ffffffbbbbbbbqqq',"re.sub('([a-z])\\1+', '\\1', 'ffffffbbbbbbbqqq')" |
remove periods inbetween capital letters that aren't immediately preceeded by word character(s) in a string `s` using regular expressions,"re.sub('(?<!\\w)([A-Z])\\.', '\\1', s)" |
Get a list of strings `split_text` with fixed chunk size `n` from a string `the_list`,"split_list = [the_list[i:i + n] for i in range(0, len(the_list), n)]" |
"match string 'this is my string' with regex '\\b(this|string)\\b' |
then replace it with regex '<markup>\\1</markup>'","re.sub('\\b(this|string)\\b', '<markup>\\1</markup>', 'this is my string')" |
output data of the first 7 columns of Pandas dataframe,"pandas.set_option('display.max_columns', 7)" |
Display maximum output data of columns in dataframe `pandas` that will fit into the screen,"pandas.set_option('display.max_columns', None)" |
set the value in column 'B' to NaN if the corresponding value in column 'A' is equal to 0 in pandas dataframe `df`,"df.ix[df.A == 0, 'B'] = np.nan" |
"Selecting Element ""//li/label/input"" followed by text ""polishpottery"" with Selenium WebDriver `driver`","driver.find_element_by_xpath(""//li/label/input[contains(..,'polishpottery')]"")" |
"Sort a list of dictionaries `mylist` by keys ""weight"" and ""factor""","mylist.sort(key=operator.itemgetter('weight', 'factor'))" |
ordering a list of dictionaries `mylist` by elements 'weight' and 'factor',"mylist.sort(key=lambda d: (d['weight'], d['factor']))" |
Convert a list of lists `lol` to a dictionary with key as second value of a list and value as list itself,{x[1]: x for x in lol} |
sort keys of dictionary 'd' based on their values,"sorted(d, key=lambda k: d[k][1])" |
round 123 to 100,"int(round(123, -2))" |
create file 'x' if file 'x' does not exist,"fd = os.open('x', os.O_WRONLY | os.O_CREAT | os.O_EXCL)" |
get a list of last trailing words from another list of strings`Original_List`,new_list = [x.split()[-1] for x in Original_List] |
Reverse a string 'hello world','hello world'[::(-1)] |
Reverse list `s`,s[::(-1)] |
Reverse string 'foo',''.join(reversed('foo')) |
Reverse a string `string`,''.join(reversed(string)) |
"Reverse a string ""foo""",'foo'[::(-1)] |
Reverse a string `a_string`,a_string[::(-1)] |
Reverse a string `a_string`,"def reversed_string(a_string): |
return a_string[::(-1)]" |
Reverse a string `s`,''.join(reversed(s)) |
generate a string of numbers separated by comma which is divisible by `4` with remainder `1` or `2`.,""""""","""""".join(str(i) for i in range(100) if i % 4 in (1, 2))" |
"convert list `lst` of key, value pairs into a dictionary","dict([(e[0], int(e[1])) for e in lst])" |
sorting a list of tuples `list_of_tuples` where each tuple is reversed,"sorted(list_of_tuples, key=lambda tup: tup[::-1])" |
sorting a list of tuples `list_of_tuples` by second key,"sorted(list_of_tuples, key=lambda tup: tup[1])" |
Concatenating two one-dimensional NumPy arrays 'a' and 'b'.,"numpy.concatenate([a, b])" |
writing items in list `thelist` to file `thefile`,"for item in thelist: |
thefile.write(('%s\n' % item))" |
writing items in list `thelist` to file `thefile`,"for item in thelist: |
pass" |
serialize `itemlist` to file `outfile`,"pickle.dump(itemlist, outfile)" |
writing items in list `itemlist` to file `outfile`,outfile.write('\n'.join(itemlist)) |
Update a user's name as `Bob Marley` having id `123` in SQLAlchemy,session.query(User).filter_by(id=123).update({'name': 'Bob Marley'}) |
send cookies `cookie` in a post request to url 'http://wikipedia.org' with the python requests library,"r = requests.post('http://wikipedia.org', cookies=cookie)" |
insert directory 'libs' at the 0th index of current directory,"sys.path.insert(0, 'libs')" |
get current date and time,datetime.datetime.now() |
get current time,datetime.datetime.now().time() |
get current time in pretty format,"strftime('%Y-%m-%d %H:%M:%S', gmtime())" |
get current time in string format,str(datetime.now()) |
get current time,datetime.datetime.time(datetime.datetime.now()) |
convert hex '\xff' to integer,ord('\xff') |
identify duplicated rows in columns 'PplNum' and 'RoomNum' with additional column in dataframe `df`,"df.groupby(['PplNum', 'RoomNum']).cumcount() + 1" |
get current utc time,datetime.utcnow() |
move last item of array `a` to the first position,a[-1:] + a[:-1] |
"Convert dataframe `df` to a pivot table using column 'year', 'month', and 'item' as indexes","df.set_index(['year', 'month', 'item']).unstack(level=-1)" |
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')" |
print a rational number `3/2`,print('\n\x1b[4m' + '3' + '\x1b[0m' + '\n2') |
iterate backwards from 10 to 0,"range(10, 0, -1)" |
get value of first child of xml node `name`,name[0].firstChild.nodeValue |
start a new thread for `myfunction` with parameters 'MyStringHere' and 1,"thread.start_new_thread(myfunction, ('MyStringHere', 1))" |
start a new thread for `myfunction` with parameters 'MyStringHere' and 1,"thread.start_new_thread(myfunction, ('MyStringHere', 1))" |
get index of the first biggest element in list `a`,a.index(max(a)) |
replace periods `.` that are not followed by periods or spaces with a period and a space `. `,"re.sub('\\.(?=[^ .])', '. ', para)" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.