text stringlengths 4 1.08k |
|---|
"find rows of 2d array in 3d numpy array 'arr' if the row has value '[[0, 3], [3, 0]]'","np.argwhere(np.all(arr == [[0, 3], [3, 0]], axis=(1, 2)))" |
From multiIndexed dataframe `data` select columns `a` and `c` within each higher order column `one` and `two`,"data.loc[:, (list(itertools.product(['one', 'two'], ['a', 'c'])))]" |
select only specific columns 'a' and 'c' from a dataframe 'data' with multiindex columns,"data.loc[:, ([('one', 'a'), ('one', 'c'), ('two', 'a'), ('two', 'c')])]" |
"match a sharp, followed by letters (including accent characters) in string `str1` using a regex","hashtags = re.findall('#(\\w+)', str1, re.UNICODE)" |
Rename file from `src` to `dst`,"os.rename(src, dst)" |
Get all texts and tags from a tag `strong` from etree tag `some_tag` using lxml,print(etree.tostring(some_tag.find('strong'))) |
Serialize dictionary `data` and its keys to a JSON formatted string,"json.dumps({str(k): v for k, v in data.items()})" |
parse UTF-8 encoded HTML response `response` to BeautifulSoup object,soup = BeautifulSoup(response.read().decode('utf-8')) |
delete file `filename`,os.remove(filename) |
get the next value greatest to `2` from a list of numbers `num_list`,min([x for x in num_list if x > 2]) |
Replace each value in column 'prod_type' of dataframe `df` with string 'responsive',df['prod_type'] = 'responsive' |
sort list `lst` with positives coming before negatives with values sorted respectively,"sorted(lst, key=lambda x: (x < 0, x))" |
get the date 6 months from today,six_months = (date.today() + relativedelta(months=(+ 6))) |
get the date 1 month from today,"(date(2010, 12, 31) + relativedelta(months=(+ 1)))" |
get the date 2 months from today,"(date(2010, 12, 31) + relativedelta(months=(+ 2)))" |
calculate the date six months from the current date,print((datetime.date.today() + datetime.timedelta(((6 * 365) / 12))).isoformat()) |
get a list of keys of dictionary `things` sorted by the value of nested dictionary key 'weight',"sorted(list(things.keys()), key=lambda x: things[x]['weight'], reverse=True)" |
get all the values from a numpy array `a` excluding index 3,a[np.arange(len(a)) != 3] |
delete all elements from a list `x` if a function `fn` taking value as parameter returns `0`,[x for x in lst if fn(x) != 0] |
set dataframe `df` index using column 'month',df.set_index('month') |
read lines from a csv file `./urls-eu.csv` into a list of lists `arr`,"arr = [line.split(',') for line in open('./urls-eu.csv')]" |
list comprehension that produces integers between 11 and 19,[i for i in range(100) if i > 10 if i < 20] |
Get only digits from a string `strs`,""""""""""""".join([c for c in strs if c.isdigit()])" |
split a string `yas` based on tab '\t',"re.split('\\t+', yas.rstrip('\t'))" |
scalar multiply matrix `a` by `b`,(a.T * b).T |
"remove trailing newline in string ""test string\n""",'test string\n'.rstrip() |
remove trailing newline in string 'test string \n\n','test string \n\n'.rstrip('\n') |
remove newline in string `s`,s.strip() |
remove newline in string `s` on the right side,s.rstrip() |
remove newline in string `s` on the left side,s.lstrip() |
remove newline in string 'Mac EOL\r','Mac EOL\r'.rstrip('\r\n') |
remove newline in string 'Windows EOL\r\n' on the right side,'Windows EOL\r\n'.rstrip('\r\n') |
remove newline in string 'Unix EOL\n' on the right side,'Unix EOL\n'.rstrip('\r\n') |
"remove newline in string ""Hello\n\n\n"" on the right side",'Hello\n\n\n'.rstrip('\n') |
split string `text` into chunks of 16 characters each,"re.findall('.{,16}\\b', text)" |
Get a list comprehension in list of lists `X`,[[X[i][j] for j in range(len(X[i]))] for i in range(len(X))] |
convert unicode string '\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0' to byte string,'\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0'.encode('latin-1') |
split dataframe `df` where the value of column `a` is equal to 'B',df.groupby((df.a == 'B').shift(1).fillna(0).cumsum()) |
save json output from a url ‘http://search.twitter.com/search.json?q=hi’ to file ‘hi.json’ in Python 2,"urllib.request.urlretrieve('http://search.twitter.com/search.json?q=hi', 'hi.json')" |
Find indices of elements equal to zero from numpy array `x`,numpy.where((x == 0))[0] |
flush output of python print,sys.stdout.flush() |
convert `i` to string,str(i) |
convert `a` to string,a.__str__() |
convert `a` to string,str(a) |
sort list of lists `L` by the second item in each list,L.sort(key=operator.itemgetter(1)) |
Print variable `count` and variable `conv` with space string ' ' in between,print(str(count) + ' ' + str(conv)) |
change NaN values in dataframe `df` using preceding values in the frame,"df.fillna(method='ffill', inplace=True)" |
change the state of the Tkinter `Text` widget to read only i.e. `disabled`,text.config(state=DISABLED) |
python sum of ascii values of all characters in a string `string`,"sum(map(ord, string))" |
apply itertools.product to elements of a list of lists `arrays`,list(itertools.product(*arrays)) |
print number `value` as thousands separators,"'{:,}'.format(value)" |
print number 1255000 as thousands separators,"locale.setlocale(locale.LC_ALL, 'en_US') |
locale.format('%d', 1255000, grouping=True)" |
"get rows of dataframe `df` where column `Col1` has values `['men', 'rocks', 'mountains']`","df[df.Col1.isin(['men', 'rocks', 'mountains'])]" |
get the value at index 1 for each tuple in the list of tuples `L`,[x[1] for x in L] |
"split unicode string ""раз два три"" into words",'\u0440\u0430\u0437 \u0434\u0432\u0430 \u0442\u0440\u0438'.split() |
sort query set by number of characters in a field `length` in django model `MyModel`,MyModel.objects.extra(select={'length': 'Length(name)'}).order_by('length') |
get a dictionary in list `dicts` which key 'ratio' is closer to a global value 1.77672955975,"min(dicts, key=lambda x: (abs(1.77672955975 - x['ratio']), -x['pixels']))" |
get the non-masked values of array `m`,m[~m.mask] |
Find all words containing letters between A and Z in string `formula`,"re.findall('\\b[A-Z]', formula)" |
"create a list `matrix` containing 5 lists, each of 5 items all set to 0",matrix = [([0] * 5) for i in range(5)] |
"creating a numpy array of 3d coordinates from three 1d arrays `x_p`, `y_p` and `z_p`","np.vstack(np.meshgrid(x_p, y_p, z_p)).reshape(3, -1).T" |
find the minimum value in a numpy array `arr` excluding 0,arr[arr != 0].min() |
"get the text of multiple elements found by xpath ""//*[@type='submit']/@value""","browser.find_elements_by_xpath(""//*[@type='submit']/@value"").text" |
find all the values in attribute `value` for the tags whose `type` attribute is `submit` in selenium,"browser.find_elements_by_xpath(""//*[@type='submit']"").get_attribute('value')" |
"parse a YAML file ""example.yaml""","with open('example.yaml', 'r') as stream: |
yaml.load(stream)" |
"parse a YAML file ""example.yaml""","with open('example.yaml', 'r') as stream: |
yaml.load(stream)" |
Sort the values of the dataframe `df` and align the columns accordingly based on the obtained indices after np.argsort., yaml.load(stream) |
Getting today's date in YYYY-MM-DD,datetime.datetime.today().strftime('%Y-%m-%d') |
urlencode a querystring 'string_of_characters_like_these:$#@=?%^Q^$' in python 2,urllib.parse.quote_plus('string_of_characters_like_these:$#@=?%^Q^$') |
sort a dictionary `d` by length of its values and print as string,"print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))" |
"convert tuple elements in list `[(1,2),(3,4),(5,6),]` into lists","map(list, zip(*[(1, 2), (3, 4), (5, 6)]))" |
"create a list of tuples which contains number 9 and the number before it, for each occurrence of 9 in the list 'myList'","[(x, y) for x, y in zip(myList, myList[1:]) if y == 9]" |
navigate to webpage given by url `http://www.python.org` using Selenium,driver.get('http://www.google.com.br') |
reverse a UTF-8 string 'a',b = a.decode('utf8')[::-1].encode('utf8') |
extract date from a string 'monkey 2010-07-32 love banana',"dparser.parse('monkey 2010-07-32 love banana', fuzzy=True)" |
extract date from a string 'monkey 20/01/1980 love banana',"dparser.parse('monkey 20/01/1980 love banana', fuzzy=True)" |
extract date from a string `monkey 10/01/1980 love banana`,"dparser.parse('monkey 10/01/1980 love banana', fuzzy=True)" |
"Convert a list `['A:1', 'B:2', 'C:3', 'D:4']` to dictionary","dict(map(lambda s: s.split(':'), ['A:1', 'B:2', 'C:3', 'D:4']))" |
check if string `the_string` contains any upper or lower-case ASCII letters,"re.search('[a-zA-Z]', the_string)" |
convert a pandas `df1` groupby object to dataframe,"DataFrame({'count': df1.groupby(['Name', 'City']).size()}).reset_index()" |
remove all non-numeric characters from string `sdkjh987978asd098as0980a98sd `,"re.sub('[^0-9]', '', 'sdkjh987978asd098as0980a98sd')" |
get items from list `a` that don't appear in list `b`,[y for y in a if y not in b] |
extract the first four rows of the column `ID` from a pandas dataframe `df`,df.groupby('ID').head(4) |
Unzip a list of tuples `l` into a list of lists,zip(*l) |
"combine two lists `[1, 2, 3, 4]` and `['a', 'b', 'c', 'd']` into a dictionary","dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))" |
"combine two lists `[1, 2, 3, 4]` and `['a', 'b', 'c', 'd']` into a dictionary","dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))" |
retrieve the path from a Flask request,request.url |
replace carriage return in string `somestring` with empty string '',"somestring.replace('\\r', '')" |
"serialize dictionary `d` as a JSON formatted string with each key formatted to pattern '%d,%d'","simplejson.dumps(dict([('%d,%d' % k, v) for k, v in list(d.items())]))" |
"parse string ""Jun 1 2005 1:33PM"" into datetime by format ""%b %d %Y %I:%M%p""","datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')" |
"parse string ""Aug 28 1999 12:00AM"" into datetime",parser.parse('Aug 28 1999 12:00AM') |
Get absolute folder path and filename for file `existGDBPath `,os.path.split(os.path.abspath(existGDBPath)) |
extract folder path from file path,os.path.dirname(os.path.abspath(existGDBPath)) |
Execute a post request to url `http://httpbin.org/post` with json data `{'test': 'cheers'}`,"requests.post('http://httpbin.org/post', json={'test': 'cheers'})" |
remove dictionary from list `a` if the value associated with its key 'link' is in list `b`,a = [x for x in a if x['link'] not in b] |
get a request parameter `a` in jinja2,{{request.args.get('a')}} |
create a list of integers between 2 values `11` and `17`,"list(range(11, 17))" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.