[ { "intent": "How to convert a list of multiple integers into a single integer?", "rewritten_intent": "Concatenate elements of a list 'x' of multiple integers to a single integer", "snippet": "sum(d * 10 ** i for i, d in enumerate(x[::-1]))", "question_id": 41067960 }, { "intent": "How to convert a list of multiple integers into a single integer?", "rewritten_intent": "convert a list of integers into a single integer", "snippet": "r = int(''.join(map(str, x)))", "question_id": 41067960 }, { "intent": "how to convert a datetime string back to datetime object?", "rewritten_intent": "convert a DateTime string back to a DateTime object of format '%Y-%m-%d %H:%M:%S.%f'", "snippet": "datetime.strptime('2010-11-13 10:33:54.227806', '%Y-%m-%d %H:%M:%S.%f')", "question_id": 4170655 }, { "intent": "Averaging the values in a dictionary based on the key", "rewritten_intent": "get the average of a list values for each key in dictionary `d`)", "snippet": "[(i, sum(j) / len(j)) for i, j in list(d.items())]", "question_id": 29565452 }, { "intent": "zip lists in python", "rewritten_intent": "zip two lists `[1, 2]` and `[3, 4]` into a list of two tuples containing elements at the same index in each list", "snippet": "zip([1, 2], [3, 4])", "question_id": 13704860 }, { "intent": "Prepend the same string to all items in a list", "rewritten_intent": "prepend string 'hello' to all items in list 'a'", "snippet": "['hello{0}'.format(i) for i in a]", "question_id": 13331419 }, { "intent": "regex for repeating words in a string in Python", "rewritten_intent": "regex for repeating words in a string `s`", "snippet": "re.sub('(?ijl', A, B)", "question_id": 31957364 }, { "intent": "print variable and a string in python", "rewritten_intent": "Print a string `card` with string formatting", "snippet": "print('I have: {0.price}'.format(card))", "question_id": 14041791 }, { "intent": "How can I add a comment to a YAML file in Python", "rewritten_intent": "Write a comment `# Data for Class A\\n` to a file object `f`", "snippet": "f.write('# Data for Class A\\n')", "question_id": 30994370 }, { "intent": "How do I move the last item in a list to the front in python?", "rewritten_intent": "move the last item in list `a` to the beginning", "snippet": "a = a[-1:] + a[:-1]", "question_id": 6490560 }, { "intent": "python - convert datetime to varchar/string", "rewritten_intent": "Parse DateTime object `datetimevariable` using format '%Y-%m-%d'", "snippet": "datetimevariable.strftime('%Y-%m-%d')", "question_id": 40173569 }, { "intent": "What's the most pythonic way of normalizing lineends in a string?", "rewritten_intent": "Normalize line ends in a string 'mixed'", "snippet": "mixed.replace('\\r\\n', '\\n').replace('\\r', '\\n')", "question_id": 1749466 }, { "intent": "How to find the real user home directory using python?", "rewritten_intent": "find the real user home directory using python", "snippet": "os.path.expanduser('~user')", "question_id": 2668909 }, { "intent": "In Python, how do I index a list with another list?", "rewritten_intent": "index a list `L` with another list `Idx`", "snippet": "T = [L[i] for i in Idx]", "question_id": 1012185 }, { "intent": "Iterate through words of a file in Python", "rewritten_intent": "get a list of words `words` of a file 'myfile'", "snippet": "words = open('myfile').read().split()", "question_id": 7745260 }, { "intent": "Summing 2nd list items in a list of lists of lists", "rewritten_intent": "Get a list of lists with summing the values of the second element from each list of lists `data`", "snippet": "[[sum([x[1] for x in i])] for i in data]", "question_id": 37619348 }, { "intent": "Summing 2nd list items in a list of lists of lists", "rewritten_intent": "summing the second item in a list of lists of lists", "snippet": "[sum([x[1] for x in i]) for i in data]", "question_id": 37619348 }, { "intent": "Django order by highest number of likes", "rewritten_intent": "sort objects in `Articles` in descending order of counts of `likes`", "snippet": "Article.objects.annotate(like_count=Count('likes')).order_by('-like_count')", "question_id": 35097130 }, { "intent": "How to convert datetime.date.today() to UTC time?", "rewritten_intent": "return a DateTime object with the current UTC date", "snippet": "today = datetime.datetime.utcnow().date()", "question_id": 27587127 }, { "intent": "How to perform element-wise multiplication of two lists in Python?", "rewritten_intent": "create a list containing the multiplication of each elements at the same index of list `lista` and list `listb`", "snippet": "[(a * b) for a, b in zip(lista, listb)]", "question_id": 10271484 }, { "intent": "Capturing emoticons using regular expression in python", "rewritten_intent": "fetch smilies matching regex pattern '(?::|;|=)(?:-)?(?:\\\\)|\\\\(|D|P)' in string `s`", "snippet": "re.findall('(?::|;|=)(?:-)?(?:\\\\)|\\\\(|D|P)', s)", "question_id": 14571103 }, { "intent": "Capturing emoticons using regular expression in python", "rewritten_intent": "match the pattern '[:;][)(](?![)(])' to the string `str`", "snippet": "re.match('[:;][)(](?![)(])', str)", "question_id": 14571103 }, { "intent": "List of objects to JSON with Python", "rewritten_intent": "convert a list of objects `list_name` to json string `json_string`", "snippet": "json_string = json.dumps([ob.__dict__ for ob in list_name])", "question_id": 26033239 }, { "intent": "List of zeros in python", "rewritten_intent": "create a list `listofzeros` of `n` zeros", "snippet": "listofzeros = [0] * n", "question_id": 8528178 }, { "intent": "python: how to convert a string to utf-8", "rewritten_intent": "decode the string 'stringnamehere' to UTF-8", "snippet": "stringnamehere.decode('utf-8', 'ignore')", "question_id": 4182603 }, { "intent": "Python regex - Ignore parenthesis as indexing?", "rewritten_intent": "Match regex pattern '((?:A|B|C)D)' on string 'BDE'", "snippet": "re.findall('((?:A|B|C)D)', 'BDE')", "question_id": 11985628 }, { "intent": "Python dict how to create key or append an element to key?", "rewritten_intent": "Create a key `key` if it does not exist in dict `dic` and append element `value` to value.", "snippet": "dic.setdefault(key, []).append(value)", "question_id": 12905999 }, { "intent": "Finding the minimum value in a numpy array and the corresponding values for the rest of that array's row", "rewritten_intent": "Get the value of the minimum element in the second column of array `a`", "snippet": "a[np.argmin(a[:, (1)])]", "question_id": 14956683 }, { "intent": "Python \"extend\" for a dictionary", "rewritten_intent": "extend dictionary `a` with key/value pairs of dictionary `b`", "snippet": "a.update(b)", "question_id": 577234 }, { "intent": "Removing key values pairs from a list of dictionaries", "rewritten_intent": "removing key values pairs with key 'mykey1' from a list of dictionaries `mylist`", "snippet": "[{k: v for k, v in d.items() if k != 'mykey1'} for d in mylist]", "question_id": 13254241 }, { "intent": "Removing key values pairs from a list of dictionaries", "rewritten_intent": null, "snippet": "[dict((k, v) for k, v in d.items() if k != 'mykey1') for d in mylist]", "question_id": 13254241 }, { "intent": "Simple way to create matrix of random numbers", "rewritten_intent": "create 3 by 3 matrix of random numbers", "snippet": "numpy.random.random((3, 3))", "question_id": 15451958 }, { "intent": "Make new column in Panda dataframe by adding values from other columns", "rewritten_intent": "make new column 'C' in panda dataframe by adding values from other columns 'A' and 'B'", "snippet": "df['C'] = df['A'] + df['B']", "question_id": 34023918 }, { "intent": "Find dictionary items whose key matches a substring", "rewritten_intent": "create a list of values from the dictionary `programs` that have a key with a case insensitive match to 'new york'", "snippet": "[value for key, value in list(programs.items()) if 'new york' in key.lower()]", "question_id": 10484261 }, { "intent": "Import module in another directory from a \"parallel\" sub-directory", "rewritten_intent": "append a path `/path/to/main_folder` in system path", "snippet": "sys.path.append('/path/to/main_folder')", "question_id": 9153527 }, { "intent": "Regex for getting all digits in a string after a character", "rewritten_intent": "get all digits in a string `s` after a '[' character", "snippet": "re.findall('\\\\d+(?=[^[]+$)', s)", "question_id": 34338341 }, { "intent": "Python pickle/unpickle a list to/from a file", "rewritten_intent": "python pickle/unpickle a list to/from a file 'afile'", "snippet": "pickle.load(open('afile', 'rb'))", "question_id": 18229082 }, { "intent": "Clicking a link using selenium using python", "rewritten_intent": null, "snippet": "driver.find_element_by_xpath('xpath').click()", "question_id": 17498027 }, { "intent": "Counting unique index values in Pandas groupby", "rewritten_intent": "count unique index values in column 'A' in pandas dataframe `ex`", "snippet": "ex.groupby(level='A').agg(lambda x: x.index.get_level_values(1).nunique())", "question_id": 35178812 }, { "intent": "Dict of dicts of dicts to DataFrame", "rewritten_intent": "Create a pandas dataframe of values from a dictionary `d` which contains dictionaries of dictionaries", "snippet": "pd.concat(map(pd.DataFrame, iter(d.values())), keys=list(d.keys())).stack().unstack(0)", "question_id": 15455388 }, { "intent": "In Python, find out number of differences between two ordered lists", "rewritten_intent": "find out the number of non-matched elements at the same index of list `a` and list `b`", "snippet": "sum(1 for i, j in zip(a, b) if i != j)", "question_id": 14914615 }, { "intent": "When the key is a tuple in dictionary in Python", "rewritten_intent": "make all keys lowercase in dictionary `d`", "snippet": "d = {(a.lower(), b): v for (a, b), v in list(d.items())}", "question_id": 21833383 }, { "intent": "Sorting a list of tuples with multiple conditions", "rewritten_intent": "sort list `list_` based on first element of each tuple and by the length of the second element of each tuple", "snippet": "list_.sort(key=lambda x: [x[0], len(x[1]), x[1]])", "question_id": 19643099 }, { "intent": "trim whitespace", "rewritten_intent": "trim whitespace in string `s`", "snippet": "s.strip()", "question_id": 1185524 }, { "intent": "trim whitespace (including tabs)", "rewritten_intent": "trim whitespace (including tabs) in `s` on the left side", "snippet": "s = s.lstrip()", "question_id": 1185524 }, { "intent": "trim whitespace (including tabs)", "rewritten_intent": "trim whitespace (including tabs) in `s` on the right side", "snippet": "s = s.rstrip()", "question_id": 1185524 }, { "intent": "trim whitespace (including tabs)", "rewritten_intent": "trim characters ' \\t\\n\\r' in `s`", "snippet": "s = s.strip(' \\t\\n\\r')", "question_id": 1185524 }, { "intent": "trim whitespace (including tabs)", "rewritten_intent": "trim whitespaces (including tabs) in string `s`", "snippet": "print(re.sub('[\\\\s+]', '', s))", "question_id": 1185524 }, { "intent": "In Django, how do I filter based on all entities in a many-to-many relation instead of any?", "rewritten_intent": "In Django, filter `Task.objects` based on all entities in ['A', 'P', 'F']", "snippet": "Task.objects.exclude(prerequisites__status__in=['A', 'P', 'F'])", "question_id": 1516795 }, { "intent": "Background color for Tk in Python", "rewritten_intent": "Change background color in Tkinter", "snippet": "root.configure(background='black')", "question_id": 2744795 }, { "intent": "python dict to numpy structured array", "rewritten_intent": "convert dict `result` to numpy structured array", "snippet": "numpy.array([(key, val) for key, val in result.items()], dtype)", "question_id": 15579649 }, { "intent": "Pandas - Sorting By Column", "rewritten_intent": "Concatenate dataframe `df_1` to dataframe `df_2` sorted by values of the column 'y'", "snippet": "pd.concat([df_1, df_2.sort_values('y')])", "question_id": 41192805 }, { "intent": "rreplace - How to replace the last occurence of an expression in a string?", "rewritten_intent": "replace the last occurence of an expression '' with '' in a string `s`", "snippet": "re.sub('(.*)', '\\\\1', s)", "question_id": 2556108 }, { "intent": "How do I compare values in a dictionary?", "rewritten_intent": "get the maximum of 'salary' and 'bonus' values in a dictionary", "snippet": "print(max(d, key=lambda x: (d[x]['salary'], d[x]['bonus'])))", "question_id": 42211584 }, { "intent": "How to do many-to-many Django query to find book with 2 given authors?", "rewritten_intent": "Filter Django objects by `author` with ids `1` and `2`", "snippet": "Book.objects.filter(author__id=1).filter(author__id=2)", "question_id": 5301996 }, { "intent": "Python regex split case insensitive in 2.6", "rewritten_intent": "split string 'fooxyzbar' based on case-insensitive matching using string 'XYZ'", "snippet": "re.compile('XYZ', re.IGNORECASE).split('fooxyzbar')", "question_id": 8993904 }, { "intent": "List comprehension - converting strings in one list, to integers in another", "rewritten_intent": "get list of sums of neighboring integers in string `example`", "snippet": "[sum(map(int, s)) for s in example.split()]", "question_id": 40498088 }, { "intent": "How to find duplicate elements in array using for loop in Python?", "rewritten_intent": "Get all the keys from dictionary `y` whose value is `1`", "snippet": "[i for i in y if y[i] == 1]", "question_id": 1920145 }, { "intent": "Converting byte string in unicode string", "rewritten_intent": "converting byte string `c` in unicode string", "snippet": "c.decode('unicode_escape')", "question_id": 13837848 }, { "intent": "How can I \"unpivot\" specific columns from a pandas DataFrame?", "rewritten_intent": "unpivot first 2 columns into new columns 'year' and 'value' from a pandas dataframe `x`", "snippet": "pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value')", "question_id": 23354124 }, { "intent": "add new item to dictionary", "rewritten_intent": "add key \"item3\" and value \"3\" to dictionary `default_data `", "snippet": "default_data['item3'] = 3", "question_id": 6416131 }, { "intent": "add new item to dictionary", "rewritten_intent": "add key \"item3\" and value \"3\" to dictionary `default_data `", "snippet": "default_data.update({'item3': 3, })", "question_id": 6416131 }, { "intent": "add new item to dictionary", "rewritten_intent": "add key value pairs 'item4' , 4 and 'item5' , 5 to dictionary `default_data`", "snippet": "default_data.update({'item4': 4, 'item5': 5, })", "question_id": 6416131 }, { "intent": "Index the first and the last n elements of a list", "rewritten_intent": "Get the first and last 3 elements of list `l`", "snippet": "l[:3] + l[-3:]", "question_id": 40016359 }, { "intent": "How to reset index in a pandas data frame?", "rewritten_intent": "reset index to default in dataframe `df`", "snippet": "df = df.reset_index(drop=True)", "question_id": 20490274 }, { "intent": "Merging a list with a list of lists", "rewritten_intent": "For each index `x` from 0 to 3, append the element at index `x` of list `b` to the list at index `x` of list a.", "snippet": "[a[x].append(b[x]) for x in range(3)]", "question_id": 18872717 }, { "intent": "how to find the target file's full(absolute path) of the symbolic link or soft link in python", "rewritten_intent": "get canonical path of the filename `path`", "snippet": "os.path.realpath(path)", "question_id": 3220755 }, { "intent": "How to check if a dictionary is in another dictionary in python", "rewritten_intent": "check if dictionary `L[0].f.items()` is in dictionary `a3.f.items()`", "snippet": "set(L[0].f.items()).issubset(set(a3.f.items()))", "question_id": 18170459 }, { "intent": "How to find the index of a value in 2d array in Python?", "rewritten_intent": "find all the indexes in a Numpy 2D array where the value is 1", "snippet": "zip(*np.where(a == 1))", "question_id": 27175400 }, { "intent": "How to find the index of a value in 2d array in Python?", "rewritten_intent": null, "snippet": "np.where(a == 1)", "question_id": 27175400 }, { "intent": "Python Pandas - How to flatten a hierarchical index in columns", "rewritten_intent": "Collapse hierarchical column index to level 0 in dataframe `df`", "snippet": "df.columns = df.columns.get_level_values(0)", "question_id": 14507794 }, { "intent": "Creating a list from a Scipy matrix", "rewritten_intent": "create a matrix from a list `[1, 2, 3]`", "snippet": "x = scipy.matrix([1, 2, 3]).transpose()", "question_id": 4690366 }, { "intent": "Regex Python adding characters after a certain word", "rewritten_intent": "add character '@' after word 'get' in string `text`", "snippet": "text = re.sub('(\\\\bget\\\\b)', '\\\\1@', text)", "question_id": 20735384 }, { "intent": "Element-wise minimum of multiple vectors in numpy", "rewritten_intent": "get a numpy array that contains the element wise minimum of three 3x1 arrays", "snippet": "np.array([np.arange(3), np.arange(2, -1, -1), np.ones((3,))]).min(axis=0)", "question_id": 39277638 }, { "intent": "Pandas (python): How to add column to dataframe for index?", "rewritten_intent": "add a column 'new_col' to dataframe `df` for index in range", "snippet": "df['new_col'] = list(range(1, len(df) + 1))", "question_id": 12168648 }, { "intent": "How to set environment variables in Python", "rewritten_intent": "set environment variable 'DEBUSSY' equal to 1", "snippet": "os.environ['DEBUSSY'] = '1'", "question_id": 5971312 }, { "intent": "How to set environment variables in Python", "rewritten_intent": "Get a environment variable `DEBUSSY`", "snippet": "print(os.environ['DEBUSSY'])", "question_id": 5971312 }, { "intent": "How to set environment variables in Python", "rewritten_intent": "set environment variable 'DEBUSSY' to '1'", "snippet": "os.environ['DEBUSSY'] = '1'", "question_id": 5971312 }, { "intent": "Python: updating a large dictionary using another large dictionary", "rewritten_intent": "update dictionary `b`, overwriting values where keys are identical, with contents of dictionary `d`", "snippet": "b.update(d)", "question_id": 12717716 }, { "intent": "How to get column by number in Pandas?", "rewritten_intent": "get all the values in column `b` from pandas data frame `df`", "snippet": "df['b']", "question_id": 17193850 }, { "intent": "How can I get the color of the last figure in matplotlib?", "rewritten_intent": "make a line plot with errorbars, `ebar`, from data `x, y, err` and set color of the errorbars to `y` (yellow)", "snippet": "ebar = plt.errorbar(x, y, yerr=err, ecolor='y')", "question_id": 13395888 }, { "intent": "Python: How can I find all files with a particular extension?", "rewritten_intent": "find all files with extension '.c' in directory `folder`", "snippet": "results += [each for each in os.listdir(folder) if each.endswith('.c')]", "question_id": 3608411 }, { "intent": "Concatenating Unicode with string: print '\u00a3' + '1' works, but print '\u00a3' + u'1' throws UnicodeDecodeError", "rewritten_intent": "add unicode string '1' to UTF-8 decoded string '\\xc2\\xa3'", "snippet": "print('\\xc2\\xa3'.decode('utf8') + '1')", "question_id": 31771758 }, { "intent": "How to convert the following string in python?", "rewritten_intent": "lower-case the string obtained by replacing the occurrences of regex pattern '(?<=[a-z])([A-Z])' in string `s` with eplacement '-\\\\1'", "snippet": "re.sub('(?<=[a-z])([A-Z])', '-\\\\1', s).lower()", "question_id": 39414085 }, { "intent": "Setting stacksize in a python script", "rewritten_intent": null, "snippet": "os.system('ulimit -s unlimited; some_executable')", "question_id": 5061582 }, { "intent": "Python Decimals format", "rewritten_intent": "format a string `num` using string formatting", "snippet": "\"\"\"{0:.3g}\"\"\".format(num)", "question_id": 2389846 }, { "intent": "Add single element to array in numpy", "rewritten_intent": "append the first element of array `a` to array `a`", "snippet": "numpy.append(a, a[0])", "question_id": 7332841 }, { "intent": "Return the column name(s) for a specific value in a pandas dataframe", "rewritten_intent": "return the column for value 38.15 in dataframe `df`", "snippet": "df.ix[:, (df.loc[0] == 38.15)].columns", "question_id": 38331568 }, { "intent": "Merge 2 dataframes with same values in a column", "rewritten_intent": "merge 2 dataframes `df1` and `df2` with same values in a column 'revenue' with and index 'date'", "snippet": "df2['revenue'] = df2.CET.map(df1.set_index('date')['revenue'])", "question_id": 41463763 }, { "intent": "How To Format a JSON Text In Python?", "rewritten_intent": "load a json data `json_string` into variable `json_data`", "snippet": "json_data = json.loads(json_string)", "question_id": 23970693 }, { "intent": "Python: converting radians to degrees", "rewritten_intent": "convert radians 1 to degrees", "snippet": "math.cos(math.radians(1))", "question_id": 9875964 }, { "intent": "count how many of an object type there are in a list Python", "rewritten_intent": "count the number of integers in list `a`", "snippet": "sum(isinstance(x, int) for x in a)", "question_id": 25355705 }, { "intent": "Python: Getting rid of \\u200b from a string using regular expressions", "rewritten_intent": "replacing '\\u200b' with '*' in a string using regular expressions", "snippet": "'used\\u200b'.replace('\\u200b', '*')", "question_id": 31522361 }, { "intent": "How to run two functions simultaneously", "rewritten_intent": "run function 'SudsMove' simultaneously", "snippet": "threading.Thread(target=SudsMove).start()", "question_id": 2108126 }, { "intent": "sum of squares in a list in one line?", "rewritten_intent": "sum of squares values in a list `l`", "snippet": "sum(i * i for i in l)", "question_id": 26894227 }, { "intent": "sum of squares in a list in one line?", "rewritten_intent": "calculate the sum of the squares of each value in list `l`", "snippet": "sum(map(lambda x: x * x, l))", "question_id": 26894227 }, { "intent": "Create a dictionary with list comprehension", "rewritten_intent": "Create a dictionary `d` from list `iterable`", "snippet": "d = dict(((key, value) for (key, value) in iterable))", "question_id": 1747817 }, { "intent": "Create a dictionary with list comprehension", "rewritten_intent": "Create a dictionary `d` from list `iterable`", "snippet": "d = {key: value for (key, value) in iterable}", "question_id": 1747817 }, { "intent": "Create a dictionary with list comprehension", "rewritten_intent": "Create a dictionary `d` from list of key value pairs `iterable`", "snippet": "d = {k: v for (k, v) in iterable}", "question_id": 1747817 }, { "intent": "Rounding entries in a Pandas DafaFrame", "rewritten_intent": "round off entries in dataframe `df` column `Alabama_exp` to two decimal places, and entries in column `Credit_exp` to three decimal places", "snippet": "df.round({'Alabama_exp': 2, 'Credit_exp': 3})", "question_id": 19100540 }, { "intent": "Pycurl keeps printing in terminal", "rewritten_intent": "Make function `WRITEFUNCTION` output nothing in curl `p`", "snippet": "p.setopt(pycurl.WRITEFUNCTION, lambda x: None)", "question_id": 7668141 }, { "intent": "Return a random word from a word list in python", "rewritten_intent": "return a random word from a word list 'words'", "snippet": "print(random.choice(words))", "question_id": 1456617 }, { "intent": "Find Max in Nested Dictionary", "rewritten_intent": "Find a max value of the key `count` in a nested dictionary `d`", "snippet": "max(d, key=lambda x: d[x]['count'])", "question_id": 12829889 }, { "intent": "How to replace empty string with zero in comma-separated string?", "rewritten_intent": "get list of string elements in string `data` delimited by commas, putting `0` in place of empty strings", "snippet": "[(int(x) if x else 0) for x in data.split(',')]", "question_id": 2606976 }, { "intent": "How to replace empty string with zero in comma-separated string?", "rewritten_intent": "split string `s` into a list of strings based on ',' then replace empty strings with zero", "snippet": "\"\"\",\"\"\".join(x or '0' for x in s.split(','))", "question_id": 2606976 }, { "intent": "Regular expression syntax for \"match nothing\"?", "rewritten_intent": "regular expression match nothing", "snippet": "re.compile('$^')", "question_id": 940822 }, { "intent": "Regular expression syntax for \"match nothing\"?", "rewritten_intent": "regular expression syntax for not to match anything", "snippet": "re.compile('.\\\\A|.\\\\A*|.\\\\A+')", "question_id": 940822 }, { "intent": "Regular expression syntax for \"match nothing\"?", "rewritten_intent": "create a regular expression object with a pattern that will match nothing", "snippet": "re.compile('a^')", "question_id": 940822 }, { "intent": "Python Pandas drop columns based on max value of column", "rewritten_intent": "drop all columns in dataframe `df` that holds a maximum value bigger than 0", "snippet": "df.columns[df.max() > 0]", "question_id": 26897536 }, { "intent": "How can I check if a date is the same day as datetime.today()?", "rewritten_intent": "check if date `yourdatetime` is equal to today's date", "snippet": "yourdatetime.date() == datetime.today().date()", "question_id": 6407362 }, { "intent": "How do I print bold text in Python?", "rewritten_intent": "print bold text 'Hello'", "snippet": "print('\\x1b[1m' + 'Hello')", "question_id": 8924173 }, { "intent": "Renaming multiple files in python", "rewritten_intent": "remove 20 symbols in front of '.' in string 'unique12345678901234567890.mkv'", "snippet": "re.sub('.{20}(.mkv)', '\\\\1', 'unique12345678901234567890.mkv')", "question_id": 4358701 }, { "intent": "Can I get a list of the variables that reference an other in Python 2.7?", "rewritten_intent": "Define a list with string values `['a', 'c', 'b', 'obj']`", "snippet": "['a', 'c', 'b', 'obj']", "question_id": 17589590 }, { "intent": "Substitute multiple whitespace with single whitespace in Python", "rewritten_intent": "substitute multiple whitespace with single whitespace in string `mystring`", "snippet": "\"\"\" \"\"\".join(mystring.split())", "question_id": 2077897 }, { "intent": "How to print floating point numbers as it is without any truncation in python?", "rewritten_intent": "print a floating point number 2.345e-67 without any truncation", "snippet": "print('{:.100f}'.format(2.345e-67))", "question_id": 20048987 }, { "intent": "Check if a given key already exists in a dictionary", "rewritten_intent": "Check if key 'key1' in `dict`", "snippet": "('key1' in dict)", "question_id": 1602934 }, { "intent": "Check if a given key already exists in a dictionary", "rewritten_intent": "Check if key 'a' in `d`", "snippet": "('a' in d)", "question_id": 1602934 }, { "intent": "Check if a given key already exists in a dictionary", "rewritten_intent": "Check if key 'c' in `d`", "snippet": "('c' in d)", "question_id": 1602934 }, { "intent": "Check if a given key already exists in a dictionary", "rewritten_intent": "Check if a given key 'key1' exists in dictionary `dict`", "snippet": "if ('key1' in dict):\n pass", "question_id": 1602934 }, { "intent": "Check if a given key already exists in a dictionary", "rewritten_intent": "Check if a given key `key` exists in dictionary `d`", "snippet": "if (key in d):\n pass", "question_id": 1602934 }, { "intent": "django filter with list of values", "rewritten_intent": "create a django query for a list of values `1, 4, 7`", "snippet": "Blog.objects.filter(pk__in=[1, 4, 7])", "question_id": 9304908 }, { "intent": "read a binary file (python)", "rewritten_intent": "read a binary file 'test/test.pdf'", "snippet": "f = open('test/test.pdf', 'rb')", "question_id": 2497027 }, { "intent": "Format string - spaces between every three digit", "rewritten_intent": "insert ' ' between every three digit before '.' and replace ',' with '.' in 12345678.46", "snippet": "format(12345678.46, ',').replace(',', ' ').replace('.', ',')", "question_id": 17484631 }, { "intent": "Joining pandas dataframes by column names", "rewritten_intent": "Join pandas data frame `frame_1` and `frame_2` with left join by `county_ID` and right join by `countyid`", "snippet": "pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')", "question_id": 20375561 }, { "intent": "How to calculate percentage of sparsity for a numpy array/matrix?", "rewritten_intent": "calculate ratio of sparsity in a numpy array `a`", "snippet": "np.isnan(a).sum() / np.prod(a.shape)", "question_id": 38708621 }, { "intent": "Sorting a defaultdict by value in python", "rewritten_intent": "reverse sort items in default dictionary `cityPopulation` by the third item in each key's list of values", "snippet": "sorted(iter(cityPopulation.items()), key=lambda k_v: k_v[1][2], reverse=True)", "question_id": 10194713 }, { "intent": "Sorting a defaultdict by value in python", "rewritten_intent": "Sort dictionary `u` in ascending order based on second elements of its values", "snippet": "sorted(list(u.items()), key=lambda v: v[1])", "question_id": 10194713 }, { "intent": "Sorting a defaultdict by value in python", "rewritten_intent": "reverse sort dictionary `d` based on its values", "snippet": "sorted(list(d.items()), key=lambda k_v: k_v[1], reverse=True)", "question_id": 10194713 }, { "intent": "Sorting a defaultdict by value in python", "rewritten_intent": "sorting a defaultdict `d` by value", "snippet": "sorted(list(d.items()), key=lambda k_v: k_v[1])", "question_id": 10194713 }, { "intent": "How to reliably open a file in the same directory as a Python script", "rewritten_intent": "open a file 'bundled-resource.jpg' in the same directory as a python script", "snippet": "f = open(os.path.join(__location__, 'bundled-resource.jpg'))", "question_id": 4060221 }, { "intent": "How do I convert LF to CRLF?", "rewritten_intent": "open the file 'words.txt' in 'rU' mode", "snippet": "f = open('words.txt', 'rU')", "question_id": 13954840 }, { "intent": "Divide the values of two dictionaries in python", "rewritten_intent": "divide the values with same keys of two dictionary `d1` and `d2`", "snippet": "{k: (float(d2[k]) / d1[k]) for k in d2}", "question_id": 11840111 }, { "intent": "Divide the values of two dictionaries in python", "rewritten_intent": "divide the value for each key `k` in dict `d2` by the value for the same key `k` in dict `d1`", "snippet": "{k: (d2[k] / d1[k]) for k in list(d1.keys()) & d2}", "question_id": 11840111 }, { "intent": "Divide the values of two dictionaries in python", "rewritten_intent": "divide values associated with each key in dictionary `d1` from values associated with the same key in dictionary `d2`", "snippet": "dict((k, float(d2[k]) / d1[k]) for k in d2)", "question_id": 11840111 }, { "intent": "How to specify date format when using pandas.to_csv?", "rewritten_intent": "write dataframe `df` to csv file `filename` with dates formatted as yearmonthday `%Y%m%d`", "snippet": "df.to_csv(filename, date_format='%Y%m%d')", "question_id": 13999850 }, { "intent": "How to remove a key from a python dictionary?", "rewritten_intent": "remove a key 'key' from a dictionary `my_dict`", "snippet": "my_dict.pop('key', None)", "question_id": 11277432 }, { "intent": "replace values in an array", "rewritten_intent": "replace NaN values in array `a` with zeros", "snippet": "b = np.where(np.isnan(a), 0, a)", "question_id": 1800187 }, { "intent": "Python, running command line tools in parallel", "rewritten_intent": "subprocess run command 'start command -flags arguments' through the shell", "snippet": "subprocess.call('start command -flags arguments', shell=True)", "question_id": 9554544 }, { "intent": "Python, running command line tools in parallel", "rewritten_intent": "run command 'command -flags arguments &' on command line tools as separate processes", "snippet": "subprocess.call('command -flags arguments &', shell=True)", "question_id": 9554544 }, { "intent": "Passing the '+' character in a POST request in Python", "rewritten_intent": "replace percent-encoded code in request `f` to their single-character equivalent", "snippet": "f = urllib.request.urlopen(url, urllib.parse.unquote(urllib.parse.urlencode(params)))", "question_id": 12527959 }, { "intent": "How do I remove whitespace from the end of a string in Python?", "rewritten_intent": "remove white spaces from the end of string \" xyz \"", "snippet": "\"\"\" xyz \"\"\".rstrip()", "question_id": 2372573 }, { "intent": "URL encoding in python", "rewritten_intent": "Replace special characters in utf-8 encoded string `s` using the %xx escape", "snippet": "urllib.parse.quote(s.encode('utf-8'))", "question_id": 8905864 }, { "intent": "URL encoding in python", "rewritten_intent": null, "snippet": "urllib.parse.quote_plus('a b')", "question_id": 8905864 }, { "intent": "Convert string to numpy array", "rewritten_intent": "Create an array containing the conversion of string '100110' into separate elements", "snippet": "np.array(map(int, '100110'))", "question_id": 28207743 }, { "intent": "Convert string to numpy array", "rewritten_intent": "convert a string 'mystr' to numpy array of integer values", "snippet": "print(np.array(list(mystr), dtype=int))", "question_id": 28207743 }, { "intent": "How can I convert an RGB image into grayscale in Python?", "rewritten_intent": "convert an rgb image 'messi5.jpg' into grayscale `img`", "snippet": "img = cv2.imread('messi5.jpg', 0)", "question_id": 12201577 }, { "intent": "sorting a graph by its edge weight. python", "rewritten_intent": "sort list `lst` in descending order based on the second item of each tuple in it", "snippet": "lst.sort(key=lambda x: x[2], reverse=True)", "question_id": 11584773 }, { "intent": "How to find all occurrences of an element in a list?", "rewritten_intent": null, "snippet": "indices = [i for i, x in enumerate(my_list) if x == 'whatever']", "question_id": 6294179 }, { "intent": "How can I execute shell command with a | pipe in it", "rewritten_intent": "execute shell command 'grep -r PASSED *.log | sort -u | wc -l' with a | pipe in it", "snippet": "subprocess.call('grep -r PASSED *.log | sort -u | wc -l', shell=True)", "question_id": 18050937 }, { "intent": "How to count the number of a specific character at the end of a string ignoring duplicates?", "rewritten_intent": "count the number of trailing question marks in string `my_text`", "snippet": "len(my_text) - len(my_text.rstrip('?'))", "question_id": 42178481 }, { "intent": "converting currency with $ to numbers in Python pandas", "rewritten_intent": "remove dollar sign '$' from second to last column data in dataframe 'df' and convert the data into floats", "snippet": "df[df.columns[1:]].replace('[\\\\$,]', '', regex=True).astype(float)", "question_id": 32464280 }, { "intent": "Conditionally fill a column of a pandas df with values of a different df", "rewritten_intent": "Merge column 'word' in dataframe `df2` with column 'word' on dataframe `df1`", "snippet": "df1.merge(df2, how='left', on='word')", "question_id": 42060144 }, { "intent": "Switch every pair of characters in a string", "rewritten_intent": "switch positions of each two adjacent characters in string `a`", "snippet": "print(''.join(''.join(i) for i in zip(a2, a1)) + a[-1] if len(a) % 2 else '')", "question_id": 30628176 }, { "intent": "How to make a window jump to the front?", "rewritten_intent": "make a window `root` jump to the front", "snippet": "root.attributes('-topmost', True)", "question_id": 1892339 }, { "intent": "How to make a window jump to the front?", "rewritten_intent": "make a window `root` jump to the front", "snippet": "root.lift()", "question_id": 1892339 }, { "intent": "Elegant way to convert list to hex string", "rewritten_intent": "Convert list of booleans `walls` into a hex string", "snippet": "hex(int(''.join([str(int(b)) for b in walls]), 2))", "question_id": 17731822 }, { "intent": "Elegant way to convert list to hex string", "rewritten_intent": "convert the sum of list `walls` into a hex presentation", "snippet": "hex(sum(b << i for i, b in enumerate(reversed(walls))))", "question_id": 17731822 }, { "intent": "Print multiple arguments in python", "rewritten_intent": "print the string `Total score for`, the value of the variable `name`, the string `is` and the value of the variable `score` in one print call.", "snippet": "print(('Total score for', name, 'is', score))", "question_id": 15286401 }, { "intent": "Print multiple arguments in python", "rewritten_intent": "print multiple arguments 'name' and 'score'.", "snippet": "print('Total score for {} is {}'.format(name, score))", "question_id": 15286401 }, { "intent": "Print multiple arguments in python", "rewritten_intent": "print a string using multiple strings `name` and `score`", "snippet": "print('Total score for %s is %s ' % (name, score))", "question_id": 15286401 }, { "intent": "Print multiple arguments in python", "rewritten_intent": "print string including multiple variables `name` and `score`", "snippet": "print(('Total score for', name, 'is', score))", "question_id": 15286401 }, { "intent": "Is it possible to serve a static html page at the root of a django project?", "rewritten_intent": "serve a static html page 'your_template.html' at the root of a django project", "snippet": "url('^$', TemplateView.as_view(template_name='your_template.html'))", "question_id": 30650254 }, { "intent": "use a list of values to select rows from a pandas dataframe", "rewritten_intent": "use a list of values `[3,6]` to select rows from a pandas dataframe `df`'s column 'A'", "snippet": "df[df['A'].isin([3, 6])]", "question_id": 12096252 }, { "intent": "How to get the concrete class name as a string?", "rewritten_intent": null, "snippet": "instance.__class__.__name__", "question_id": 521502 }, { "intent": "How can I execute Python code in a virtualenv from Matlab", "rewritten_intent": "execute python code `myscript.py` in a virtualenv `/path/to/my/venv` from matlab", "snippet": "system('/path/to/my/venv/bin/python myscript.py')", "question_id": 39538010 }, { "intent": "django models selecting single field", "rewritten_intent": "django return a QuerySet list containing the values of field 'eng_name' in model `Employees`", "snippet": "Employees.objects.values_list('eng_name', flat=True)", "question_id": 7503241 }, { "intent": "Python regex findall alternation behavior", "rewritten_intent": "find all digits in string '6,7)' and put them to a list", "snippet": "re.findall('\\\\d|\\\\d,\\\\d\\\\)', '6,7)')", "question_id": 31465002 }, { "intent": "How do I make python to wait for a pressed key", "rewritten_intent": "prompt string 'Press Enter to continue...' to the console", "snippet": "input('Press Enter to continue...')", "question_id": 983354 }, { "intent": "Print string as hex literal python", "rewritten_intent": "print string \"ABC\" as hex literal", "snippet": "\"\"\"\u0001ABC\"\"\".encode('hex')", "question_id": 21947035 }, { "intent": "python + pymongo: how to insert a new field on an existing document in mongo from a for loop", "rewritten_intent": "insert a new field 'geolocCountry' on an existing document 'b' using pymongo", "snippet": "db.Doc.update({'_id': b['_id']}, {'$set': {'geolocCountry': myGeolocCountry}})", "question_id": 15666169 }, { "intent": "Regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc", "rewritten_intent": "Write a regex statement to match 'lol' to 'lolllll'.", "snippet": "re.sub('l+', 'l', 'lollll')", "question_id": 3895874 }, { "intent": "Getting the nth element using BeautifulSoup", "rewritten_intent": "BeautifulSoup find all 'tr' elements in HTML string `soup` at the five stride starting from the fourth element", "snippet": "rows = soup.findAll('tr')[4::5]", "question_id": 8724352 }, { "intent": "Reverse Y-Axis in PyPlot", "rewritten_intent": "reverse all x-axis points in pyplot", "snippet": "plt.gca().invert_xaxis()", "question_id": 2051744 }, { "intent": "Reverse Y-Axis in PyPlot", "rewritten_intent": "reverse y-axis in pyplot", "snippet": "plt.gca().invert_yaxis()", "question_id": 2051744 }, { "intent": "How do I stack two DataFrames next to each other in Pandas?", "rewritten_intent": "stack two dataframes next to each other in pandas", "snippet": "pd.concat([GOOG, AAPL], keys=['GOOG', 'AAPL'], axis=1)", "question_id": 13079852 }, { "intent": "Creating a JSON response using Django and Python", "rewritten_intent": "create a json response `response_data`", "snippet": "return HttpResponse(json.dumps(response_data), content_type='application/json')", "question_id": 2428092 }, { "intent": "Process escape sequences in a string", "rewritten_intent": "decode escape sequences in string `myString`", "snippet": "myString.decode('string_escape')", "question_id": 4020539 }, { "intent": "How do I calculate the md5 checksum of a file in Python?", "rewritten_intent": "calculate the md5 checksum of a file named 'filename.exe'", "snippet": "hashlib.md5(open('filename.exe', 'rb').read()).hexdigest()", "question_id": 16874598 }, { "intent": "Finding key from value in Python dictionary:", "rewritten_intent": "Find all keys from a dictionary `d` whose values are `desired_value`", "snippet": "[k for k, v in d.items() if v == desired_value]", "question_id": 7657457 }, { "intent": "Extract all keys from a list of dictionaries", "rewritten_intent": "create a set containing all keys' names from dictionary `LoD`", "snippet": "{k for d in LoD for k in list(d.keys())}", "question_id": 11399384 }, { "intent": "Extract all keys from a list of dictionaries", "rewritten_intent": "create a set containing all keys names from list of dictionaries `LoD`", "snippet": "set([i for s in [list(d.keys()) for d in LoD] for i in s])", "question_id": 11399384 }, { "intent": "Extract all keys from a list of dictionaries", "rewritten_intent": "extract all keys from a list of dictionaries `LoD`", "snippet": "[i for s in [list(d.keys()) for d in LoD] for i in s]", "question_id": 11399384 }, { "intent": "Is there a more elegant way for unpacking keys and values of a dictionary into two lists, without losing consistence?", "rewritten_intent": "unpack keys and values of a dictionary `d` into two lists", "snippet": "keys, values = zip(*list(d.items()))", "question_id": 6612769 }, { "intent": "Convert a string to integer with decimal in Python", "rewritten_intent": "convert a string `s` containing a decimal to an integer", "snippet": "int(Decimal(s))", "question_id": 1094717 }, { "intent": "Convert a string to integer with decimal in Python", "rewritten_intent": null, "snippet": "int(s.split('.')[0])", "question_id": 1094717 }, { "intent": "Numpy: How to check if array contains certain numbers?", "rewritten_intent": "check if array `b` contains all elements of array `a`", "snippet": "numpy.in1d(b, a).all()", "question_id": 10565598 }, { "intent": "Numpy: How to check if array contains certain numbers?", "rewritten_intent": "numpy: check if array 'a' contains all the numbers in array 'b'.", "snippet": "numpy.array([(x in a) for x in b])", "question_id": 10565598 }, { "intent": "Node labels using networkx", "rewritten_intent": "Draw node labels `labels` on networkx graph `G ` at position `pos`", "snippet": "networkx.draw_networkx_labels(G, pos, labels)", "question_id": 15548506 }, { "intent": "How to make a copy of a 2D array in Python?", "rewritten_intent": "make a row-by-row copy `y` of array `x`", "snippet": "y = [row[:] for row in x]", "question_id": 6532881 }, { "intent": "Pythonic way to populate numpy array", "rewritten_intent": "Create 2D numpy array from the data provided in 'somefile.csv' with each row in the file having same number of values", "snippet": "X = numpy.loadtxt('somefile.csv', delimiter=',')", "question_id": 7356042 }, { "intent": "Check if a Python list item contains a string inside another string", "rewritten_intent": "get a list of items from the list `some_list` that contain string 'abc'", "snippet": "matching = [s for s in some_list if 'abc' in s]", "question_id": 4843158 }, { "intent": "How to write/read a Pandas DataFrame with MultiIndex from/to an ASCII file?", "rewritten_intent": "export a pandas data frame `df` to a file `mydf.tsv` and retain the indices", "snippet": "df.to_csv('mydf.tsv', sep='\\t')", "question_id": 11041411 }, { "intent": "How do I create a LIST of unique random numbers?", "rewritten_intent": null, "snippet": "random.sample(list(range(100)), 10)", "question_id": 9755538 }, { "intent": "Splitting on last delimiter in Python string?", "rewritten_intent": "split a string `s` on last delimiter", "snippet": "s.rsplit(',', 1)", "question_id": 15012228 }, { "intent": "Python check if all elements of a list are the same type", "rewritten_intent": "Check if all elements in list `lst` are tupples of long and int", "snippet": "all(isinstance(x, int) for x in lst)", "question_id": 13252333 }, { "intent": "Python check if all elements of a list are the same type", "rewritten_intent": "check if all elements in a list 'lst' are the same type 'int'", "snippet": "all(isinstance(x, int) for x in lst)", "question_id": 13252333 }, { "intent": "Python . How to get rid of '\\r' in string?", "rewritten_intent": "strip a string `line` of all carriage returns and newlines", "snippet": "line.strip()", "question_id": 13656519 }, { "intent": "How can I scroll a web page using selenium webdriver in python?", "rewritten_intent": "scroll to the bottom of a web page using selenium webdriver", "snippet": "driver.execute_script('window.scrollTo(0, Y)')", "question_id": 20986631 }, { "intent": "How can I scroll a web page using selenium webdriver in python?", "rewritten_intent": "scroll a to the bottom of a web page using selenium webdriver", "snippet": "driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')", "question_id": 20986631 }, { "intent": "How do I convert a datetime.date object into datetime.datetime in python?", "rewritten_intent": "convert Date object `dateobject` into a DateTime object", "snippet": "datetime.datetime.combine(dateobject, datetime.time())", "question_id": 11619169 }, { "intent": "How to check if one of the following items is in a list?", "rewritten_intent": "check if any item from list `b` is in list `a`", "snippet": "print(any(x in a for x in b))", "question_id": 740287 }, { "intent": "Saving a Numpy array as an image", "rewritten_intent": "save a numpy array `image_array` as an image 'outfile.jpg'", "snippet": "scipy.misc.imsave('outfile.jpg', image_array)", "question_id": 902761 }, { "intent": "Regex for removing data in parenthesis", "rewritten_intent": "Remove anything in parenthesis from string `item` with a regex", "snippet": "item = re.sub(' ?\\\\([^)]+\\\\)', '', item)", "question_id": 19794051 }, { "intent": "Regex for removing data in parenthesis", "rewritten_intent": "Remove word characters in parenthesis from string `item` with a regex", "snippet": "item = re.sub(' ?\\\\(\\\\w+\\\\)', '', item)", "question_id": 19794051 }, { "intent": "Regex for removing data in parenthesis", "rewritten_intent": "Remove all data inside parenthesis in string `item`", "snippet": "item = re.sub(' \\\\(\\\\w+\\\\)', '', item)", "question_id": 19794051 }, { "intent": "Checking if any elements in one list are in another", "rewritten_intent": "check if any elements in one list `list1` are in another list `list2`", "snippet": "len(set(list1).intersection(list2)) > 0", "question_id": 16138015 }, { "intent": "convert hex to decimal", "rewritten_intent": "convert hex string `s` to decimal", "snippet": "i = int(s, 16)", "question_id": 9210525 }, { "intent": "convert hex to decimal", "rewritten_intent": "convert hex string \"0xff\" to decimal", "snippet": "int('0xff', 16)", "question_id": 9210525 }, { "intent": "convert hex to decimal", "rewritten_intent": "convert hex string \"FFFF\" to decimal", "snippet": "int('FFFF', 16)", "question_id": 9210525 }, { "intent": "convert hex to decimal", "rewritten_intent": "convert hex string '0xdeadbeef' to decimal", "snippet": "ast.literal_eval('0xdeadbeef')", "question_id": 9210525 }, { "intent": "convert hex to decimal", "rewritten_intent": "convert hex string 'deadbeef' to decimal", "snippet": "int('deadbeef', 16)", "question_id": 9210525 }, { "intent": "Take screenshot in Python on Mac OS X", "rewritten_intent": "take screenshot 'screen.png' on mac os x", "snippet": "os.system('screencapture screen.png')", "question_id": 4524723 }, { "intent": "How to set window size using phantomjs and selenium webdriver in python", "rewritten_intent": "Set a window size to `1400, 1000` using selenium webdriver", "snippet": "driver.set_window_size(1400, 1000)", "question_id": 21899953 }, { "intent": "Replace non-ascii chars from a unicode string in Python", "rewritten_intent": "replace non-ascii chars from a unicode string u'm\\xfasica'", "snippet": "unicodedata.normalize('NFKD', 'm\\xfasica').encode('ascii', 'ignore')", "question_id": 3704731 }, { "intent": "Pandas/Python: How to concatenate two dataframes without duplicates?", "rewritten_intent": "concatenate dataframe `df1` with `df2` whilst removing duplicates", "snippet": "pandas.concat([df1, df2]).drop_duplicates().reset_index(drop=True)", "question_id": 21317384 }, { "intent": "numpy: efficiently reading a large array", "rewritten_intent": "Construct an array with data type float32 `a` from data in binary file 'filename'", "snippet": "a = numpy.fromfile('filename', dtype=numpy.float32)", "question_id": 4365964 }, { "intent": "How to use the mv command in Python with subprocess", "rewritten_intent": "execute a mv command `mv /home/somedir/subdir/* somedir/` in subprocess", "snippet": "subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)", "question_id": 21804935 }, { "intent": "How to use the mv command in Python with subprocess", "rewritten_intent": null, "snippet": "subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)", "question_id": 21804935 }, { "intent": "How to use Unicode characters in a python string", "rewritten_intent": "print a character that has unicode value `\\u25b2`", "snippet": "print('\\u25b2'.encode('utf-8'))", "question_id": 16658068 }, { "intent": "Comparing two .txt files using difflib in Python", "rewritten_intent": "compare contents at filehandles `file1` and `file2` using difflib", "snippet": "difflib.SequenceMatcher(None, file1.read(), file2.read())", "question_id": 977491 }, { "intent": "Creating a dictionary from a string", "rewritten_intent": "Create a dictionary from string `e` separated by `-` and `,`", "snippet": "dict((k, int(v)) for k, v in (e.split(' - ') for e in s.split(',')))", "question_id": 4627981 }, { "intent": "How to check if all elements in a tuple or list are in another?", "rewritten_intent": "check if all elements in a tuple `(1, 6)` are in another `(1, 2, 3, 4, 5)`", "snippet": "all(i in (1, 2, 3, 4, 5) for i in (1, 6))", "question_id": 34468983 }, { "intent": "python pandas extract unique dates from time series", "rewritten_intent": "extract unique dates from time series 'Date' in dataframe `df`", "snippet": "df['Date'].map(lambda t: t.date()).unique()", "question_id": 14673394 }, { "intent": "Formatting text to be justified in Python 3.3 with .format() method", "rewritten_intent": "right align string `mystring` with a width of 7", "snippet": "\"\"\"{:>7s}\"\"\".format(mystring)", "question_id": 16159228 }, { "intent": "How do I read an Excel file into Python using xlrd? Can it read newer Office formats?", "rewritten_intent": "read an excel file 'ComponentReport-DJI.xls'", "snippet": "open('ComponentReport-DJI.xls', 'rb').read(200)", "question_id": 118516 }, { "intent": "How to sort a dataFrame in python pandas by two or more columns?", "rewritten_intent": "sort dataframe `df` based on column 'b' in ascending and column 'c' in descending", "snippet": "df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)", "question_id": 17141558 }, { "intent": "How to sort a dataFrame in python pandas by two or more columns?", "rewritten_intent": "sort dataframe `df` based on column 'a' in ascending and column 'b' in descending", "snippet": "df.sort_values(['a', 'b'], ascending=[True, False])", "question_id": 17141558 }, { "intent": "How to sort a dataFrame in python pandas by two or more columns?", "rewritten_intent": "sort a pandas data frame with column `a` in ascending and `b` in descending order", "snippet": "df1.sort(['a', 'b'], ascending=[True, False], inplace=True)", "question_id": 17141558 }, { "intent": "How to sort a dataFrame in python pandas by two or more columns?", "rewritten_intent": "sort a pandas data frame by column `a` in ascending, and by column `b` in descending order", "snippet": "df.sort(['a', 'b'], ascending=[True, False])", "question_id": 17141558 }, { "intent": "Django redirect to root from a view", "rewritten_intent": "django redirect to view 'Home.views.index'", "snippet": "redirect('Home.views.index')", "question_id": 7284952 }, { "intent": "Remove all values within one list from another list in python", "rewritten_intent": "remove all values within one list `[2, 3, 7]` from another list `a`", "snippet": "[x for x in a if x not in [2, 3, 7]]", "question_id": 2514961 }, { "intent": "How to remove all the punctuation in a string? (Python)", "rewritten_intent": "remove the punctuation '!', '.', ':' from a string `asking`", "snippet": "out = ''.join(c for c in asking if c not in ('!', '.', ':'))", "question_id": 16050952 }, { "intent": "Python: BeautifulSoup - get an attribute value based on the name attribute", "rewritten_intent": "BeautifulSoup get value associated with attribute 'content' where attribute 'name' is equal to 'City' in tag 'meta' in HTML parsed string `soup`", "snippet": "soup.find('meta', {'name': 'City'})['content']", "question_id": 11205386 }, { "intent": "How to unquote a urlencoded unicode string in python?", "rewritten_intent": "unquote a urlencoded unicode string '%0a'", "snippet": "urllib.parse.unquote('%0a')", "question_id": 300445 }, { "intent": "How to unquote a urlencoded unicode string in python?", "rewritten_intent": "decode url `url` from UTF-16 code to UTF-8 code", "snippet": "urllib.parse.unquote(url).decode('utf8')", "question_id": 300445 }, { "intent": "empty a list", "rewritten_intent": "empty a list `lst`", "snippet": "del lst[:]", "question_id": 1400608 }, { "intent": "empty a list", "rewritten_intent": "empty a list `lst`", "snippet": "del lst1[:]", "question_id": 1400608 }, { "intent": "empty a list", "rewritten_intent": "empty a list `lst`", "snippet": "lst[:] = []", "question_id": 1400608 }, { "intent": "empty a list", "rewritten_intent": "empty a list `alist`", "snippet": "alist[:] = []", "question_id": 1400608 }, { "intent": "Pandas reset index on series to remove multiindex", "rewritten_intent": "reset index of series `s`", "snippet": "s.reset_index(0).reset_index(drop=True)", "question_id": 18624039 }, { "intent": "How to convert unicode text to normal text", "rewritten_intent": "convert unicode text from list `elems` with index 0 to normal text 'utf-8'", "snippet": "elems[0].getText().encode('utf-8')", "question_id": 36623789 }, { "intent": "Subtracting the current and previous item in a list", "rewritten_intent": "create a list containing the subtraction of each item in list `L` from the item prior to it", "snippet": "[(y - x) for x, y in zip(L, L[1:])]", "question_id": 4029436 }, { "intent": "Cleanest way to get a value from a list element", "rewritten_intent": "get value in string `line` matched by regex pattern '\\\\bLOG_ADDR\\\\s+(\\\\S+)'", "snippet": "print(re.search('\\\\bLOG_ADDR\\\\s+(\\\\S+)', line).group(1))", "question_id": 32950347 }, { "intent": "Importing everything ( * ) dynamically from a module", "rewritten_intent": "import all classes from module `some.package`", "snippet": "globals().update(importlib.import_module('some.package').__dict__)", "question_id": 4116061 }, { "intent": "Convert a list of characters into a string", "rewritten_intent": "convert a list of characters `['a', 'b', 'c', 'd']` into a string", "snippet": "\"\"\"\"\"\".join(['a', 'b', 'c', 'd'])", "question_id": 4481724 }, { "intent": "Slicing URL with Python", "rewritten_intent": "Slice `url` with '&' as delimiter to get \"http://www.domainname.com/page?CONTENT_ITEM_ID=1234\" from url \"http://www.domainname.com/page?CONTENT_ITEM_ID=1234¶m2¶m3\r\n\"", "snippet": "url.split('&')", "question_id": 258746 }, { "intent": "sort a dictionary by key", "rewritten_intent": "sort dictionary `d` by key", "snippet": "od = collections.OrderedDict(sorted(d.items()))", "question_id": 9001509 }, { "intent": "sort a dictionary by key", "rewritten_intent": "sort a dictionary `d` by key", "snippet": "OrderedDict(sorted(list(d.items()), key=(lambda t: t[0])))", "question_id": 9001509 }, { "intent": "PUT Request to REST API using Python", "rewritten_intent": "Execute a put request to the url `url`", "snippet": "response = requests.put(url, data=json.dumps(data), headers=headers)", "question_id": 33127636 }, { "intent": "Python remove anything that is not a letter or number", "rewritten_intent": "replace everything that is not an alphabet or a digit with '' in 's'.", "snippet": "re.sub('[\\\\W_]+', '', s)", "question_id": 6323296 }, { "intent": "Python Nested List Comprehension with two Lists", "rewritten_intent": "create a list of aggregation of each element from list `l2` to all elements of list `l1`", "snippet": "[(x + y) for x in l2 for y in l1]", "question_id": 16568056 }, { "intent": "convert string to dict using list comprehension in python", "rewritten_intent": "convert string `x' to dictionary splitted by `=` using list comprehension", "snippet": "dict([x.split('=') for x in s.split()])", "question_id": 1246444 }, { "intent": "Remove object from a list of objects in python", "rewritten_intent": "remove index 2 element from a list `my_list`", "snippet": "my_list.pop(2)", "question_id": 9754729 }, { "intent": "How to delete a character from a string using python?", "rewritten_intent": "Delete character \"M\" from a string `s` using python", "snippet": "s = s.replace('M', '')", "question_id": 3559559 }, { "intent": "How to delete a character from a string using python?", "rewritten_intent": null, "snippet": "newstr = oldstr.replace('M', '')", "question_id": 3559559 }, { "intent": "How can I sum the product of two list items using for loop in python?", "rewritten_intent": "get the sum of the products of each pair of corresponding elements in lists `a` and `b`", "snippet": "sum(x * y for x, y in zip(a, b))", "question_id": 41821112 }, { "intent": "How can I sum the product of two list items using for loop in python?", "rewritten_intent": "sum the products of each two elements at the same index of list `a` and list `b`", "snippet": "list(x * y for x, y in list(zip(a, b)))", "question_id": 41821112 }, { "intent": "How can I sum the product of two list items using for loop in python?", "rewritten_intent": "sum the product of each two items at the same index of list `a` and list `b`", "snippet": "sum(i * j for i, j in zip(a, b))", "question_id": 41821112 }, { "intent": "How can I sum the product of two list items using for loop in python?", "rewritten_intent": "sum the product of elements of two lists named `a` and `b`", "snippet": "sum(x * y for x, y in list(zip(a, b)))", "question_id": 41821112 }, { "intent": "Can I read and write file in one line with Python?", "rewritten_intent": "write the content of file `xxx.mp4` to file `f`", "snippet": "f.write(open('xxx.mp4', 'rb').read())", "question_id": 12426043 }, { "intent": "How to add an integer to each element in a list?", "rewritten_intent": "Add 1 to each integer value in list `my_list`", "snippet": "new_list = [(x + 1) for x in my_list]", "question_id": 9304408 }, { "intent": "Return list of items in list greater than some value", "rewritten_intent": "get a list of all items in list `j` with values greater than `5`", "snippet": "[x for x in j if x >= 5]", "question_id": 4587915 }, { "intent": "matplotlib: Set markers for individual points on a line", "rewritten_intent": "set color marker styles `--bo` in matplotlib", "snippet": "plt.plot(list(range(10)), '--bo')", "question_id": 8409095 }, { "intent": "matplotlib: Set markers for individual points on a line", "rewritten_intent": "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)", "snippet": "plt.plot(list(range(10)), linestyle='--', marker='o', color='b')", "question_id": 8409095 }, { "intent": "split elements of a list in python", "rewritten_intent": "split strings in list `l` on the first occurring tab `\\t` and enter only the first resulting substring in a new list", "snippet": "[i.split('\\t', 1)[0] for i in l]", "question_id": 6696027 }, { "intent": "split elements of a list in python", "rewritten_intent": "Split each string in list `myList` on the tab character", "snippet": "myList = [i.split('\\t')[0] for i in myList]", "question_id": 6696027 }, { "intent": "Summing elements in a list", "rewritten_intent": "Sum numbers in a list 'your_list'", "snippet": "sum(your_list)", "question_id": 11344827 }, { "intent": "How to attach debugger to a python subproccess?", "rewritten_intent": "attach debugger pdb to class `ForkedPdb`", "snippet": "ForkedPdb().set_trace()", "question_id": 4716533 }, { "intent": "Python: comprehension to compose two dictionaries", "rewritten_intent": "Compose keys from dictionary `d1` with respective values in dictionary `d2`", "snippet": "result = {k: d2.get(v) for k, v in list(d1.items())}", "question_id": 17846545 }, { "intent": "datetime.datetime.now() + 1", "rewritten_intent": "add one day and three hours to the present time from datetime.now()", "snippet": "datetime.datetime.now() + datetime.timedelta(days=1, hours=3)", "question_id": 6310475 }, { "intent": "Convert binary string to list of integers using Python", "rewritten_intent": null, "snippet": "[int(s[i:i + 3], 2) for i in range(0, len(s), 3)]", "question_id": 1386811 }, { "intent": "switching keys and values in a dictionary in python", "rewritten_intent": "switch keys and values in a dictionary `my_dict`", "snippet": "dict((v, k) for k, v in my_dict.items())", "question_id": 8305518 }, { "intent": "Specific sort a list of numbers separated by dots", "rewritten_intent": "sort a list `L` by number after second '.'", "snippet": "print(sorted(L, key=lambda x: int(x.split('.')[2])))", "question_id": 21361604 }, { "intent": "How to find a value in a list of python dictionaries?", "rewritten_intent": "Check if the value of the key \"name\" is \"Test\" in a list of dictionaries `label`", "snippet": "any(d['name'] == 'Test' for d in label)", "question_id": 17149561 }, { "intent": "How can I remove all instances of an element from a list in Python?", "rewritten_intent": "remove all instances of [1, 1] from list `a`", "snippet": "a[:] = [x for x in a if x != [1, 1]]", "question_id": 2186656 }, { "intent": "How can I remove all instances of an element from a list in Python?", "rewritten_intent": "remove all instances of `[1, 1]` from a list `a`", "snippet": "[x for x in a if x != [1, 1]]", "question_id": 2186656 }, { "intent": "Convert a list to a dictionary in Python", "rewritten_intent": "convert a list 'a' to a dictionary where each even element represents the key to the dictionary, and the following odd element is the value", "snippet": "b = {a[i]: a[i + 1] for i in range(0, len(a), 2)}", "question_id": 4576115 }, { "intent": "How to check whether elements appears in the list only once in python?", "rewritten_intent": "check whether elements in list `a` appear only once", "snippet": "len(set(a)) == len(a)", "question_id": 3899782 }, { "intent": "Generating an MD5 checksum of a file", "rewritten_intent": "Generate MD5 checksum of file in the path `full_path` in hashlib", "snippet": "print(hashlib.md5(open(full_path, 'rb').read()).hexdigest())", "question_id": 3431825 }, { "intent": "How to sort a dictionary in python by value when the value is a list and I want to sort it by the first index of that list", "rewritten_intent": null, "snippet": "sorted(list(data.items()), key=lambda x: x[1][0])", "question_id": 42765620 }, { "intent": "Pythons fastest way of randomising case of a string", "rewritten_intent": "randomly switch letters' cases in string `s`", "snippet": "\"\"\"\"\"\".join(x.upper() if random.randint(0, 1) else x for x in s)", "question_id": 8344905 }, { "intent": "How to force os.system() to use bash instead of shell", "rewritten_intent": "force bash interpreter '/bin/bash' to be used instead of shell", "snippet": "os.system('GREPDB=\"echo 123\"; /bin/bash -c \"$GREPDB\"')", "question_id": 21822054 }, { "intent": "How to force os.system() to use bash instead of shell", "rewritten_intent": "Run a command `echo hello world` in bash instead of shell", "snippet": "os.system('/bin/bash -c \"echo hello world\"')", "question_id": 21822054 }, { "intent": "how to access the class variable by string in Python?", "rewritten_intent": "access the class variable `a_string` from a class object `test`", "snippet": "getattr(test, a_string)", "question_id": 13303100 }, { "intent": "How to display a jpg file in Python?", "rewritten_intent": "Display a image file `pathToFile`", "snippet": "Image.open('pathToFile').show()", "question_id": 5333244 }, { "intent": "Replace the single quote (') character from a string", "rewritten_intent": "replace single quote character in string \"didn't\" with empty string ''", "snippet": "\"\"\"didn't\"\"\".replace(\"'\", '')", "question_id": 3151146 }, { "intent": "Sorting files in a list", "rewritten_intent": "sort list `files` based on variable `file_number`", "snippet": "files.sort(key=file_number)", "question_id": 9466017 }, { "intent": "remove all whitespace in a string", "rewritten_intent": "remove all whitespace in a string `sentence`", "snippet": "sentence.replace(' ', '')", "question_id": 8270092 }, { "intent": "remove all whitespace in a string", "rewritten_intent": "remove all whitespace in a string `sentence`", "snippet": "pattern = re.compile('\\\\s+')\nsentence = re.sub(pattern, '', sentence)", "question_id": 8270092 }, { "intent": "remove all whitespace in a string", "rewritten_intent": "remove whitespace in string `sentence` from beginning and end", "snippet": "sentence.strip()", "question_id": 8270092 }, { "intent": "remove all whitespace in a string", "rewritten_intent": "remove all whitespaces in string `sentence`", "snippet": "sentence = re.sub('\\\\s+', '', sentence, flags=re.UNICODE)", "question_id": 8270092 }, { "intent": "remove all whitespace in a string", "rewritten_intent": "remove all whitespaces in a string `sentence`", "snippet": "sentence = ''.join(sentence.split())", "question_id": 8270092 }, { "intent": "Sum all values of a counter in Python", "rewritten_intent": "sum all the values in a counter variable `my_counter`", "snippet": "sum(my_counter.values())", "question_id": 32511444 }, { "intent": "Numpy: find the euclidean distance between two 3-D arrays", "rewritten_intent": "find the euclidean distance between two 3-d arrays `A` and `B`", "snippet": "np.sqrt(((A - B) ** 2).sum(-1))", "question_id": 40319433 }, { "intent": "Python: define multiple variables of same type?", "rewritten_intent": "create list `levels` containing 3 empty dictionaries", "snippet": "levels = [{}, {}, {}]", "question_id": 4411811 }, { "intent": "Find the sum of subsets of a list in python", "rewritten_intent": "find the sums of length 7 subsets of a list `daily`", "snippet": "weekly = [sum(visitors[x:x + 7]) for x in range(0, len(daily), 7)]", "question_id": 6133434 }, { "intent": "Delete an element from a dictionary", "rewritten_intent": "Delete an element `key` from a dictionary `d`", "snippet": "del d[key]", "question_id": 5844672 }, { "intent": "Delete an element from a dictionary", "rewritten_intent": "Delete an element 0 from a dictionary `a`", "snippet": "{i: a[i] for i in a if (i != 0)}", "question_id": 5844672 }, { "intent": "Delete an element from a dictionary", "rewritten_intent": "Delete an element \"hello\" from a dictionary `lol`", "snippet": "lol.pop('hello')", "question_id": 5844672 }, { "intent": "Delete an element from a dictionary", "rewritten_intent": "Delete an element with key `key` dictionary `r`", "snippet": "del r[key]", "question_id": 5844672 }, { "intent": "Efficient computation of the least-squares algorithm in NumPy", "rewritten_intent": "solve for the least squares' solution of matrices `a` and `b`", "snippet": "np.linalg.solve(np.dot(a.T, a), np.dot(a.T, b))", "question_id": 41648246 }, { "intent": "Splitting dictionary/list inside a Pandas Column into Separate Columns", "rewritten_intent": "split dictionary/list inside a pandas column 'b' into separate columns in dataframe `df`", "snippet": "pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)", "question_id": 38231591 }, { "intent": "loop through a Python list by twos", "rewritten_intent": "loop through 0 to 10 with step 2", "snippet": "for i in range(0, 10, 2):\n pass", "question_id": 2990121 }, { "intent": "loop through a Python list by twos", "rewritten_intent": "loop through `mylist` with step 2", "snippet": "for i in mylist[::2]:\n pass", "question_id": 2990121 }, { "intent": "How to use map to lowercase strings in a dictionary?", "rewritten_intent": "lowercase string values with key 'content' in a list of dictionaries `messages`", "snippet": "[{'content': x['content'].lower()} for x in messages]", "question_id": 42353686 }, { "intent": "convert list into string with spaces in python", "rewritten_intent": "convert a list `my_list` into string with values separated by spaces", "snippet": "\"\"\" \"\"\".join(my_list)", "question_id": 12309976 }, { "intent": "Regex. Match words that contain special characters or 'http://'", "rewritten_intent": "replace each occurrence of the pattern '(http://\\\\S+|\\\\S*[^\\\\w\\\\s]\\\\S*)' within `a` with ''", "snippet": "re.sub('(http://\\\\S+|\\\\S*[^\\\\w\\\\s]\\\\S*)', '', a)", "question_id": 4695143 }, { "intent": "How to check for palindrome using Python logic", "rewritten_intent": "check if string `str` is palindrome", "snippet": "str(n) == str(n)[::-1]", "question_id": 17331290 }, { "intent": "How to upload binary file with ftplib in Python?", "rewritten_intent": "upload binary file `myfile.txt` with ftplib", "snippet": "ftp.storbinary('STOR myfile.txt', open('myfile.txt', 'rb'))", "question_id": 2911754 }, { "intent": "How to remove all characters before a specific character in Python?", "rewritten_intent": "remove all characters from string `stri` upto character 'I'", "snippet": "re.sub('.*I', 'I', stri)", "question_id": 30945784 }, { "intent": "Python parse comma-separated number into int", "rewritten_intent": "parse a comma-separated string number '1,000,000' into int", "snippet": "int('1,000,000'.replace(',', ''))", "question_id": 2953746 }, { "intent": "Combine two Pandas dataframes with the same index", "rewritten_intent": "combine dataframe `df1` and dataframe `df2` by index number", "snippet": "pd.merge(df1, df2, left_index=True, right_index=True, how='outer')", "question_id": 28773683 }, { "intent": "Combine two Pandas dataframes with the same index", "rewritten_intent": null, "snippet": "pandas.concat([df1, df2], axis=1)", "question_id": 28773683 }, { "intent": "What's the best way to aggregate the boolean values of a Python dictionary?", "rewritten_intent": "check if all boolean values in a python dictionary `dict` are true", "snippet": "all(dict.values())", "question_id": 2806611 }, { "intent": "How to extract first two characters from string using regex", "rewritten_intent": "use regex pattern '^12(?=.{4}$)' to remove digit 12 if followed by 4 other digits in column `c_contofficeID` of dataframe `df`", "snippet": "df.c_contofficeID.str.replace('^12(?=.{4}$)', '')", "question_id": 40273313 }, { "intent": "reverse a list", "rewritten_intent": "reverse a list `L`", "snippet": "L[::(-1)]", "question_id": 3940128 }, { "intent": "reverse a list", "rewritten_intent": "reverse a list `array`", "snippet": "reversed(array)", "question_id": 3940128 }, { "intent": "reverse a list", "rewritten_intent": "reverse a list `L`", "snippet": "L.reverse()", "question_id": 3940128 }, { "intent": "reverse a list", "rewritten_intent": "reverse a list `array`", "snippet": "list(reversed(array))", "question_id": 3940128 }, { "intent": "How to index nested lists in Python?", "rewritten_intent": "get first element of each tuple in list `A`", "snippet": "[tup[0] for tup in A]", "question_id": 31302904 }, { "intent": "Replacing characters in a file", "rewritten_intent": "replace character 'a' with character 'e' and character 's' with character '3' in file `contents`", "snippet": "newcontents = contents.replace('a', 'e').replace('s', '3')", "question_id": 10562778 }, { "intent": "How to serialize SqlAlchemy result to JSON?", "rewritten_intent": "serialise SqlAlchemy RowProxy object `row` to a json object", "snippet": "json.dumps([dict(list(row.items())) for row in rs])", "question_id": 5022066 }, { "intent": "Cross-platform addressing of the config file", "rewritten_intent": "get file '~/foo.ini'", "snippet": "config_file = os.path.expanduser('~/foo.ini')", "question_id": 3227624 }, { "intent": "How to get multiple parameters with same name from a URL in Pylons?", "rewritten_intent": "get multiple parameters with same name from a url in pylons", "snippet": "request.params.getall('c')", "question_id": 14734750 }, { "intent": "how to create similarity matrix in numpy python?", "rewritten_intent": "Convert array `x` into a correlation matrix", "snippet": "np.corrcoef(x)", "question_id": 18432823 }, { "intent": "Python - Find the greatest number in a set of numbers", "rewritten_intent": "Find the greatest number in set `(1, 2, 3)`", "snippet": "print(max(1, 2, 3))", "question_id": 3090175 }, { "intent": "Google App Engine - Request class query_string", "rewritten_intent": "Retrieve parameter 'var_name' from a GET request.", "snippet": "self.request.get('var_name')", "question_id": 1391026 }, { "intent": "python pandas: apply a function with arguments to a series. Update", "rewritten_intent": "Add 100 to each element of column \"x\" in dataframe `a`", "snippet": "a['x'].apply(lambda x, y: x + y, args=(100,))", "question_id": 21188504 }, { "intent": "Get models ordered by an attribute that belongs to its OneToOne model", "rewritten_intent": "Django get first 10 records of model `User` ordered by criteria 'age' of model 'pet'", "snippet": "User.objects.order_by('-pet__age')[:10]", "question_id": 40079728 }, { "intent": "make a time delay", "rewritten_intent": "delay for \"5\" seconds", "snippet": "time.sleep(5)", "question_id": 510348 }, { "intent": "make a time delay", "rewritten_intent": "make a 60 seconds time delay", "snippet": "time.sleep(60)", "question_id": 510348 }, { "intent": "make a time delay", "rewritten_intent": "make a 0.1 seconds time delay", "snippet": "sleep(0.1)", "question_id": 510348 }, { "intent": "make a time delay", "rewritten_intent": "make a 60 seconds time delay", "snippet": "time.sleep(60)", "question_id": 510348 }, { "intent": "make a time delay", "rewritten_intent": "make a 0.1 seconds time delay", "snippet": "time.sleep(0.1)", "question_id": 510348 }, { "intent": "Remove strings from a list that contains numbers in python", "rewritten_intent": "From a list of strings `my_list`, remove the values that contains numbers.", "snippet": "[x for x in my_list if not any(c.isdigit() for c in x)]", "question_id": 16084642 }, { "intent": "how to do a left,right and mid of a string in a pandas dataframe", "rewritten_intent": "get the middle two characters of a string 'state' in a pandas dataframe `df`", "snippet": "df['state'].apply(lambda x: x[len(x) / 2 - 1:len(x) / 2 + 1])", "question_id": 20970279 }, { "intent": "How do I draw a grid onto a plot in Python?", "rewritten_intent": "draw a grid line on every tick of plot `plt`", "snippet": "plt.grid(True)", "question_id": 8209568 }, { "intent": "python How do you sort list by occurrence with out removing elements from the list?", "rewritten_intent": "sort list `lst` based on each element's number of occurrences", "snippet": "sorted(lst, key=lambda x: (-1 * c[x], lst.index(x)))", "question_id": 42394627 }, { "intent": "Find max length of each column in a list of lists", "rewritten_intent": "Get the value with the maximum length in each column in array `foo`", "snippet": "[max(len(str(x)) for x in line) for line in zip(*foo)]", "question_id": 6018916 }, { "intent": "Count the number of Occurrence of Values based on another column", "rewritten_intent": "get the count of each unique value in column `Country` of dataframe `df` and store in column `Sum of Accidents`", "snippet": "df.Country.value_counts().reset_index(name='Sum of Accidents')", "question_id": 39607540 }, { "intent": "Calculating difference between two rows in Python / Pandas", "rewritten_intent": "calculat the difference between each row and the row previous to it in dataframe `data`", "snippet": "data.set_index('Date').diff()", "question_id": 13114512 }, { "intent": "python: append values to a set", "rewritten_intent": "append values `[3, 4]` to a set `a`", "snippet": "a.update([3, 4])", "question_id": 3392354 }, { "intent": "How can I get an array of alternating values in python?", "rewritten_intent": "set every two-stride far element to -1 starting from second element in array `a`", "snippet": "a[1::2] = -1", "question_id": 7154739 }, { "intent": "Faster way to rank rows in subgroups in pandas dataframe", "rewritten_intent": "Get rank of rows from highest to lowest of dataframe `df`, grouped by value in column `group`, according to value in column `value`", "snippet": "df.groupby('group')['value'].rank(ascending=False)", "question_id": 26720916 }, { "intent": "Js Date object to python datetime", "rewritten_intent": "convert js date object 'Tue, 22 Nov 2011 06:00:00 GMT' to python datetime", "snippet": "datetime.strptime('Tue, 22 Nov 2011 06:00:00 GMT', '%a, %d %b %Y %H:%M:%S %Z')", "question_id": 8153631 }, { "intent": "Python: Converting from binary to String", "rewritten_intent": "Convert a binary value '1633837924' to string", "snippet": "struct.pack(' 2])", "question_id": 29471884 }, { "intent": "pandas: replace string with another string", "rewritten_intent": "Replace each value in column 'prod_type' of dataframe `df` with string 'responsive'", "snippet": "df['prod_type'] = 'responsive'", "question_id": 39602824 }, { "intent": "How do I sort a list with positives coming before negatives with values sorted respectively?", "rewritten_intent": "sort list `lst` with positives coming before negatives with values sorted respectively", "snippet": "sorted(lst, key=lambda x: (x < 0, x))", "question_id": 40620804 }, { "intent": "How do I calculate the date six months from the current date", "rewritten_intent": "get the date 6 months from today", "snippet": "six_months = (date.today() + relativedelta(months=(+ 6)))", "question_id": 546321 }, { "intent": "How do I calculate the date six months from the current date", "rewritten_intent": "get the date 1 month from today", "snippet": "(date(2010, 12, 31) + relativedelta(months=(+ 1)))", "question_id": 546321 }, { "intent": "How do I calculate the date six months from the current date", "rewritten_intent": "get the date 2 months from today", "snippet": "(date(2010, 12, 31) + relativedelta(months=(+ 2)))", "question_id": 546321 }, { "intent": "calculate the date six months from the current date", "rewritten_intent": "calculate the date six months from the current date", "snippet": "print((datetime.date.today() + datetime.timedelta(((6 * 365) / 12))).isoformat())", "question_id": 546321 }, { "intent": "Finding The Biggest Key In A Python Dictionary", "rewritten_intent": "get a list of keys of dictionary `things` sorted by the value of nested dictionary key 'weight'", "snippet": "sorted(list(things.keys()), key=lambda x: things[x]['weight'], reverse=True)", "question_id": 42352887 }, { "intent": "how to get all the values from a numpy array excluding a certain index?", "rewritten_intent": "get all the values from a numpy array `a` excluding index 3", "snippet": "a[np.arange(len(a)) != 3]", "question_id": 7429118 }, { "intent": "what is a quick way to delete all elements from a list that do not satisfy a constraint?", "rewritten_intent": "delete all elements from a list `x` if a function `fn` taking value as parameter returns `0`", "snippet": "[x for x in lst if fn(x) != 0]", "question_id": 3895424 }, { "intent": "Python Pandas - Date Column to Column index", "rewritten_intent": "set dataframe `df` index using column 'month'", "snippet": "df.set_index('month')", "question_id": 15752422 }, { "intent": "How to read lines from a file into a multidimensional array (or an array of lists) in python", "rewritten_intent": "read lines from a csv file `./urls-eu.csv` into a list of lists `arr`", "snippet": "arr = [line.split(',') for line in open('./urls-eu.csv')]", "question_id": 1532810 }, { "intent": "python list comprehension with multiple 'if's", "rewritten_intent": "list comprehension that produces integers between 11 and 19", "snippet": "[i for i in range(100) if i > 10 if i < 20]", "question_id": 15248272 }, { "intent": "Removing letters from a list of both numbers and letters", "rewritten_intent": "Get only digits from a string `strs`", "snippet": "\"\"\"\"\"\".join([c for c in strs if c.isdigit()])", "question_id": 18116235 }, { "intent": "splitting a string based on tab in the file", "rewritten_intent": "split a string `yas` based on tab '\\t'", "snippet": "re.split('\\\\t+', yas.rstrip('\\t'))", "question_id": 17038426 }, { "intent": "numpy matrix multiplication", "rewritten_intent": "scalar multiply matrix `a` by `b`", "snippet": "(a.T * b).T", "question_id": 3809265 }, { "intent": "remove (chomp) a newline", "rewritten_intent": "remove trailing newline in string \"test string\\n\"", "snippet": "'test string\\n'.rstrip()", "question_id": 275018 }, { "intent": "remove (chomp) a newline", "rewritten_intent": "remove trailing newline in string 'test string \\n\\n'", "snippet": "'test string \\n\\n'.rstrip('\\n')", "question_id": 275018 }, { "intent": "remove (chomp) a newline", "rewritten_intent": "remove newline in string `s`", "snippet": "s.strip()", "question_id": 275018 }, { "intent": "remove (chomp) a newline", "rewritten_intent": "remove newline in string `s` on the right side", "snippet": "s.rstrip()", "question_id": 275018 }, { "intent": "remove (chomp) a newline", "rewritten_intent": "remove newline in string `s` on the left side", "snippet": "s.lstrip()", "question_id": 275018 }, { "intent": "remove (chomp) a newline", "rewritten_intent": "remove newline in string 'Mac EOL\\r'", "snippet": "'Mac EOL\\r'.rstrip('\\r\\n')", "question_id": 275018 }, { "intent": "remove (chomp) a newline", "rewritten_intent": "remove newline in string 'Windows EOL\\r\\n' on the right side", "snippet": "'Windows EOL\\r\\n'.rstrip('\\r\\n')", "question_id": 275018 }, { "intent": "remove (chomp) a newline", "rewritten_intent": "remove newline in string 'Unix EOL\\n' on the right side", "snippet": "'Unix EOL\\n'.rstrip('\\r\\n')", "question_id": 275018 }, { "intent": "remove (chomp) a newline", "rewritten_intent": "remove newline in string \"Hello\\n\\n\\n\" on the right side", "snippet": "'Hello\\n\\n\\n'.rstrip('\\n')", "question_id": 275018 }, { "intent": "Python - split sentence after words but with maximum of n characters in result", "rewritten_intent": "split string `text` into chunks of 16 characters each", "snippet": "re.findall('.{,16}\\\\b', text)", "question_id": 18551752 }, { "intent": "NumPy List Comprehension Syntax", "rewritten_intent": "Get a list comprehension in list of lists `X`", "snippet": "[[X[i][j] for j in range(len(X[i]))] for i in range(len(X))]", "question_id": 21360028 }, { "intent": "Convert unicode string to byte string", "rewritten_intent": "convert unicode string '\\xd0\\xbc\\xd0\\xb0\\xd1\\x80\\xd0\\xba\\xd0\\xb0' to byte string", "snippet": "'\\xd0\\xbc\\xd0\\xb0\\xd1\\x80\\xd0\\xba\\xd0\\xb0'.encode('latin-1')", "question_id": 11174790 }, { "intent": "Best way to split a DataFrame given an edge", "rewritten_intent": "split dataframe `df` where the value of column `a` is equal to 'B'", "snippet": "df.groupby((df.a == 'B').shift(1).fillna(0).cumsum())", "question_id": 13353233 }, { "intent": "Save JSON outputed from a URL to a file", "rewritten_intent": "save json output from a url \u2018http://search.twitter.com/search.json?q=hi\u2019 to file \u2018hi.json\u2019 in Python 2", "snippet": "urllib.request.urlretrieve('http://search.twitter.com/search.json?q=hi', 'hi.json')", "question_id": 3040904 }, { "intent": "Find indices of elements equal to zero from numpy array", "rewritten_intent": "Find indices of elements equal to zero from numpy array `x`", "snippet": "numpy.where((x == 0))[0]", "question_id": 4588628 }, { "intent": "python, subprocess: reading output from subprocess", "rewritten_intent": "flush output of python print", "snippet": "sys.stdout.flush()", "question_id": 3804727 }, { "intent": "Converting integer to string", "rewritten_intent": "convert `i` to string", "snippet": "str(i)", "question_id": 961632 }, { "intent": "Converting integer to string", "rewritten_intent": "convert `a` to string", "snippet": "a.__str__()", "question_id": 961632 }, { "intent": "Converting integer to string", "rewritten_intent": "convert `a` to string", "snippet": "str(a)", "question_id": 961632 }, { "intent": "Method to sort a list of lists?", "rewritten_intent": "sort list of lists `L` by the second item in each list", "snippet": "L.sort(key=operator.itemgetter(1))", "question_id": 5201191 }, { "intent": "How do I add space between two variables after a print in Python", "rewritten_intent": "Print variable `count` and variable `conv` with space string ' ' in between", "snippet": "print(str(count) + ' ' + str(conv))", "question_id": 9969684 }, { "intent": "Pandas changing cell values based on another cell", "rewritten_intent": "change NaN values in dataframe `df` using preceding values in the frame", "snippet": "df.fillna(method='ffill', inplace=True)", "question_id": 38457059 }, { "intent": "Is there a way to make the Tkinter text widget read only?", "rewritten_intent": "change the state of the Tkinter `Text` widget to read only i.e. `disabled`", "snippet": "text.config(state=DISABLED)", "question_id": 3842155 }, { "intent": "Python sum of ASCII values of all characters in a string", "rewritten_intent": "python sum of ascii values of all characters in a string `string`", "snippet": "sum(map(ord, string))", "question_id": 12492137 }, { "intent": "How to apply itertools.product to elements of a list of lists?", "rewritten_intent": "apply itertools.product to elements of a list of lists `arrays`", "snippet": "list(itertools.product(*arrays))", "question_id": 3034014 }, { "intent": "print number with commas as thousands separators", "rewritten_intent": "print number `value` as thousands separators", "snippet": "'{:,}'.format(value)", "question_id": 1823058 }, { "intent": "print number with commas as thousands separators", "rewritten_intent": "print number 1255000 as thousands separators", "snippet": "locale.setlocale(locale.LC_ALL, 'en_US')\nlocale.format('%d', 1255000, grouping=True)", "question_id": 1823058 }, { "intent": "How to pass through a list of queries to a pandas dataframe, and output the list of results?", "rewritten_intent": "get rows of dataframe `df` where column `Col1` has values `['men', 'rocks', 'mountains']`", "snippet": "df[df.Col1.isin(['men', 'rocks', 'mountains'])]", "question_id": 39988589 }, { "intent": "Accessing a value in a tuple that is in a list", "rewritten_intent": "get the value at index 1 for each tuple in the list of tuples `L`", "snippet": "[x[1] for x in L]", "question_id": 4800811 }, { "intent": "splitting unicode string into words", "rewritten_intent": "split unicode string \"\u0440\u0430\u0437 \u0434\u0432\u0430 \u0442\u0440\u0438\" into words", "snippet": "'\\u0440\\u0430\\u0437 \\u0434\\u0432\\u0430 \\u0442\\u0440\\u0438'.split()", "question_id": 7286879 }, { "intent": "Django - How to sort queryset by number of character in a field", "rewritten_intent": "sort query set by number of characters in a field `length` in django model `MyModel`", "snippet": "MyModel.objects.extra(select={'length': 'Length(name)'}).order_by('length')", "question_id": 12804801 }, { "intent": "Python - Choose a dictionary in list which key is closer to a global value", "rewritten_intent": "get a dictionary in list `dicts` which key 'ratio' is closer to a global value 1.77672955975", "snippet": "min(dicts, key=lambda x: (abs(1.77672955975 - x['ratio']), -x['pixels']))", "question_id": 42442428 }, { "intent": "Finding missing values in a numpy array", "rewritten_intent": "get the non-masked values of array `m`", "snippet": "m[~m.mask]", "question_id": 3262437 }, { "intent": "Use of findall and parenthesis in Python", "rewritten_intent": "Find all words containing letters between A and Z in string `formula`", "snippet": "re.findall('\\\\b[A-Z]', formula)", "question_id": 13840883 }, { "intent": "How to define two-dimensional array in python", "rewritten_intent": "create a list `matrix` containing 5 lists, each of 5 items all set to 0", "snippet": "matrix = [([0] * 5) for i in range(5)]", "question_id": 6667201 }, { "intent": "Creating a numpy array of 3D coordinates from three 1D arrays", "rewritten_intent": "creating a numpy array of 3d coordinates from three 1d arrays `x_p`, `y_p` and `z_p`", "snippet": "np.vstack(np.meshgrid(x_p, y_p, z_p)).reshape(3, -1).T", "question_id": 18253210 }, { "intent": "How to find the minimum value in a numpy matrix?", "rewritten_intent": "find the minimum value in a numpy array `arr` excluding 0", "snippet": "arr[arr != 0].min()", "question_id": 11764260 }, { "intent": "Python Selenium: Find object attributes using xpath", "rewritten_intent": "get the text of multiple elements found by xpath \"//*[@type='submit']/@value\"", "snippet": "browser.find_elements_by_xpath(\"//*[@type='submit']/@value\").text", "question_id": 12579061 }, { "intent": "Python Selenium: Find object attributes using xpath", "rewritten_intent": "find all the values in attribute `value` for the tags whose `type` attribute is `submit` in selenium", "snippet": "browser.find_elements_by_xpath(\"//*[@type='submit']\").get_attribute('value')", "question_id": 12579061 }, { "intent": "parse a YAML file", "rewritten_intent": "parse a YAML file \"example.yaml\"", "snippet": "with open('example.yaml', 'r') as stream:\n try:\n print((yaml.load(stream)))\n except yaml.YAMLError as exc:\n print(exc)", "question_id": 1773805 }, { "intent": "parse a YAML file", "rewritten_intent": "parse a YAML file \"example.yaml\"", "snippet": "with open('example.yaml') as stream:\n try:\n print((yaml.load(stream)))\n except yaml.YAMLError as exc:\n print(exc)", "question_id": 1773805 }, { "intent": "How to swap a group of column headings with their values in Pandas", "rewritten_intent": "Sort the values of the dataframe `df` and align the columns accordingly based on the obtained indices after np.argsort.", "snippet": "pd.DataFrame(df.columns[np.argsort(df.values)], df.index, np.unique(df.values))", "question_id": 41572822 }, { "intent": "Getting today's date in YYYY-MM-DD in Python?", "rewritten_intent": "Getting today's date in YYYY-MM-DD", "snippet": "datetime.datetime.today().strftime('%Y-%m-%d')", "question_id": 32490629 }, { "intent": "How to urlencode a querystring in Python?", "rewritten_intent": "urlencode a querystring 'string_of_characters_like_these:$#@=?%^Q^$' in python 2", "snippet": "urllib.parse.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')", "question_id": 5607551 }, { "intent": "python sorting dictionary by length of values", "rewritten_intent": "sort a dictionary `d` by length of its values and print as string", "snippet": "print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))", "question_id": 16868457 }, { "intent": "convert list of tuples to multiple lists in Python", "rewritten_intent": "convert tuple elements in list `[(1,2),(3,4),(5,6),]` into lists", "snippet": "map(list, zip(*[(1, 2), (3, 4), (5, 6)]))", "question_id": 8081545 }, { "intent": "convert list of tuples to multiple lists in Python", "rewritten_intent": null, "snippet": "map(list, zip(*[(1, 2), (3, 4), (5, 6)]))", "question_id": 8081545 }, { "intent": "convert list of tuples to multiple lists in Python", "rewritten_intent": null, "snippet": "zip(*[(1, 2), (3, 4), (5, 6)])", "question_id": 8081545 }, { "intent": "Create a list of tuples with adjacent list elements if a condition is true", "rewritten_intent": "create a list of tuples which contains number 9 and the number before it, for each occurrence of 9 in the list 'myList'", "snippet": "[(x, y) for x, y in zip(myList, myList[1:]) if y == 9]", "question_id": 38251245 }, { "intent": "How can i set proxy with authentication in selenium chrome web driver using python", "rewritten_intent": "navigate to webpage given by url `http://www.python.org` using Selenium", "snippet": "driver.get('http://www.google.com.br')", "question_id": 29983106 }, { "intent": "Python reversing an UTF-8 string", "rewritten_intent": "reverse a UTF-8 string 'a'", "snippet": "b = a.decode('utf8')[::-1].encode('utf8')", "question_id": 34015615 }, { "intent": "Extracting date from a string in Python", "rewritten_intent": "extract date from a string 'monkey 2010-07-32 love banana'", "snippet": "dparser.parse('monkey 2010-07-32 love banana', fuzzy=True)", "question_id": 3276180 }, { "intent": "Extracting date from a string in Python", "rewritten_intent": "extract date from a string 'monkey 20/01/1980 love banana'", "snippet": "dparser.parse('monkey 20/01/1980 love banana', fuzzy=True)", "question_id": 3276180 }, { "intent": "Extracting date from a string in Python", "rewritten_intent": "extract date from a string `monkey 10/01/1980 love banana`", "snippet": "dparser.parse('monkey 10/01/1980 love banana', fuzzy=True)", "question_id": 3276180 }, { "intent": "Efficient way to convert a list to dictionary", "rewritten_intent": "Convert a list `['A:1', 'B:2', 'C:3', 'D:4']` to dictionary", "snippet": "dict(map(lambda s: s.split(':'), ['A:1', 'B:2', 'C:3', 'D:4']))", "question_id": 16374540 }, { "intent": "How can I check if a string contains ANY letters from the alphabet?", "rewritten_intent": "check if string `the_string` contains any upper or lower-case ASCII letters", "snippet": "re.search('[a-zA-Z]', the_string)", "question_id": 9072844 }, { "intent": "Converting a Pandas GroupBy object to DataFrame", "rewritten_intent": "convert a pandas `df1` groupby object to dataframe", "snippet": "DataFrame({'count': df1.groupby(['Name', 'City']).size()}).reset_index()", "question_id": 10373660 }, { "intent": "Removing all non-numeric characters from string in Python", "rewritten_intent": "remove all non-numeric characters from string `sdkjh987978asd098as0980a98sd `", "snippet": "re.sub('[^0-9]', '', 'sdkjh987978asd098as0980a98sd')", "question_id": 1249388 }, { "intent": "List comprehension with if statement", "rewritten_intent": "get items from list `a` that don't appear in list `b`", "snippet": "[y for y in a if y not in b]", "question_id": 15474933 }, { "intent": "How to subset a dataset in pandas dataframe?", "rewritten_intent": "extract the first four rows of the column `ID` from a pandas dataframe `df`", "snippet": "df.groupby('ID').head(4)", "question_id": 40987319 }, { "intent": "How to unzip a list of tuples into individual lists?", "rewritten_intent": "Unzip a list of tuples `l` into a list of lists", "snippet": "zip(*l)", "question_id": 12974474 }, { "intent": "How do I combine two lists into a dictionary in Python?", "rewritten_intent": "combine two lists `[1, 2, 3, 4]` and `['a', 'b', 'c', 'd']` into a dictionary", "snippet": "dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))", "question_id": 7271385 }, { "intent": "How do I combine two lists into a dictionary in Python?", "rewritten_intent": "combine two lists `[1, 2, 3, 4]` and `['a', 'b', 'c', 'd']` into a dictionary", "snippet": "dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))", "question_id": 7271385 }, { "intent": "How do I get the different parts of a Flask request's url?", "rewritten_intent": "retrieve the path from a Flask request", "snippet": "request.url", "question_id": 15974730 }, { "intent": "How to remove ^M from a text file and replace it with the next line", "rewritten_intent": "replace carriage return in string `somestring` with empty string ''", "snippet": "somestring.replace('\\\\r', '')", "question_id": 11755208 }, { "intent": "Best way to encode tuples with json", "rewritten_intent": "serialize dictionary `d` as a JSON formatted string with each key formatted to pattern '%d,%d'", "snippet": "simplejson.dumps(dict([('%d,%d' % k, v) for k, v in list(d.items())]))", "question_id": 715550 }, { "intent": "Converting string into datetime", "rewritten_intent": "parse string \"Jun 1 2005 1:33PM\" into datetime by format \"%b %d %Y %I:%M%p\"", "snippet": "datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')", "question_id": 466345 }, { "intent": "Converting string into datetime", "rewritten_intent": "parse string \"Aug 28 1999 12:00AM\" into datetime", "snippet": "parser.parse('Aug 28 1999 12:00AM')", "question_id": 466345 }, { "intent": "Python - Extract folder path from file path", "rewritten_intent": "Get absolute folder path and filename for file `existGDBPath `", "snippet": "os.path.split(os.path.abspath(existGDBPath))", "question_id": 17057544 }, { "intent": "Python - Extract folder path from file path", "rewritten_intent": "extract folder path from file path", "snippet": "os.path.dirname(os.path.abspath(existGDBPath))", "question_id": 17057544 }, { "intent": "Post JSON using Python Requests", "rewritten_intent": "Execute a post request to url `http://httpbin.org/post` with json data `{'test': 'cheers'}`", "snippet": "requests.post('http://httpbin.org/post', json={'test': 'cheers'})", "question_id": 9733638 }, { "intent": "Python - Remove dictionary from list if key is equal to value", "rewritten_intent": "remove dictionary from list `a` if the value associated with its key 'link' is in list `b`", "snippet": "a = [x for x in a if x['link'] not in b]", "question_id": 42260840 }, { "intent": "Getting a request parameter in Jinja2", "rewritten_intent": "get a request parameter `a` in jinja2", "snippet": "{{request.args.get('a')}}", "question_id": 9647586 }, { "intent": "Python - Create list with numbers between 2 values?", "rewritten_intent": "create a list of integers between 2 values `11` and `17`", "snippet": "list(range(11, 17))", "question_id": 18265935 }, { "intent": "type conversion in python from int to float", "rewritten_intent": "Change data type of data in column 'grade' of dataframe `data_df` into float and then to int", "snippet": "data_df['grade'] = data_df['grade'].astype(float).astype(int)", "question_id": 40707158 }, { "intent": "Sorting or Finding Max Value by the second element in a nested list. Python", "rewritten_intent": "Find the list in a list of lists `alkaline_earth_values` with the max value of the second element.", "snippet": "max(alkaline_earth_values, key=lambda x: x[1])", "question_id": 4800419 }, { "intent": "How to remove leading and trailing zeros in a string? Python", "rewritten_intent": "remove leading and trailing zeros in the string 'your_Strip'", "snippet": "your_string.strip('0')", "question_id": 13142347 }, { "intent": "Generating all unique pair permutations", "rewritten_intent": "generate a list of all unique pairs of integers in `range(9)`", "snippet": "list(permutations(list(range(9)), 2))", "question_id": 14169122 }, { "intent": "Python regular expression matching a multiline block of text", "rewritten_intent": "create a regular expression that matches the pattern '^(.+)(?:\\\\n|\\\\r\\\\n?)((?:(?:\\\\n|\\\\r\\\\n?).+)+)' over multiple lines of text", "snippet": "re.compile('^(.+)(?:\\\\n|\\\\r\\\\n?)((?:(?:\\\\n|\\\\r\\\\n?).+)+)', re.MULTILINE)", "question_id": 587345 }, { "intent": "Python regular expression matching a multiline block of text", "rewritten_intent": "regular expression \"^(.+)\\\\n((?:\\\\n.+)+)\" matching a multiline block of text", "snippet": "re.compile('^(.+)\\\\n((?:\\\\n.+)+)', re.MULTILINE)", "question_id": 587345 }, { "intent": "How do you call a python file that requires a command line argument from within another python file?", "rewritten_intent": "Run 'test2.py' file with python location 'path/to/python' and arguments 'neededArgumetGoHere' as a subprocess", "snippet": "call(['path/to/python', 'test2.py', 'neededArgumetGoHere'])", "question_id": 33218968 }, { "intent": "Sort a multidimensional list by a variable number of keys", "rewritten_intent": "sort a multidimensional list `a` by second and third column", "snippet": "a.sort(key=operator.itemgetter(2, 3))", "question_id": 1683775 }, { "intent": "Add another tuple to a tuple", "rewritten_intent": "Add a tuple with value `another_choice` to a tuple `my_choices`", "snippet": "final_choices = ((another_choice,) + my_choices)", "question_id": 3523048 }, { "intent": "Add another tuple to a tuple", "rewritten_intent": "Add a tuple with value `another_choice` to a tuple `my_choices`", "snippet": "final_choices = ((another_choice,) + my_choices)", "question_id": 3523048 }, { "intent": "Find current directory and file's directory", "rewritten_intent": "find the current directory", "snippet": "os.getcwd()", "question_id": 5137497 }, { "intent": "Find current directory and file's directory", "rewritten_intent": "find the current directory", "snippet": "os.path.realpath(__file__)", "question_id": 5137497 }, { "intent": "Find current directory and file's directory", "rewritten_intent": "get the directory name of `path`", "snippet": "os.path.dirname(path)", "question_id": 5137497 }, { "intent": "Find current directory and file's directory", "rewritten_intent": "get the canonical path of file `path`", "snippet": "os.path.realpath(path)", "question_id": 5137497 }, { "intent": "Find current directory", "rewritten_intent": "Find name of current directory", "snippet": "dir_path = os.path.dirname(os.path.realpath(__file__))", "question_id": 5137497 }, { "intent": "Find current directory", "rewritten_intent": "Find current directory", "snippet": "cwd = os.getcwd()", "question_id": 5137497 }, { "intent": "Find current directory", "rewritten_intent": "Find the full path of current directory", "snippet": "full_path = os.path.realpath(__file__)", "question_id": 5137497 }, { "intent": "Sort numpy matrix row values in ascending order", "rewritten_intent": "sort array `arr` in ascending order by values of the 3rd column", "snippet": "arr[arr[:, (2)].argsort()]", "question_id": 10078470 }, { "intent": "Sort numpy matrix row values in ascending order", "rewritten_intent": "sort rows of numpy matrix `arr` in ascending order according to all column values", "snippet": "numpy.sort(arr, axis=0)", "question_id": 10078470 }, { "intent": "split string on a number of different characters", "rewritten_intent": "split string 'a b.c' on space \" \" and dot character \".\"", "snippet": "re.split('[ .]', 'a b.c')", "question_id": 373459 }, { "intent": "copying one file's contents to another in python", "rewritten_intent": "copy the content of file 'file.txt' to file 'file2.txt'", "snippet": "shutil.copy('file.txt', 'file2.txt')", "question_id": 36875258 }, { "intent": "What's the best way to generate random strings of a specific length in Python?", "rewritten_intent": "generate random upper-case ascii string of 12 characters length", "snippet": "print(''.join(choice(ascii_uppercase) for i in range(12)))", "question_id": 18319101 }, { "intent": "How to merge the elements in a list sequentially in python", "rewritten_intent": "merge the elements in a list `lst` sequentially", "snippet": "[''.join(seq) for seq in zip(lst, lst[1:])]", "question_id": 39646401 }, { "intent": "python: rename single column header in pandas dataframe", "rewritten_intent": "rename column 'gdp' in dataframe `data` to 'log(gdp)'", "snippet": "data.rename(columns={'gdp': 'log(gdp)'}, inplace=True)", "question_id": 19758364 }, { "intent": "Converting html to text with Python", "rewritten_intent": "convert a beautiful soup html `soup` to text", "snippet": "print(soup.get_text())", "question_id": 14694482 }, { "intent": "python: sort a list of lists by an item in the sublist", "rewritten_intent": "Sort list `li` in descending order based on the second element of each list inside list`li`", "snippet": "sorted(li, key=operator.itemgetter(1), reverse=True)", "question_id": 18142090 }, { "intent": "Pandas - replacing column values", "rewritten_intent": "replace value 0 with 'Female' and value 1 with 'Male' in column 'sex' of dataframe `data`", "snippet": "data['sex'].replace([0, 1], ['Female', 'Male'], inplace=True)", "question_id": 31888871 }, { "intent": "Regex punctuation split [Python]", "rewritten_intent": "split string 'Words, words, words.' on punctuation", "snippet": "re.split('\\\\W+', 'Words, words, words.')", "question_id": 19894478 }, { "intent": "Limit the number of sentences in a string", "rewritten_intent": "Extract first two substrings in string `phrase` that end in `.`, `?` or `!`", "snippet": "re.match('(.*?[.?!](?:\\\\s+.*?[.?!]){0,1})', phrase).group(1)", "question_id": 3329386 }, { "intent": "Split string into strings of repeating elements", "rewritten_intent": "split string `s` into strings of repeating elements", "snippet": "print([a for a, b in re.findall('((\\\\w)\\\\2*)', s)])", "question_id": 9505526 }, { "intent": "How does this function to remove duplicate characters from a string in python work?", "rewritten_intent": "Create new string with unique characters from `s` seperated by ' '", "snippet": "print(' '.join(OrderedDict.fromkeys(s)))", "question_id": 29360607 }, { "intent": "How does this function to remove duplicate characters from a string in python work?", "rewritten_intent": "create a set from string `s` to remove duplicate characters", "snippet": "print(' '.join(set(s)))", "question_id": 29360607 }, { "intent": "How can i list only the folders in zip archive in Python?", "rewritten_intent": "list folders in zip file 'file' that ends with '/'", "snippet": "[x for x in file.namelist() if x.endswith('/')]", "question_id": 6510477 }, { "intent": "How to find the count of a word in a string?", "rewritten_intent": "find the count of a word 'Hello' in a string `input_string`", "snippet": "input_string.count('Hello')", "question_id": 11300383 }, { "intent": "Python: reduce (list of strings) -> string", "rewritten_intent": "reduce the first element of list of strings `data` to a string, separated by '.'", "snippet": "print('.'.join([item[0] for item in data]))", "question_id": 27436748 }, { "intent": "Dumping subprcess output in a file in append mode", "rewritten_intent": "Move the cursor of file pointer `fh1` at the end of the file.", "snippet": "fh1.seek(2)", "question_id": 14332141 }, { "intent": "list of ints into a list of tuples python", "rewritten_intent": "convert a flat list into a list of tuples of every two items in the list, in order", "snippet": "print(zip(my_list[0::2], my_list[1::2]))", "question_id": 15852295 }, { "intent": "list of ints into a list of tuples python", "rewritten_intent": "group a list of ints into a list of tuples of each 2 elements", "snippet": "my_new_list = zip(my_list[0::2], my_list[1::2])", "question_id": 15852295 }, { "intent": "How to fix: \"UnicodeDecodeError: 'ascii' codec can't decode byte\"", "rewritten_intent": "set the default encoding to 'utf-8'", "snippet": "sys.setdefaultencoding('utf8')", "question_id": 21129020 }, { "intent": "Python datetime to string without microsecond component", "rewritten_intent": "Formate current date and time to a string using pattern '%Y-%m-%d %H:%M:%S'", "snippet": "datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')", "question_id": 7999935 }, { "intent": "How to retrieve only arabic texts from a string using regular expression?", "rewritten_intent": "retrieve arabic texts from string `my_string`", "snippet": "print(re.findall('[\\\\u0600-\\\\u06FF]+', my_string))", "question_id": 36661837 }, { "intent": "How to group DataFrame by a period of time?", "rewritten_intent": "group dataframe `df` based on minute interval", "snippet": "df.groupby(df.index.map(lambda t: t.minute))", "question_id": 11073609 }, { "intent": "Accessing elements of python dictionary", "rewritten_intent": "access value associated with key 'American' of key 'Apple' from dictionary `dict`", "snippet": "dict['Apple']['American']", "question_id": 5404665 }, { "intent": "How to remove rows with null values from kth column onward in python", "rewritten_intent": "remove all null values from columns 'three', 'four' and 'five' of dataframe `df2`", "snippet": "df2.dropna(subset=['three', 'four', 'five'], how='all')", "question_id": 14991195 }, { "intent": "How do I insert a list at the front of another list?", "rewritten_intent": "insert a list `k` at the front of list `a`", "snippet": "a.insert(0, k)", "question_id": 8785554 }, { "intent": "How do I insert a list at the front of another list?", "rewritten_intent": "insert elements of list `k` into list `a` at position `n`", "snippet": "a = a[:n] + k + a[n:]", "question_id": 8785554 }, { "intent": "Pyhon - Best way to find the 1d center of mass in a binary numpy array", "rewritten_intent": "calculate the mean of the nonzero values' indices of dataframe `df`", "snippet": "np.flatnonzero(x).mean()", "question_id": 39719140 }, { "intent": "Keep only date part when using pandas.to_datetime", "rewritten_intent": "get date from dataframe `df` column 'dates' to column 'just_date'", "snippet": "df['just_date'] = df['dates'].dt.date", "question_id": 16176996 }, { "intent": "Removing one list from another", "rewritten_intent": "remove elements in list `b` from list `a`", "snippet": "[x for x in a if x not in b]", "question_id": 9053260 }, { "intent": "How do I transform a multi-level list into a list of strings in Python?", "rewritten_intent": "join elements of each tuple in list `a` into one string", "snippet": "[''.join(x) for x in a]", "question_id": 35015693 }, { "intent": "How do I transform a multi-level list into a list of strings in Python?", "rewritten_intent": "join items of each tuple in list of tuples `a` into a list of strings", "snippet": "list(map(''.join, a))", "question_id": 35015693 }, { "intent": "Matching blank lines with regular expressions", "rewritten_intent": "match blank lines in `s` with regular expressions", "snippet": "re.split('\\n\\\\s*\\n', s)", "question_id": 1197600 }, { "intent": "Merging items in a list - Python", "rewritten_intent": "merge a list of integers `[1, 2, 3, 4, 5]` into a single integer", "snippet": "from functools import reduce\nreduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5])", "question_id": 4299741 }, { "intent": "Convert float to comma-separated string", "rewritten_intent": "Convert float 24322.34 to comma-separated string", "snippet": "\"\"\"{0:,.2f}\"\"\".format(24322.34)", "question_id": 10677350 }, { "intent": "How to pass dictionary items as function arguments in python?", "rewritten_intent": "pass dictionary items `data` as keyword arguments in function `my_function`", "snippet": "my_function(**data)", "question_id": 21986194 }, { "intent": "get line count", "rewritten_intent": "get line count of file 'myfile.txt'", "snippet": "sum((1 for line in open('myfile.txt')))", "question_id": 845058 }, { "intent": "get line count", "rewritten_intent": "get line count of file `filename`", "snippet": "def bufcount(filename):\n f = open(filename)\n lines = 0\n buf_size = (1024 * 1024)\n read_f = f.read\n buf = read_f(buf_size)\n while buf:\n lines += buf.count('\\n')\n buf = read_f(buf_size)\n return lines", "question_id": 845058 }, { "intent": "How to round integers in python", "rewritten_intent": "round 1123.456789 to be an integer", "snippet": "print(round(1123.456789, -1))", "question_id": 3348825 }, { "intent": "Sorting list based on values from another list?", "rewritten_intent": "sort list `X` based on values from another list `Y`", "snippet": "[x for y, x in sorted(zip(Y, X))]", "question_id": 6618515 }, { "intent": "Sorting list based on values from another list?", "rewritten_intent": "sorting list 'X' based on values from another list 'Y'", "snippet": "[x for y, x in sorted(zip(Y, X))]", "question_id": 6618515 }, { "intent": "How to get week number in Python?", "rewritten_intent": "get equivalent week number from a date `2010/6/16` using isocalendar", "snippet": "datetime.date(2010, 6, 16).isocalendar()[1]", "question_id": 2600775 }, { "intent": "Select multiple ranges of columns in Pandas DataFrame", "rewritten_intent": "select multiple ranges of columns 1-10, 15, 17, and 50-100 in pandas dataframe `df`", "snippet": "df.iloc[:, (np.r_[1:10, (15), (17), 50:100])]", "question_id": 41256648 }, { "intent": "Python Pandas: Multiple aggregations of the same column", "rewritten_intent": "apply two different aggregating functions `mean` and `sum` to the same column `dummy` in pandas data frame `df`", "snippet": "df.groupby('dummy').agg({'returns': [np.mean, np.sum]})", "question_id": 12589481 }, { "intent": "convert string to lowercase", "rewritten_intent": "convert string `s` to lowercase", "snippet": "s.lower()", "question_id": 6797984 }, { "intent": "convert string to lowercase", "rewritten_intent": "convert utf-8 string `s` to lowercase", "snippet": "s.decode('utf-8').lower()", "question_id": 6797984 }, { "intent": "How to download a file via FTP with Python ftplib", "rewritten_intent": null, "snippet": "ftp.retrbinary('RETR %s' % filename, file.write)", "question_id": 11573817 }, { "intent": "How do I increase the timeout for imaplib requests?", "rewritten_intent": "handle the `urlfetch_errors ` exception for imaplib request to url `url`", "snippet": "urlfetch.fetch(url, deadline=10 * 60)", "question_id": 19445682 }, { "intent": "Output first 100 characters in a string", "rewritten_intent": "output first 100 characters in a string `my_string`", "snippet": "print(my_string[0:100])", "question_id": 3486384 }, { "intent": "matplotlib Legend Markers Only Once", "rewritten_intent": "make matplotlib plot legend put marker in legend only once", "snippet": "legend(numpoints=1)", "question_id": 6146778 }, { "intent": "Python - How to calculate equal parts of two dictionaries?", "rewritten_intent": "get set intersection between dictionaries `d1` and `d2`", "snippet": "dict((x, set(y) & set(d1.get(x, ()))) for x, y in d2.items())", "question_id": 638360 }, { "intent": "load csv into 2D matrix with numpy for plotting", "rewritten_intent": "convert csv file 'test.csv' into two-dimensional matrix", "snippet": "numpy.loadtxt(open('test.csv', 'rb'), delimiter=',', skiprows=1)", "question_id": 4315506 }, { "intent": "Django database query: How to filter objects by date range?", "rewritten_intent": "filter the objects in django model 'Sample' between date range `2011-01-01` and `2011-01-31`", "snippet": "Sample.objects.filter(date__range=['2011-01-01', '2011-01-31'])", "question_id": 4668619 }, { "intent": "Django database query: How to filter objects by date range?", "rewritten_intent": "filter objects month wise in django model `Sample` for year `2011`", "snippet": "Sample.objects.filter(date__year='2011', date__month='01')", "question_id": 4668619 }, { "intent": "syntax for creating a dictionary into another dictionary in python", "rewritten_intent": "create a dictionary `{'spam': 5, 'ham': 6}` into another dictionary `d` field 'dict3'", "snippet": "d['dict3'] = {'spam': 5, 'ham': 6}", "question_id": 3817529 }, { "intent": "How to apply numpy.linalg.norm to each row of a matrix?", "rewritten_intent": "apply `numpy.linalg.norm` to each row of a matrix `a`", "snippet": "numpy.apply_along_axis(numpy.linalg.norm, 1, a)", "question_id": 7741878 }, { "intent": "How to merge two Python dictionaries in a single expression?", "rewritten_intent": "merge dictionaries form array `dicts` in a single expression", "snippet": "dict((k, v) for d in dicts for k, v in list(d.items()))", "question_id": 38987 }, { "intent": "Python. Convert escaped utf string to utf-string", "rewritten_intent": "Convert escaped utf string to utf string in `your string`", "snippet": "print('your string'.decode('string_escape'))", "question_id": 42548362 }, { "intent": "Counting the number of True Booleans in a Python List", "rewritten_intent": "counting the number of true booleans in a python list `[True, True, False, False, False, True]`", "snippet": "sum([True, True, False, False, False, True])", "question_id": 12765833 }, { "intent": "Matplotlib.animation: how to remove white margin", "rewritten_intent": "set the size of figure `fig` in inches to width height of `w`, `h`", "snippet": "fig.set_size_inches(w, h, forward=True)", "question_id": 15882395 }, { "intent": "python string format() with dict with integer keys", "rewritten_intent": "format string with dict `{'5': 'you'}` with integer keys", "snippet": "'hello there %(5)s' % {'5': 'you'}", "question_id": 20677660 }, { "intent": "Python - converting a string of numbers into a list of int", "rewritten_intent": "Convert a string of numbers `example_string` separated by `,` into a list of integers", "snippet": "map(int, example_string.split(','))", "question_id": 19334374 }, { "intent": "Python - converting a string of numbers into a list of int", "rewritten_intent": "Convert a string of numbers 'example_string' separated by comma into a list of numbers", "snippet": "[int(s) for s in example_string.split(',')]", "question_id": 19334374 }, { "intent": "Python list of tuples to list of int", "rewritten_intent": "Flatten list `x`", "snippet": "x = [i[0] for i in x]", "question_id": 15096021 }, { "intent": "Python list of tuples to list of int", "rewritten_intent": "convert list `x` into a flat list", "snippet": "y = map(operator.itemgetter(0), x)", "question_id": 15096021 }, { "intent": "Python list of tuples to list of int", "rewritten_intent": "get a list `y` of the first element of every tuple in list `x`", "snippet": "y = [i[0] for i in x]", "question_id": 15096021 }, { "intent": "How do I extract all the values of a specific key from a list of dictionaries?", "rewritten_intent": "extract all the values of a specific key named 'values' from a list of dictionaries", "snippet": "results = [item['value'] for item in test_data]", "question_id": 25148611 }, { "intent": "ISO Time (ISO 8601) in Python", "rewritten_intent": "get current datetime in ISO format", "snippet": "datetime.datetime.now().isoformat()", "question_id": 2150739 }, { "intent": "ISO Time (ISO 8601) in Python", "rewritten_intent": "get UTC datetime in ISO format", "snippet": "datetime.datetime.utcnow().isoformat()", "question_id": 2150739 }, { "intent": "Merging data frame columns of strings into one single column in Pandas", "rewritten_intent": "Merge all columns in dataframe `df` into one column", "snippet": "df.apply(' '.join, axis=0)", "question_id": 38549915 }, { "intent": "pandas Subtract Dataframe with a row from another dataframe", "rewritten_intent": "pandas subtract a row from dataframe `df2` from dataframe `df`", "snippet": "pd.DataFrame(df.values - df2.values, columns=df.columns)", "question_id": 22093471 }, { "intent": "How can I detect DOS line breaks in a file?", "rewritten_intent": "read file 'myfile.txt' using universal newline mode 'U'", "snippet": "print(open('myfile.txt', 'U').read())", "question_id": 2798627 }, { "intent": "Python - read text file with weird utf-16 format", "rewritten_intent": "print line `line` from text file with 'utf-16-le' format", "snippet": "print(line.decode('utf-16-le').split())", "question_id": 19328874 }, { "intent": "Python - read text file with weird utf-16 format", "rewritten_intent": "open a text file `data.txt` in io module with encoding `utf-16-le`", "snippet": "file = io.open('data.txt', 'r', encoding='utf-16-le')", "question_id": 19328874 }, { "intent": "Finding common rows (intersection) in two Pandas dataframes", "rewritten_intent": "Join data of dataframe `df1` with data in dataframe `df2` based on similar values of column 'user_id' in both dataframes", "snippet": "s1 = pd.merge(df1, df2, how='inner', on=['user_id'])", "question_id": 19618912 }, { "intent": "How can I check a Python unicode string to see that it *actually* is proper Unicode?", "rewritten_intent": "check if string `foo` is UTF-8 encoded", "snippet": "foo.decode('utf8').encode('utf8')", "question_id": 3487377 }, { "intent": "Numpy array dimensions", "rewritten_intent": "get the dimensions of numpy array `a`", "snippet": "a.shape", "question_id": 3061761 }, { "intent": "Numpy array dimensions", "rewritten_intent": "get the dimensions of numpy array `a`", "snippet": "N.shape(a)", "question_id": 3061761 }, { "intent": "Numpy array dimensions", "rewritten_intent": "get the dimensions of array `a`", "snippet": "N.shape(a)", "question_id": 3061761 }, { "intent": "Numpy array dimensions", "rewritten_intent": "get the dimensions of numpy array `a`", "snippet": "a.shape", "question_id": 3061761 }, { "intent": "How to search a list of tuples in Python", "rewritten_intent": "get the indices of tuples in list of tuples `L` where the first value is 53", "snippet": "[i for i, v in enumerate(L) if v[0] == 53]", "question_id": 2917372 }, { "intent": "convert a string of bytes into an int (python)", "rewritten_intent": "convert string of bytes `y\\xcc\\xa6\\xbb` into an int", "snippet": "struct.unpack('' in database `db` in sqlalchemy-flask app", "snippet": "result = db.engine.execute('')", "question_id": 17972020 }, { "intent": "Is there a method that tells my program to quit?", "rewritten_intent": "quit program", "snippet": "sys.exit(0)", "question_id": 2823472 }, { "intent": "Python - find digits in a string", "rewritten_intent": "get digits in string `my_string`", "snippet": "\"\"\"\"\"\".join(c for c in my_string if c.isdigit())", "question_id": 12005558 }, { "intent": "python split string based on regular expression", "rewritten_intent": "split string `str1` on one or more spaces with a regular expression", "snippet": "re.split(' +', str1)", "question_id": 10974932 }, { "intent": "python split string based on regular expression", "rewritten_intent": null, "snippet": "re.findall('\\\\S+', str1)", "question_id": 10974932 }, { "intent": "Python: How to get attribute of attribute of an object with getattr?", "rewritten_intent": "Evaluate a nested dictionary `myobject.id.number` to get `number` if `myobject` is present with getattr", "snippet": "getattr(getattr(myobject, 'id', None), 'number', None)", "question_id": 14925239 }, { "intent": "Convert generator object to a dictionary", "rewritten_intent": "convert generator object to a dictionary", "snippet": "{i: (i * 2) for i in range(10)}", "question_id": 17815945 }, { "intent": "Convert generator object to a dictionary", "rewritten_intent": "convert generator object to a dictionary", "snippet": "dict((i, i * 2) for i in range(10))", "question_id": 17815945 }, { "intent": "How do I tell matplotlib that I am done with a plot?", "rewritten_intent": "Matplotlib clear the current axes.", "snippet": "plt.cla()", "question_id": 741877 }, { "intent": "Python Convert String Literal to Float", "rewritten_intent": "split string `s` into float values and write sum to `total`", "snippet": "total = sum(float(item) for item in s.split(','))", "question_id": 21212706 }, { "intent": "Python ASCII to binary", "rewritten_intent": "Convert ascii value 'P' to binary", "snippet": "bin(ord('P'))", "question_id": 4523551 }, { "intent": "Get a string after a specific substring", "rewritten_intent": "print a string after a specific substring ', ' in string `my_string `", "snippet": "print(my_string.split(', ', 1)[1])", "question_id": 12572362 }, { "intent": "Python Accessing Nested JSON Data", "rewritten_intent": "get value of key `post code` associated with first index of key `places` of dictionary `data`", "snippet": "print(data['places'][0]['post code'])", "question_id": 23306653 }, { "intent": "Python RegEx using re.sub with multiple patterns", "rewritten_intent": "remove colon character surrounded by vowels letters in string `word`", "snippet": "word = re.sub('([aeiou]):(([aeiou][^aeiou]*){3})$', '\\\\1\\\\2', word)", "question_id": 33724111 }, { "intent": "How to extract data from JSON Object in Python?", "rewritten_intent": "extract data field 'bar' from json object", "snippet": "json.loads('{\"foo\": 42, \"bar\": \"baz\"}')['bar']", "question_id": 6407780 }, { "intent": "Convert JSON array to Python list", "rewritten_intent": "Convert JSON array `array` to Python object", "snippet": "data = json.loads(array)", "question_id": 10973614 }, { "intent": "Convert JSON array to Python list", "rewritten_intent": "Convert JSON array `array` to Python object", "snippet": "data = json.loads(array)", "question_id": 10973614 }, { "intent": "Parsing a tweet to extract hashtags into an array in Python", "rewritten_intent": "pars a string 'http://example.org/#comments' to extract hashtags into an array", "snippet": "re.findall('#(\\\\w+)', 'http://example.org/#comments')", "question_id": 2527892 }, { "intent": "Python - Fastest way to check if a string contains specific characters in any of the items in a list", "rewritten_intent": "do a boolean check if a string `lestring` contains any of the items in list `lelist`", "snippet": "any(e in lestring for e in lelist)", "question_id": 14411633 }, { "intent": "How to plot two columns of a pandas data frame using points?", "rewritten_intent": null, "snippet": "df.plot(x='col_name_1', y='col_name_2', style='o')", "question_id": 17812978 }, { "intent": "Parsing HTML", "rewritten_intent": "Parsing HTML string `html` using BeautifulSoup", "snippet": "parsed_html = BeautifulSoup(html)\nprint(parsed_html.body.find('div', attrs={'class': 'container', }).text)", "question_id": 11709079 }, { "intent": "Parsing HTML", "rewritten_intent": "Parsing webpage 'http://www.google.com/' using BeautifulSoup", "snippet": "page = urllib.request.urlopen('http://www.google.com/')\nsoup = BeautifulSoup(page)", "question_id": 11709079 }, { "intent": "change figure size and figure format in matplotlib", "rewritten_intent": "change figure size to 3 by 4 in matplotlib", "snippet": "plt.figure(figsize=(3, 4))", "question_id": 17109608 }, { "intent": "Best way to strip punctuation from a string in Python", "rewritten_intent": "Strip punctuation from string `s`", "snippet": "s.translate(None, string.punctuation)", "question_id": 265960 }, { "intent": "Django urlsafe base64 decoding with decryption", "rewritten_intent": "django urlsafe base64 decode string `uenc` with decryption", "snippet": "base64.urlsafe_b64decode(uenc.encode('ascii'))", "question_id": 2229827 }, { "intent": "Get the number of all keys in a dictionary of dictionaries in Python", "rewritten_intent": "get the number of all keys in the nested dictionary `dict_list`", "snippet": "len(dict_test) + sum(len(v) for v in dict_test.values())", "question_id": 35427814 }, { "intent": "Python convert decimal to hex", "rewritten_intent": "return the conversion of decimal `d` to hex without the '0x' prefix", "snippet": "hex(d).split('x')[1]", "question_id": 5796238 }, { "intent": "converting integer to list in python", "rewritten_intent": "create a list containing digits of number 123 as its elements", "snippet": "list(str(123))", "question_id": 13905936 }, { "intent": "converting integer to list in python", "rewritten_intent": "converting integer `num` to list", "snippet": "[int(x) for x in str(num)]", "question_id": 13905936 }, { "intent": "Python Mechanize select a form with no name", "rewritten_intent": "select a first form with no name in mechanize", "snippet": "br.select_form(nr=0)", "question_id": 2582580 }, { "intent": "Python load json file with UTF-8 BOM header", "rewritten_intent": "Open file 'sample.json' in read mode with encoding of 'utf-8-sig'", "snippet": "json.load(codecs.open('sample.json', 'r', 'utf-8-sig'))", "question_id": 13156395 }, { "intent": "Python load json file with UTF-8 BOM header", "rewritten_intent": "load json file 'sample.json' with utf-8 bom header", "snippet": "json.loads(open('sample.json').read().decode('utf-8-sig'))", "question_id": 13156395 }, { "intent": "Issue sending email with python?", "rewritten_intent": "setup a smtp mail server to `smtp.gmail.com` with port `587`", "snippet": "server = smtplib.SMTP('smtp.gmail.com', 587)", "question_id": 12030179 }, { "intent": "Reversing bits of Python integer", "rewritten_intent": "revers correlating bits of integer `n`", "snippet": "int('{:08b}'.format(n)[::-1], 2)", "question_id": 12681945 }, { "intent": "Pandas DataFrame Add column to index without resetting", "rewritten_intent": "add column `d` to index of dataframe `df`", "snippet": "df.set_index(['d'], append=True)", "question_id": 11040626 }, { "intent": "Iterating over dictionaries using for loops", "rewritten_intent": "Iterating over a dictionary `d` using for loops", "snippet": "for (key, value) in d.items():\n pass", "question_id": 3294889 }, { "intent": "Iterating over dictionaries using for loops", "rewritten_intent": "Iterating over a dictionary `d` using for loops", "snippet": "for (key, value) in list(d.items()):\n pass", "question_id": 3294889 }, { "intent": "Iterating over dictionaries using for loops", "rewritten_intent": "Iterating key and items over dictionary `d`", "snippet": "for (letter, number) in list(d.items()):\n pass", "question_id": 3294889 }, { "intent": "Iterating over dictionaries using for loops", "rewritten_intent": "Iterating key and items over dictionary `d`", "snippet": "for (k, v) in list(d.items()):\n pass", "question_id": 3294889 }, { "intent": "Iterating over dictionaries using for loops", "rewritten_intent": "get keys and items of dictionary `d`", "snippet": "list(d.items())", "question_id": 3294889 }, { "intent": "Iterating over dictionaries using for loops", "rewritten_intent": "get keys and items of dictionary `d` as a list", "snippet": "list(d.items())", "question_id": 3294889 }, { "intent": "Iterating over dictionaries using for loops", "rewritten_intent": "Iterating key and items over dictionary `d`", "snippet": "for (k, v) in list(d.items()):\n pass", "question_id": 3294889 }, { "intent": "Iterating over dictionaries using for loops", "rewritten_intent": "Iterating key and items over dictionary `d`", "snippet": "for (letter, number) in list(d.items()):\n pass", "question_id": 3294889 }, { "intent": "Iterating over dictionaries using for loops", "rewritten_intent": "Iterating key and items over dictionary `d`", "snippet": "for (letter, number) in list(d.items()):\n pass", "question_id": 3294889 }, { "intent": "How do I implement a null coalescing operator in SQLAlchemy?", "rewritten_intent": "query all data from table `Task` where the value of column `time_spent` is bigger than 3 hours", "snippet": "session.query(Task).filter(Task.time_spent > timedelta(hours=3)).all()", "question_id": 18102109 }, { "intent": "How do I compile a Visual Studio project from the command-line?", "rewritten_intent": "compile Visual Studio project `project.sln` from the command line through python", "snippet": "os.system('msbuild project.sln /p:Configuration=Debug')", "question_id": 498106 }, { "intent": "Get max key in dictionary", "rewritten_intent": "get max key in dictionary `MyCount`", "snippet": "max(list(MyCount.keys()), key=int)", "question_id": 3108042 }, { "intent": "Can I use an alias to execute a program from a python script", "rewritten_intent": "execute command 'source .bashrc; shopt -s expand_aliases; nuke -x scriptPath' from python script", "snippet": "os.system('source .bashrc; shopt -s expand_aliases; nuke -x scriptPath')", "question_id": 6856119 }, { "intent": "How to get a function name as a string in Python?", "rewritten_intent": "get a name of function `my_function` as a string", "snippet": "my_function.__name__", "question_id": 251464 }, { "intent": "How to get a function name as a string in Python?", "rewritten_intent": null, "snippet": "my_function.__name__", "question_id": 251464 }, { "intent": "How to check if all values in the columns of a numpy matrix are the same?", "rewritten_intent": "check if all values in the columns of a numpy matrix `a` are same", "snippet": "np.all(a == a[(0), :], axis=0)", "question_id": 14859458 }, { "intent": "Sorting a list of tuples by the addition of second and third element of the tuple", "rewritten_intent": "sort list `a` in ascending order based on the addition of the second and third elements of each tuple in it", "snippet": "sorted(a, key=lambda x: (sum(x[1:3]), x[0]))", "question_id": 40384599 }, { "intent": "Sorting a list of tuples by the addition of second and third element of the tuple", "rewritten_intent": "sort a list of tuples `a` by the sum of second and third element of each tuple", "snippet": "sorted(a, key=lambda x: (sum(x[1:3]), x[0]), reverse=True)", "question_id": 40384599 }, { "intent": "Sorting a list of tuples by the addition of second and third element of the tuple", "rewritten_intent": "sorting a list of tuples `lst` by the sum of the second elements onwards, and third element of the tuple", "snippet": "sorted(lst, key=lambda x: (sum(x[1:]), x[0]))", "question_id": 40384599 }, { "intent": "Sorting a list of tuples by the addition of second and third element of the tuple", "rewritten_intent": "sort the list of tuples `lst` by the sum of every value except the first and by the first value in reverse order", "snippet": "sorted(lst, key=lambda x: (sum(x[1:]), x[0]), reverse=True)", "question_id": 40384599 }, { "intent": "Add headers in a Flask app with unicode_literals", "rewritten_intent": "add header 'WWWAuthenticate' in a flask app with value 'Basic realm=\"test\"'", "snippet": "response.headers['WWW-Authenticate'] = 'Basic realm=\"test\"'", "question_id": 19410585 }, { "intent": "In Django, how do I clear a sessionkey?", "rewritten_intent": "clear session key 'mykey'", "snippet": "del request.session['mykey']", "question_id": 2375335 }, { "intent": "Python date string to date object", "rewritten_intent": "convert date string '24052010' to date object in format '%d%m%Y'", "snippet": "datetime.datetime.strptime('24052010', '%d%m%Y').date()", "question_id": 2803852 }, { "intent": "Replace non-ASCII characters with a single space", "rewritten_intent": "Replace non-ASCII characters in string `text` with a single space", "snippet": "re.sub('[^\\\\x00-\\\\x7F]+', ' ', text)", "question_id": 20078816 }, { "intent": "List of lists into numpy array", "rewritten_intent": null, "snippet": "numpy.array([[1, 2], [3, 4]])", "question_id": 10346336 }, { "intent": "What does a for loop within a list do in Python?", "rewritten_intent": "Get a list `myList` from 1 to 10", "snippet": "myList = [i for i in range(10)]", "question_id": 11479392 }, { "intent": "using regular expression to split string in python", "rewritten_intent": "use regex pattern '((.+?)\\\\2+)' to split string '44442(2)2(2)44'", "snippet": "[m[0] for m in re.compile('((.+?)\\\\2+)').findall('44442(2)2(2)44')]", "question_id": 40582103 }, { "intent": "using regular expression to split string in python", "rewritten_intent": "use regular expression '((\\\\d)(?:[()]*\\\\2*[()]*)*)' to split string `s`", "snippet": "[i[0] for i in re.findall('((\\\\d)(?:[()]*\\\\2*[()]*)*)', s)]", "question_id": 40582103 }, { "intent": "How to remove the space between subplots in matplotlib.pyplot?", "rewritten_intent": "remove the space between subplots in matplotlib.pyplot", "snippet": "fig.subplots_adjust(wspace=0, hspace=0)", "question_id": 41071947 }, { "intent": "How to reverse tuples in Python?", "rewritten_intent": "Reverse list `x`", "snippet": "x[::-1]", "question_id": 10201977 }, { "intent": "Python JSON encoding", "rewritten_intent": null, "snippet": "json.dumps({'apple': 'cat', 'banana': 'dog', 'pear': 'fish'})", "question_id": 983855 }, { "intent": "Writing List of Strings to Excel CSV File in Python", "rewritten_intent": "write a list of strings `row` to csv object `csvwriter`", "snippet": "csvwriter.writerow(row)", "question_id": 6916542 }, { "intent": "How to convert datetime to string in python in django", "rewritten_intent": "Jinja2 formate date `item.date` accorto pattern 'Y M d'", "snippet": "{{(item.date | date): 'Y M d'}}", "question_id": 794995 }, { "intent": "Non-consuming regular expression split in Python", "rewritten_intent": "Split a string `text` with comma, question mark or exclamation by non-consuming regex using look-behind", "snippet": "re.split('(?<=[\\\\.\\\\?!]) ', text)", "question_id": 5801945 }, { "intent": "UTF in Python Regex", "rewritten_intent": "create a regular expression object with the pattern '\\xe2\\x80\\x93'", "snippet": "re.compile('\\xe2\\x80\\x93')", "question_id": 372102 }, { "intent": "declare an array", "rewritten_intent": "declare an array `variable`", "snippet": "variable = []", "question_id": 1514553 }, { "intent": "declare an array", "rewritten_intent": "declare an array with element 'i'", "snippet": "intarray = array('i')", "question_id": 1514553 }, { "intent": "How to reverse the elements in a sublist?", "rewritten_intent": "given list `to_reverse`, reverse the all sublists and the list itself", "snippet": "[sublist[::-1] for sublist in to_reverse[::-1]]", "question_id": 39821166 }, { "intent": "Replace all non-alphanumeric characters in a string", "rewritten_intent": null, "snippet": "re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')", "question_id": 12985456 }, { "intent": "Python: unescape special characters without splitting data", "rewritten_intent": "unescape special characters without splitting data in array of strings `['I ', u'<', '3s U ', u'&', ' you luvz me']`", "snippet": "\"\"\"\"\"\".join(['I ', '<', '3s U ', '&', ' you luvz me'])", "question_id": 20876077 }, { "intent": "How can I disable logging while running unit tests in Python Django?", "rewritten_intent": "disable logging while running unit tests in python django", "snippet": "logging.disable(logging.CRITICAL)", "question_id": 5255657 }, { "intent": "Adding url to mysql row in python", "rewritten_intent": "adding url `url` to mysql row", "snippet": "cursor.execute('INSERT INTO index(url) VALUES(%s)', (url,))", "question_id": 13042013 }, { "intent": "Convert column of date objects in Pandas DataFrame to strings", "rewritten_intent": "convert column of date objects 'DateObj' in pandas dataframe `df` to strings in new column 'DateStr'", "snippet": "df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y')", "question_id": 19738169 }, { "intent": "python regex get first part of an email address", "rewritten_intent": "split string `s` by '@' and get the first element", "snippet": "s.split('@')[0]", "question_id": 15210485 }, { "intent": "Python Pandas: drop rows of a timeserie based on time range", "rewritten_intent": "drop rows of dataframe `df` whose index is smaller than the value of `start_remove` or bigger than the value of`end_remove`", "snippet": "df.query('index < @start_remove or index > @end_remove')", "question_id": 41513324 }, { "intent": "Python Pandas: drop rows of a timeserie based on time range", "rewritten_intent": "Drop the rows in pandas timeseries `df` from the row containing index `start_remove` to the row containing index `end_remove`", "snippet": "df.loc[(df.index < start_remove) | (df.index > end_remove)]", "question_id": 41513324 }, { "intent": "How to count the Nan values in the column in Panda Data frame", "rewritten_intent": "Get the number of NaN values in each column of dataframe `df`", "snippet": "df.isnull().sum()", "question_id": 26266362 }, { "intent": "Turn Pandas Multi-Index into column", "rewritten_intent": "reset index of dataframe `df`so that existing index values are transferred into `df`as columns", "snippet": "df.reset_index(inplace=True)", "question_id": 20110170 }, { "intent": "python getting a list of value from list of dict", "rewritten_intent": "generate a list containing values associated with the key 'value' of each dictionary inside list `list_of_dicts`", "snippet": "[x['value'] for x in list_of_dicts]", "question_id": 7271482 }, { "intent": "python getting a list of value from list of dict", "rewritten_intent": null, "snippet": "[d['value'] for d in l]", "question_id": 7271482 }, { "intent": "python getting a list of value from list of dict", "rewritten_intent": null, "snippet": "[d['value'] for d in l if 'value' in d]", "question_id": 7271482 }, { "intent": "Converting NumPy array into Python List structure?", "rewritten_intent": "convert numpy array into python list structure", "snippet": "np.array([[1, 2, 3], [4, 5, 6]]).tolist()", "question_id": 1966207 }, { "intent": "Converting string to tuple and adding to tuple", "rewritten_intent": "converting string '(1,2,3,4)' to a tuple", "snippet": "ast.literal_eval('(1,2,3,4)')", "question_id": 3945856 }, { "intent": "How to keep a list of lists sorted as it is created", "rewritten_intent": "keep a list `dataList` of lists sorted as it is created by second element", "snippet": "dataList.sort(key=lambda x: x[1])", "question_id": 12324456 }, { "intent": "Python: Uniqueness for list of lists", "rewritten_intent": "remove duplicated items from list of lists `testdata`", "snippet": "list(map(list, set(map(lambda i: tuple(i), testdata))))", "question_id": 3724551 }, { "intent": "Python: Uniqueness for list of lists", "rewritten_intent": "uniqueness for list of lists `testdata`", "snippet": "[list(i) for i in set(tuple(i) for i in testdata)]", "question_id": 3724551 }, { "intent": "In Django, how do I check if a user is in a certain group?", "rewritten_intent": "in django, check if a user is in a group 'Member'", "snippet": "return user.groups.filter(name='Member').exists()", "question_id": 4789021 }, { "intent": "In Django, how do I check if a user is in a certain group?", "rewritten_intent": "check if a user `user` is in a group from list of groups `['group1', 'group2']`", "snippet": "return user.groups.filter(name__in=['group1', 'group2']).exists()", "question_id": 4789021 }, { "intent": "Dynamically changing log level in python without restarting the application", "rewritten_intent": "Change log level dynamically to 'DEBUG' without restarting the application", "snippet": "logging.getLogger().setLevel(logging.DEBUG)", "question_id": 19617355 }, { "intent": "How to transform a tuple to a string of values without comma and parentheses", "rewritten_intent": "Concat each values in a tuple `(34.2424, -64.2344, 76.3534, 45.2344)` to get a string", "snippet": "\"\"\"\"\"\".join(str(i) for i in (34.2424, -64.2344, 76.3534, 45.2344))", "question_id": 17426386 }, { "intent": "What is the simplest way to swap char in a string with Python?", "rewritten_intent": "swap each pair of characters in string `s`", "snippet": "\"\"\"\"\"\".join([s[x:x + 2][::-1] for x in range(0, len(s), 2)])", "question_id": 4605439 }, { "intent": "Drawing a huge graph with networkX and matplotlib", "rewritten_intent": "save current figure to file 'graph.png' with resolution of 1000 dpi", "snippet": "plt.savefig('graph.png', dpi=1000)", "question_id": 9402255 }, { "intent": "delete items from list of list: pythonic way", "rewritten_intent": "delete items from list `my_list` if the item exist in list `to_dell`", "snippet": "my_list = [[x for x in sublist if x not in to_del] for sublist in my_list]", "question_id": 41313232 }, { "intent": "Find an element in a list of tuples", "rewritten_intent": "find all the elements that consists value '1' in a list of tuples 'a'", "snippet": "[item for item in a if 1 in item]", "question_id": 2191699 }, { "intent": "Find an element in a list of tuples", "rewritten_intent": "find all elements in a list of tuples `a` where the first element of each tuple equals 1", "snippet": "[item for item in a if item[0] == 1]", "question_id": 2191699 }, { "intent": "How can I get the index value of a list comprehension?", "rewritten_intent": "Get the index value in list `p_list` using enumerate in list comprehension", "snippet": "{p.id: {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}", "question_id": 18816297 }, { "intent": "how to uniqify a list of dict in python", "rewritten_intent": null, "snippet": "[dict(y) for y in set(tuple(x.items()) for x in d)]", "question_id": 6280978 }, { "intent": "How do I load a file into the python console?", "rewritten_intent": "load a file `file.py` into the python console", "snippet": "exec(compile(open('file.py').read(), 'file.py', 'exec'))", "question_id": 5280178 }, { "intent": "Get the number of rows in table using SQLAlchemy", "rewritten_intent": "SQLAlchemy count the number of rows in table `Congress`", "snippet": "rows = session.query(Congress).count()", "question_id": 10822635 }, { "intent": "Execute Shell Script from python with variable", "rewritten_intent": null, "snippet": "subprocess.call(['test.sh', str(domid)])", "question_id": 18742657 }, { "intent": "How to read a .xlsx file using the pandas Library in iPython?", "rewritten_intent": "read excel file `file_name` using pandas", "snippet": "dfs = pd.read_excel(file_name, sheetname=None)", "question_id": 16888888 }, { "intent": "Reading hex to double-precision float python", "rewritten_intent": "unpack the binary data represented by the hexadecimal string '4081637ef7d0424a' to a float", "snippet": "struct.unpack('d', binascii.unhexlify('4081637ef7d0424a'))", "question_id": 38831808 }, { "intent": "Indexing numpy array with another numpy array", "rewritten_intent": "Get index of numpy array `a` with another numpy array `b`", "snippet": "a[tuple(b)]", "question_id": 5508352 }, { "intent": "How to find all possible sequences of elements in a list?", "rewritten_intent": "find all possible sequences of elements in a list `[2, 3, 4]`", "snippet": "map(list, permutations([2, 3, 4]))", "question_id": 9040939 }, { "intent": "Sort a list in python based on another sorted list", "rewritten_intent": "sort a list `unsorted_list` based on another sorted list `presorted_list`", "snippet": "sorted(unsorted_list, key=presorted_list.index)", "question_id": 36518800 }, { "intent": "How to get yesterday in python", "rewritten_intent": null, "snippet": "datetime.datetime.now() - datetime.timedelta(days=1)", "question_id": 19779790 }, { "intent": "Creating a zero-filled pandas data frame", "rewritten_intent": "create a dataframe `d` filled with zeros with indices from 0 to length of `data` and column names from `feature_list`", "snippet": "d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)", "question_id": 22963263 }, { "intent": "string find", "rewritten_intent": "find the index of sub string 'World' in `x`", "snippet": "x.find('World')", "question_id": 674764 }, { "intent": "string find", "rewritten_intent": "find the index of sub string 'Aloha' in `x`", "snippet": "x.find('Aloha')", "question_id": 674764 }, { "intent": "string find", "rewritten_intent": "find the index of sub string 'cc' in string 'sdfasdf'", "snippet": "'sdfasdf'.index('cc')", "question_id": 674764 }, { "intent": "string find", "rewritten_intent": "find the index of sub string 'df' in string 'sdfasdf'", "snippet": "'sdfasdf'.index('df')", "question_id": 674764 }, { "intent": "string find", "rewritten_intent": "find the index of sub string 'a' in string `str`", "snippet": "str.find('a')", "question_id": 674764 }, { "intent": "string find", "rewritten_intent": "find the index of sub string 'g' in string `str`", "snippet": "str.find('g')", "question_id": 674764 }, { "intent": "string find", "rewritten_intent": "find the index of sub string 's' in string `str` starting from index 11", "snippet": "str.find('s', 11)", "question_id": 674764 }, { "intent": "string find", "rewritten_intent": "find the index of sub string 's' in string `str` starting from index 15", "snippet": "str.find('s', 15)", "question_id": 674764 }, { "intent": "string find", "rewritten_intent": "find the index of sub string 's' in string `str` starting from index 16", "snippet": "str.find('s', 16)", "question_id": 674764 }, { "intent": "string find", "rewritten_intent": "find the index of sub string 's' in string `str` starting from index 11 and ending at index 14", "snippet": "str.find('s', 11, 14)", "question_id": 674764 }, { "intent": "Sort list of date strings", "rewritten_intent": "sort list of date strings 'd'", "snippet": "sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))", "question_id": 17627531 }, { "intent": "Regular expression in Python sentence extractor", "rewritten_intent": "Get all the sentences from a string `text` using regex", "snippet": "re.split('\\\\.\\\\s', text)", "question_id": 27946742 }, { "intent": "Regular expression in Python sentence extractor", "rewritten_intent": null, "snippet": "re.split('\\\\.\\\\s', re.sub('\\\\.\\\\s*$', '', text))", "question_id": 27946742 }, { "intent": "Python - How to cut a string in Python?", "rewritten_intent": "get all characters in string 'foobar' up to the fourth index", "snippet": "\"\"\"foobar\"\"\"[:4]", "question_id": 8247792 }, { "intent": "Python - How to cut a string in Python?", "rewritten_intent": "cut a string by delimiter '&'", "snippet": "s.rfind('&')", "question_id": 8247792 }, { "intent": "Python - How to cut a string in Python?", "rewritten_intent": "cut a string using delimiter '&'", "snippet": "s[:s.rfind('&')]", "question_id": 8247792 }, { "intent": "Using a variable in xpath in Python Selenium", "rewritten_intent": "find a tag `option` whose `value` attribute is `state` in selenium", "snippet": "driver.find_element_by_xpath(\"//option[@value='\" + state + \"']\").click()", "question_id": 32874539 }, { "intent": "append to a file", "rewritten_intent": "append line \"appended text\" to file \"test.txt\"", "snippet": "with open('test.txt', 'a') as myfile:\n myfile.write('appended text')", "question_id": 4706499 }, { "intent": "append to a file", "rewritten_intent": "append line \"cool beans...\" to file \"foo\"", "snippet": "with open('foo', 'a') as f:\n f.write('cool beans...')", "question_id": 4706499 }, { "intent": "append to a file", "rewritten_intent": "append to file 'test1' content 'koko'", "snippet": "with open('test1', 'ab') as f:\n pass", "question_id": 4706499 }, { "intent": "append to a file", "rewritten_intent": "append to file 'test' content 'koko'", "snippet": "open('test', 'a+b').write('koko')", "question_id": 4706499 }, { "intent": "How can I split a string into tokens?", "rewritten_intent": "split string 'x+13.5*10x-4e1' into tokens", "snippet": "print([i for i in re.split('([\\\\d.]+|\\\\W+)', 'x+13.5*10x-4e1') if i])", "question_id": 18312447 }, { "intent": "Python: Check if a string contains chinese character?", "rewritten_intent": "Find all Chinese characters in string `ipath`", "snippet": "re.findall('[\\u4e00-\\u9fff]+', ipath)", "question_id": 34587346 }, { "intent": "String splitting in Python", "rewritten_intent": "split string `s` by letter 's'", "snippet": "s.split('s')", "question_id": 13128565 }, { "intent": "How to start a background process in Python?", "rewritten_intent": "run shell command 'rm -r some.file' in the background", "snippet": "subprocess.Popen(['rm', '-r', 'some.file'])", "question_id": 1196074 }, { "intent": "Elegant way to transform a list of dict into a dict of dicts", "rewritten_intent": "convert a list of dictionaries `listofdict into a dictionary of dictionaries", "snippet": "dict((d['name'], d) for d in listofdict)", "question_id": 8303993 }, { "intent": "print date in a regular format", "rewritten_intent": "print current date and time in a regular format", "snippet": "datetime.datetime.now().strftime('%Y-%m-%d %H:%M')", "question_id": 311627 }, { "intent": "print date in a regular format", "rewritten_intent": "print current date and time in a regular format", "snippet": "time.strftime('%Y-%m-%d %H:%M')", "question_id": 311627 }, { "intent": "Finding consecutive consonants in a word", "rewritten_intent": "find consecutive consonants in a word `CONCENTRATION` using regex", "snippet": "re.findall('[bcdfghjklmnpqrstvwxyz]+', 'CONCERTATION', re.IGNORECASE)", "question_id": 27744882 }, { "intent": "How do I get a list of indices of non zero elements in a list?", "rewritten_intent": "get a list of indices of non zero elements in a list `a`", "snippet": "[i for i, e in enumerate(a) if e != 0]", "question_id": 4111412 }, { "intent": "How to get integer values from a string in Python?", "rewritten_intent": "get multiple integer values from a string 'string1'", "snippet": "map(int, re.findall('\\\\d+', string1))", "question_id": 11339210 }, { "intent": "How can I know python's path under windows?", "rewritten_intent": "get the path of Python executable under windows", "snippet": "os.path.dirname(sys.executable)", "question_id": 647515 }, { "intent": "Moving x-axis to the top of a plot in matplotlib", "rewritten_intent": "move an x-axis label to the top of a plot `ax` in matplotlib", "snippet": "ax.xaxis.set_label_position('top')", "question_id": 14406214 }, { "intent": "Moving x-axis to the top of a plot in matplotlib", "rewritten_intent": "move x-axis to the top of a plot `ax`", "snippet": "ax.xaxis.tick_top()", "question_id": 14406214 }, { "intent": "Moving x-axis to the top of a plot in matplotlib", "rewritten_intent": "Move x-axis of the pyplot object `ax` to the top of a plot in matplotlib", "snippet": "ax.xaxis.set_ticks_position('top')", "question_id": 14406214 }, { "intent": "Parsing non-zero padded timestamps in Python", "rewritten_intent": "parse string '2015/01/01 12:12am' to DateTime object using format '%Y/%m/%d %I:%M%p'", "snippet": "datetime.strptime('2015/01/01 12:12am', '%Y/%m/%d %I:%M%p')", "question_id": 25279993 }, { "intent": "Open images", "rewritten_intent": "Open image 'picture.jpg'", "snippet": "img = Image.open('picture.jpg')\nimg.show()", "question_id": 16387069 }, { "intent": "Open images", "rewritten_intent": "Open image \"picture.jpg\"", "snippet": "img = Image.open('picture.jpg')\nImg.show", "question_id": 16387069 }, { "intent": "How do I abort the execution of a Python script?", "rewritten_intent": "terminate the script using status value 0", "snippet": "sys.exit(0)", "question_id": 179369 }, { "intent": "How do I abort the execution of a Python script?", "rewritten_intent": "abort the execution of the script using message 'aa! errors!'", "snippet": "sys.exit('aa! errors!')", "question_id": 179369 }, { "intent": "How do I abort the execution of a Python script?", "rewritten_intent": "abort the execution of a python script", "snippet": "sys.exit()", "question_id": 179369 }, { "intent": "Find maximum with limited length in a list", "rewritten_intent": "find maximum with lookahead = 4 in a list `arr`", "snippet": "[max(abs(x) for x in arr[i:i + 4]) for i in range(0, len(arr), 4)]", "question_id": 34543513 }, { "intent": "How to set the current working directory in Python?", "rewritten_intent": "set the current working directory to 'c:\\\\Users\\\\uname\\\\desktop\\\\python'", "snippet": "os.chdir('c:\\\\Users\\\\uname\\\\desktop\\\\python')", "question_id": 1810743 }, { "intent": "How to set the current working directory in Python?", "rewritten_intent": "set the current working directory to path `path`", "snippet": "os.chdir(path)", "question_id": 1810743 }, { "intent": "How to remove all integer values from a list in python", "rewritten_intent": "get a list `no_integers` of all the items in list `mylist` that are not of type `int`", "snippet": "no_integers = [x for x in mylist if not isinstance(x, int)]", "question_id": 3159155 }, { "intent": "How do I match contents of an element in XPath (lxml)?", "rewritten_intent": "match contents of an element to 'Example' in xpath (lxml)", "snippet": "tree.xpath(\".//a[text()='Example']\")[0].tag", "question_id": 2637760 }, { "intent": "convert dictionaries into string python", "rewritten_intent": "concatenate key/value pairs in dictionary `a` with string ', ' into a single string", "snippet": "\"\"\", \"\"\".join([(str(k) + ' ' + str(v)) for k, v in list(a.items())])", "question_id": 40512124 }, { "intent": "Detecting non-ascii characters in unicode string", "rewritten_intent": "Strip all non-ASCII characters from a unicode string, `\\xa3\\u20ac\\xa3\\u20ac`", "snippet": "print(set(re.sub('[\\x00-\\x7f]', '', '\\xa3\\u20ac\\xa3\\u20ac')))", "question_id": 16866261 }, { "intent": "Detecting non-ascii characters in unicode string", "rewritten_intent": "Get all non-ascii characters in a unicode string `\\xa3100 is worth more than \\u20ac100`", "snippet": "print(re.sub('[\\x00-\\x7f]', '', '\\xa3100 is worth more than \\u20ac100'))", "question_id": 16866261 }, { "intent": "Convert a String representation of a Dictionary to a dictionary?", "rewritten_intent": "build a dict of key:value pairs from a string representation of a dict, `{'muffin' : 'lolz', 'foo' : 'kitty'}`", "snippet": "ast.literal_eval(\"{'muffin' : 'lolz', 'foo' : 'kitty'}\")", "question_id": 988228 }, { "intent": "Easiest way to remove unicode representations from a string in python 3?", "rewritten_intent": "Print string `t` with proper unicode representations", "snippet": "print(t.decode('unicode_escape'))", "question_id": 13793973 }, { "intent": "String encoding and decoding from possibly latin1 and utf8", "rewritten_intent": "Normalize string `str` from 'cp1252' code to 'utf-8' code", "snippet": "print(str.encode('cp1252').decode('utf-8').encode('cp1252').decode('utf-8'))", "question_id": 10525301 }, { "intent": "merge lists into a list of tuples", "rewritten_intent": "merge lists `list_a` and `list_b` into a list of tuples", "snippet": "zip(list_a, list_b)", "question_id": 2407398 }, { "intent": "merge lists into a list of tuples", "rewritten_intent": "merge lists `a` and `a` into a list of tuples", "snippet": "list(zip(a, b))", "question_id": 2407398 }, { "intent": "python pandas dataframe to dictionary", "rewritten_intent": "convert pandas DataFrame `df` to a dictionary using `id` field as the key", "snippet": "df.set_index('id').to_dict()", "question_id": 18695605 }, { "intent": "python pandas dataframe to dictionary", "rewritten_intent": "convert pandas dataframe `df` with fields 'id', 'value' to dictionary", "snippet": "df.set_index('id')['value'].to_dict()", "question_id": 18695605 }, { "intent": "Can I sort text by its numeric value in Python?", "rewritten_intent": null, "snippet": "sorted(list(mydict.items()), key=lambda a: map(int, a[0].split('.')))", "question_id": 1534542 }, { "intent": "How can I remove text within parentheses with a regex?", "rewritten_intent": "remove parentheses and text within it in string `filename`", "snippet": "re.sub('\\\\([^)]*\\\\)', '', filename)", "question_id": 640001 }, { "intent": "How can I tell if a string only contains letter AND spaces", "rewritten_intent": "Check if string 'a b' only contains letters and spaces", "snippet": "\"\"\"a b\"\"\".replace(' ', '').isalpha()", "question_id": 29454773 }, { "intent": "Add SUM of values of two LISTS into new LIST", "rewritten_intent": "sum each element `x` in list `first` with element `y` at the same index in list `second`.", "snippet": "[(x + y) for x, y in zip(first, second)]", "question_id": 14050824 }, { "intent": "How to sort a Python dictionary by value?", "rewritten_intent": "sort a python dictionary `a_dict` by element `1` of the value", "snippet": "sorted(list(a_dict.items()), key=lambda item: item[1][1])", "question_id": 11932729 }, { "intent": "How to exclude a character from a regex group?", "rewritten_intent": null, "snippet": "re.compile('[^a-zA-Z0-9-]+')", "question_id": 4108561 }, { "intent": "Get index of the top n values of a list in python", "rewritten_intent": "get index of the biggest 2 values of a list `a`", "snippet": "sorted(list(range(len(a))), key=lambda i: a[i])[-2:]", "question_id": 13070461 }, { "intent": "Get index of the top n values of a list in python", "rewritten_intent": "get indexes of the largest `2` values from a list `a` using itemgetter", "snippet": "zip(*sorted(enumerate(a), key=operator.itemgetter(1)))[0][-2:]", "question_id": 13070461 }, { "intent": "Get index of the top n values of a list in python", "rewritten_intent": "get the indexes of the largest `2` values from a list of integers `a`", "snippet": "sorted(list(range(len(a))), key=lambda i: a[i], reverse=True)[:2]", "question_id": 13070461 }, { "intent": "How to get the index with the key in Python dictionary?", "rewritten_intent": "get index of key 'c' in dictionary `x`", "snippet": "list(x.keys()).index('c')", "question_id": 14538885 }, { "intent": "How to print +1 in Python, as +1 (with plus sign) instead of 1?", "rewritten_intent": "Print +1 using format '{0:+d}'", "snippet": "print('{0:+d}'.format(score))", "question_id": 8337004 }, { "intent": "Remove adjacent duplicate elements from a list", "rewritten_intent": "remove adjacent duplicate elements from a list `[1, 2, 2, 3, 2, 2, 4]`", "snippet": "[k for k, g in itertools.groupby([1, 2, 2, 3, 2, 2, 4])]", "question_id": 3460161 }, { "intent": "Converting a String to List in Python", "rewritten_intent": "split string \"0,1,2\" based on delimiter ','", "snippet": "\"\"\"0,1,2\"\"\".split(',')", "question_id": 2168123 }, { "intent": "Converting a String to List in Python", "rewritten_intent": "convert the string '0,1,2' to a list of integers", "snippet": "[int(x) for x in '0,1,2'.split(',')]", "question_id": 2168123 }, { "intent": "Python: Convert list of key-value tuples into dictionary?", "rewritten_intent": "convert list of key-value tuples `[('A', 1), ('B', 2), ('C', 3)]` into dictionary", "snippet": "dict([('A', 1), ('B', 2), ('C', 3)])", "question_id": 6586310 }, { "intent": "How to write a multidimensional array to a text file?", "rewritten_intent": "save numpy array `x` into text file 'test.txt'", "snippet": "np.savetxt('test.txt', x)", "question_id": 3685265 }, { "intent": "How to store os.system() output in a variable or a list in python", "rewritten_intent": "store the output of command 'ls' in variable `direct_output`", "snippet": "direct_output = subprocess.check_output('ls', shell=True)", "question_id": 19267591 }, { "intent": "Select everything but a list of columns from pandas dataframe", "rewritten_intent": "get all column name of dataframe `df` except for column 'T1_V6'", "snippet": "df[df.columns - ['T1_V6']]", "question_id": 32032836 }, { "intent": "How to count values in a certain range in a Numpy array?", "rewritten_intent": "get count of values in numpy array `a` that are between values `25` and `100`", "snippet": "((25 < a) & (a < 100)).sum()", "question_id": 9560207 }, { "intent": "how to get day name in datetime in python", "rewritten_intent": "Get day name from a datetime object", "snippet": "date.today().strftime('%A')", "question_id": 8380389 }, { "intent": "Python regular expression match whole word", "rewritten_intent": null, "snippet": "re.search('\\\\bis\\\\b', your_string)", "question_id": 15863066 }, { "intent": "Python: How do I format a date in Jinja2?", "rewritten_intent": "Jinja parse datetime object `car.date_of_manufacture` to use format pattern `datetime`", "snippet": "{{car.date_of_manufacture | datetime}}", "question_id": 4830535 }, { "intent": "Python: How do I format a date in Jinja2?", "rewritten_intent": "Get the date object `date_of_manufacture` of object `car` in string format '%Y-%m-%d'", "snippet": "{{car.date_of_manufacture.strftime('%Y-%m-%d')}}", "question_id": 4830535 }, { "intent": "Making a flat list out of list of lists", "rewritten_intent": "make a flat list from list of lists `sublist`", "snippet": "[item for sublist in l for item in sublist]", "question_id": 952914 }, { "intent": "Making a flat list out of list of lists", "rewritten_intent": "make a flat list from list of lists `list2d`", "snippet": "list(itertools.chain(*list2d))", "question_id": 952914 }, { "intent": "Making a flat list out of list of lists", "rewritten_intent": "make a flat list from list of lists `list2d`", "snippet": "list(itertools.chain.from_iterable(list2d))", "question_id": 952914 }, { "intent": "Convert int to ASCII and back in Python", "rewritten_intent": "convert ascii value 'a' to int", "snippet": "ord('a')", "question_id": 3673428 }, { "intent": "Python: use regular expression to remove the white space from all lines", "rewritten_intent": "replace white spaces in string ' a\\n b\\n c\\nd e' with empty string ''", "snippet": "re.sub('(?m)^[^\\\\S\\\\n]+', '', ' a\\n b\\n c\\nd e')", "question_id": 3984539 }, { "intent": "Python: use regular expression to remove the white space from all lines", "rewritten_intent": "remove white spaces from all the lines using a regular expression in string 'a\\n b\\n c'", "snippet": "re.sub('(?m)^\\\\s+', '', 'a\\n b\\n c')", "question_id": 3984539 }, { "intent": "Python: Assign each element of a List to a separate Variable", "rewritten_intent": "destruct elements of list `[1, 2, 3]` to variables `a`, `b` and `c`", "snippet": "a, b, c = [1, 2, 3]", "question_id": 19300174 }, { "intent": "Python split a list into subsets based on pattern", "rewritten_intent": "split list `mylist` into a list of lists whose elements have the same first five characters", "snippet": "[list(v) for k, v in itertools.groupby(mylist, key=lambda x: x[:5])]", "question_id": 13368723 }, { "intent": "Regular expression substitution in Python", "rewritten_intent": "remove all instances of parenthesesis containing text beginning with `as ` from string `line`", "snippet": "line = re.sub('\\\\(+as .*?\\\\) ', '', line)", "question_id": 37584492 }, { "intent": "How to skip the extra newline while printing lines read from a file?", "rewritten_intent": "skip the newline while printing `line`", "snippet": "print(line.rstrip('\\n'))", "question_id": 17027690 }, { "intent": "Get index values of Pandas DataFrame as list?", "rewritten_intent": "get index values of pandas dataframe `df` as list", "snippet": "df.index.values.tolist()", "question_id": 18358938 }, { "intent": "check if a list is empty", "rewritten_intent": "check if list `a` is empty", "snippet": "if (not a):\n pass", "question_id": 53513 }, { "intent": "check if a list is empty", "rewritten_intent": "check if list `seq` is empty", "snippet": "if (not seq):\n pass", "question_id": 53513 }, { "intent": "check if a list is empty", "rewritten_intent": "check if list `li` is empty", "snippet": "if (len(li) == 0):\n pass", "question_id": 53513 }, { "intent": "Find the indices of elements greater than x", "rewritten_intent": "create a list containing the indices of elements greater than 4 in list `a`", "snippet": "[i for i, v in enumerate(a) if v > 4]", "question_id": 13717463 }, { "intent": "sorting list of nested dictionaries in python", "rewritten_intent": "reverse list `yourdata`", "snippet": "sorted(yourdata, reverse=True)", "question_id": 13237941 }, { "intent": "sorting list of nested dictionaries in python", "rewritten_intent": "sort list of nested dictionaries `yourdata` in reverse based on values associated with each dictionary's key 'subkey'", "snippet": "sorted(yourdata, key=lambda d: d.get('key', {}).get('subkey'), reverse=True)", "question_id": 13237941 }, { "intent": "sorting list of nested dictionaries in python", "rewritten_intent": "sort list of nested dictionaries `yourdata` in reverse order of 'key' and 'subkey'", "snippet": "yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)", "question_id": 13237941 }, { "intent": "How to remove decimal points in pandas", "rewritten_intent": "remove decimal points in pandas data frame using round", "snippet": "df.round()", "question_id": 37084812 }, { "intent": "How to extract data from matplotlib plot", "rewritten_intent": "Get data from matplotlib plot", "snippet": "gca().get_lines()[n].get_xydata()", "question_id": 8938449 }, { "intent": "How to get the N maximum values per row in a numpy ndarray?", "rewritten_intent": "get the maximum 2 values per row in array `A`", "snippet": "A[:, -2:]", "question_id": 37125495 }, { "intent": "MultiValueDictKeyError in Django", "rewritten_intent": "Get value for \"username\" parameter in GET request in Django", "snippet": "request.GET.get('username', '')", "question_id": 23531030 }, { "intent": "Any way to properly pretty-print ordered dictionaries in Python?", "rewritten_intent": "pretty-print ordered dictionary `o`", "snippet": "pprint(dict(list(o.items())))", "question_id": 4301069 }, { "intent": "Django can't find URL pattern", "rewritten_intent": "Confirm urls in Django properly", "snippet": "url('^$', include('sms.urls')),", "question_id": 32458541 }, { "intent": "Django can't find URL pattern", "rewritten_intent": "Configure url in django properly", "snippet": "url('^', include('sms.urls')),", "question_id": 32458541 }, { "intent": "Pythonic way to get the largest item in a list", "rewritten_intent": "get the tuple in list `a_list` that has the largest item in the second index", "snippet": "max_item = max(a_list, key=operator.itemgetter(1))", "question_id": 1874194 }, { "intent": "Pythonic way to get the largest item in a list", "rewritten_intent": "find tuple in list of tuples `a_list` with the largest second element", "snippet": "max(a_list, key=operator.itemgetter(1))", "question_id": 1874194 }, { "intent": "How to iterate over time periods in pandas", "rewritten_intent": "resample series `s` into 3 months bins and sum each bin", "snippet": "s.resample('3M', how='sum')", "question_id": 29100599 }, { "intent": "how to extract elements from a list in python?", "rewritten_intent": "extract elements at indices (1, 2, 5) from a list `a`", "snippet": "[a[i] for i in (1, 2, 5)]", "question_id": 2621674 }, { "intent": "Python: Filter lines from a text file which contain a particular word", "rewritten_intent": "filter lines from a text file 'textfile' which contain a word 'apple'", "snippet": "[line for line in open('textfile') if 'apple' in line]", "question_id": 5245058 }, { "intent": "How to convert a Date string to a DateTime object?", "rewritten_intent": "convert a date string `s` to a datetime object", "snippet": "datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')", "question_id": 2721782 }, { "intent": "Reading tab-delimited file with Pandas - works on Windows, but not on Mac", "rewritten_intent": "reading tab-delimited csv file `filename` with pandas on mac", "snippet": "pandas.read_csv(filename, sep='\\t', lineterminator='\\r')", "question_id": 27896214 }, { "intent": "Replace first occurence of string", "rewritten_intent": "replace only first occurence of string `TEST` from a string `longlongTESTstringTEST`", "snippet": "'longlongTESTstringTEST'.replace('TEST', '?', 1)", "question_id": 4628618 }, { "intent": "How can I zip file with a flattened directory structure using Zipfile in Python?", "rewritten_intent": "zip file `pdffile` using its basename as directory name", "snippet": "archive.write(pdffile, os.path.basename(pdffile))", "question_id": 12777222 }, { "intent": "Elegant way to create a dictionary of pairs, from a list of tuples?", "rewritten_intent": "create a dictionary of pairs from a list of tuples `myListOfTuples`", "snippet": "dict(x[1:] for x in reversed(myListOfTuples))", "question_id": 3457673 }, { "intent": "How to subtract two lists in python", "rewritten_intent": "subtract elements of list `List1` from elements of list `List2`", "snippet": "[(x1 - x2) for x1, x2 in zip(List1, List2)]", "question_id": 8194156 }, { "intent": "How to tell if string starts with a number?", "rewritten_intent": "check if string `string` starts with a number", "snippet": "string[0].isdigit()", "question_id": 5577501 }, { "intent": "How to tell if string starts with a number?", "rewritten_intent": "Check if string `strg` starts with any of the elements in list ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')", "snippet": "strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))", "question_id": 5577501 }, { "intent": "How can I find script's directory with Python?", "rewritten_intent": "print script's directory", "snippet": "print(os.path.dirname(os.path.realpath(__file__)))", "question_id": 4934806 }, { "intent": "Finding the surrounding sentence of a char/word in a string", "rewritten_intent": "split string `text` by the occurrences of regex pattern '(?<=\\\\?|!|\\\\.)\\\\s{0,2}(?=[A-Z]|$)'", "snippet": "re.split('(?<=\\\\?|!|\\\\.)\\\\s{0,2}(?=[A-Z]|$)', text)", "question_id": 15530399 }, { "intent": "Plotting a list of (x, y) coordinates in python matplotlib", "rewritten_intent": "Make a scatter plot using unpacked values of list `li`", "snippet": "plt.scatter(*zip(*li))", "question_id": 21519203 }, { "intent": "Rearrange tuple of tuples in Python", "rewritten_intent": "rearrange tuple of tuples `t`", "snippet": "tuple(zip(*t))", "question_id": 16040156 }, { "intent": "Find Average of Every Three Columns in Pandas dataframe", "rewritten_intent": "Get average for every three columns in `df` dataframe", "snippet": "df.groupby(np.arange(len(df.columns)) // 3, axis=1).mean()", "question_id": 40963347 }, { "intent": "How do I convert a list of ascii values to a string in python?", "rewritten_intent": "convert a list `L` of ascii values to a string", "snippet": "\"\"\"\"\"\".join(chr(i) for i in L)", "question_id": 180606 }, { "intent": "Python 2.7 Counting number of dictionary items with given value", "rewritten_intent": "count the number of pairs in dictionary `d` whose value equal to `chosen_value`", "snippet": "sum(x == chosen_value for x in list(d.values()))", "question_id": 13462365 }, { "intent": "Python 2.7 Counting number of dictionary items with given value", "rewritten_intent": "count the number of values in `d` dictionary that are predicate to function `some_condition`", "snippet": "sum(1 for x in list(d.values()) if some_condition(x))", "question_id": 13462365 }, { "intent": "convert double to float in Python", "rewritten_intent": "convert double 0.00582811585976 to float", "snippet": "struct.unpack('f', struct.pack('f', 0.00582811585976))", "question_id": 13291539 }, { "intent": "Converting datetime.date to UTC timestamp in Python", "rewritten_intent": "convert datetime.date `dt` to utc timestamp", "snippet": "timestamp = (dt - datetime(1970, 1, 1)).total_seconds()", "question_id": 8777753 }, { "intent": "Custom sorting in pandas dataframe", "rewritten_intent": "sort column `m` in panda dataframe `df`", "snippet": "df.sort('m')", "question_id": 13838405 }, { "intent": "How to sort with lambda in Python", "rewritten_intent": "Sort a data `a` in descending order based on the `modified` attribute of elements using lambda function", "snippet": "a = sorted(a, key=lambda x: x.modified, reverse=True)", "question_id": 3766633 }, { "intent": "How can I print the Truth value of a variable?", "rewritten_intent": "print the truth value of `a`", "snippet": "print(bool(a))", "question_id": 39604780 }, { "intent": "How can I change a specific row label in a Pandas dataframe?", "rewritten_intent": "rename `last` row index label in dataframe `df` to `a`", "snippet": "df = df.rename(index={last: 'a'})", "question_id": 42142756 }, { "intent": "Scikit-learn: How to run KMeans on a one-dimensional array?", "rewritten_intent": "Fit Kmeans function to a one-dimensional array `x` by reshaping it to be a multidimensional array of single values", "snippet": "km.fit(x.reshape(-1, 1))", "question_id": 28416408 }, { "intent": "sorting a list in python", "rewritten_intent": "Sort a list of strings 'words' such that items starting with 's' come first.", "snippet": "sorted(words, key=lambda x: 'a' + x if x.startswith('s') else 'b' + x)", "question_id": 17608210 }, { "intent": "login to a site using python and opening the login site in the browser", "rewritten_intent": "open the login site 'http://somesite.com/adminpanel/index.php' in the browser", "snippet": "webbrowser.open('http://somesite.com/adminpanel/index.php')", "question_id": 21414159 }, { "intent": "Pythonic way to fetch all elements in a dictionary, falling between two keys?", "rewritten_intent": "fetch all elements in a dictionary `parent_dict`, falling between two keys 2 and 4", "snippet": "dict((k, v) for k, v in parent_dict.items() if 2 < k < 4)", "question_id": 8654637 }, { "intent": "Pythonic way to fetch all elements in a dictionary, falling between two keys?", "rewritten_intent": "fetch all elements in a dictionary 'parent_dict' where the key is between the range of 2 to 4", "snippet": "dict((k, v) for k, v in parent_dict.items() if k > 2 and k < 4)", "question_id": 8654637 }, { "intent": "python sorting two lists", "rewritten_intent": "sort two lists `list1` and `list2` together using lambda function", "snippet": "[list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0]))]", "question_id": 13668393 }, { "intent": "number of values in a list greater than a certain number", "rewritten_intent": "get the number of values in list `j` that is greater than 5", "snippet": "sum(((i > 5) for i in j))", "question_id": 10543303 }, { "intent": "number of values in a list greater than a certain number", "rewritten_intent": "get the number of values in list `j` that is greater than 5", "snippet": "len([1 for i in j if (i > 5)])", "question_id": 10543303 }, { "intent": "number of values in a list greater than a certain number", "rewritten_intent": "get the number of values in list `j` that is greater than `i`", "snippet": "j = np.array(j)\nsum((j > i))", "question_id": 10543303 }, { "intent": "Python: elegant way of creating a list of tuples?", "rewritten_intent": "zip list `a`, `b`, `c` into a list of tuples", "snippet": "[(x + tuple(y)) for x, y in zip(zip(a, b), c)]", "question_id": 12655007 }, { "intent": "Changing file permission in python", "rewritten_intent": "changing permission of file `path` to `stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH`", "snippet": "os.chmod(path, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)", "question_id": 16249440 }, { "intent": "Multiple files for one argument in argparse Python 2.7", "rewritten_intent": "argparse associate zero or more arguments with flag 'file'", "snippet": "parser.add_argument('file', nargs='*')", "question_id": 26727314 }, { "intent": "Comparing values in two lists in Python", "rewritten_intent": "get a list of booleans `z` that shows wether the corresponding items in list `x` and `y` are equal", "snippet": "z = [(i == j) for i, j in zip(x, y)]", "question_id": 32996293 }, { "intent": "Comparing values in two lists in Python", "rewritten_intent": "create a list which indicates whether each element in `x` and `y` is identical", "snippet": "[(x[i] == y[i]) for i in range(len(x))]", "question_id": 32996293 }, { "intent": "Python: Extract numbers from a string", "rewritten_intent": null, "snippet": "[int(s) for s in re.findall('\\\\b\\\\d+\\\\b', \"he33llo 42 I'm a 32 string 30\")]", "question_id": 4289331 }, { "intent": "Create an empty data frame with index from another data frame", "rewritten_intent": "create an empty data frame `df2` with index from another data frame `df1`", "snippet": "df2 = pd.DataFrame(index=df1.index)", "question_id": 18176933 }, { "intent": "How do I convert a string 2 bytes long to an integer in python", "rewritten_intent": "unpack first and second bytes of byte string `pS` into integer", "snippet": "struct.unpack('h', pS[0:2])", "question_id": 826284 }, { "intent": "Printing lists onto tables in python", "rewritten_intent": "print list `t` into a table-like shape", "snippet": "print('\\n'.join(' '.join(map(str, row)) for row in t))", "question_id": 16677816 }, { "intent": "Sort Pandas Dataframe by Date", "rewritten_intent": null, "snippet": "df.sort_values(by='Date')", "question_id": 28161356 }, { "intent": "How can I check if a checkbox is checked in Selenium Python Webdriver?", "rewritten_intent": "check if a checkbox is checked in selenium python webdriver", "snippet": "driver.find_element_by_name('').is_selected()", "question_id": 14442636 }, { "intent": "How can I check if a checkbox is checked in Selenium Python Webdriver?", "rewritten_intent": "determine if checkbox with id '' is checked in selenium python webdriver", "snippet": "driver.find_element_by_id('').is_selected()", "question_id": 14442636 }, { "intent": "Is it possible to use 'else' in a python list comprehension?", "rewritten_intent": "replace `0` with `2` in the list `[0, 1, 0, 3]`", "snippet": "[(a if a else 2) for a in [0, 1, 0, 3]]", "question_id": 2951701 }, { "intent": "Parsing string containing Unicode character names", "rewritten_intent": "Produce a string that is suitable as Unicode literal from string 'M\\\\N{AMPERSAND}M\\\\N{APOSTROPHE}s'", "snippet": "'M\\\\N{AMPERSAND}M\\\\N{APOSTROPHE}s'.encode().decode('unicode-escape')", "question_id": 30747705 }, { "intent": "Parsing string containing Unicode character names", "rewritten_intent": "Parse a unicode string `M\\\\N{AMPERSAND}M\\\\N{APOSTROPHE}s`", "snippet": "'M\\\\N{AMPERSAND}M\\\\N{APOSTROPHE}s'.decode('unicode-escape')", "question_id": 30747705 }, { "intent": "Convert unicode codepoint to UTF8 hex in python", "rewritten_intent": "convert Unicode codepoint to utf8 hex", "snippet": "chr(int('fd9b', 16)).encode('utf-8')", "question_id": 867866 }, { "intent": "How can I get Python to use upper case letters to print hex values?", "rewritten_intent": "use upper case letters to print hex value `value`", "snippet": "print('0x%X' % value)", "question_id": 13277440 }, { "intent": "How to remove empty string in a list?", "rewritten_intent": "get a list `cleaned` that contains all non-empty elements in list `your_list`", "snippet": "cleaned = [x for x in your_list if x]", "question_id": 16099694 }, { "intent": "Python: Want to use a string as a slice specifier", "rewritten_intent": "create a slice object using string `string_slice`", "snippet": "slice(*[(int(i.strip()) if i else None) for i in string_slice.split(':')])", "question_id": 13324554 }, { "intent": "Beautiful Soup Using Regex to Find Tags?", "rewritten_intent": "Find all the tags `a` and `div` from Beautiful Soup object `soup`", "snippet": "soup.find_all(['a', 'div'])", "question_id": 24748445 }, { "intent": "Get function name as a string in python", "rewritten_intent": "get the name of function `func` as a string", "snippet": "print(func.__name__)", "question_id": 7142062 }, { "intent": "How to convert dictionary into string", "rewritten_intent": "convert dictionary `adict` into string", "snippet": "\"\"\"\"\"\".join('{}{}'.format(key, val) for key, val in sorted(adict.items()))", "question_id": 10472907 }, { "intent": "How to convert dictionary into string", "rewritten_intent": "convert dictionary `adict` into string", "snippet": "\"\"\"\"\"\".join('{}{}'.format(key, val) for key, val in list(adict.items()))", "question_id": 10472907 }, { "intent": "copy a list", "rewritten_intent": "copy list `old_list` as `new_list`", "snippet": "new_list = old_list[:]", "question_id": 2612802 }, { "intent": "copy a list", "rewritten_intent": "copy list `old_list` as `new_list`", "snippet": "new_list = list(old_list)", "question_id": 2612802 }, { "intent": "copy a list", "rewritten_intent": "copy list `old_list` as `new_list`", "snippet": "new_list = copy.copy(old_list)", "question_id": 2612802 }, { "intent": "copy a list", "rewritten_intent": "deep copy list `old_list` as `new_list`", "snippet": "new_list = copy.deepcopy(old_list)", "question_id": 2612802 }, { "intent": "copy a list", "rewritten_intent": "make a copy of list `old_list`", "snippet": "[i for i in old_list]", "question_id": 2612802 }, { "intent": "Remove or adapt border of frame of legend using matplotlib", "rewritten_intent": "remove frame of legend in plot `plt`", "snippet": "plt.legend(frameon=False)", "question_id": 25540259 }, { "intent": "How to work with surrogate pairs in Python?", "rewritten_intent": "Print a emoji from a string `\\\\ud83d\\\\ude4f` having surrogate pairs", "snippet": "\"\"\"\\\\ud83d\\\\ude4f\"\"\".encode('utf-16', 'surrogatepass').decode('utf-16')", "question_id": 38147259 }, { "intent": "Calling a function of a module from a string with the function's name in Python", "rewritten_intent": "calling a function named 'myfunction' in the module", "snippet": "globals()['myfunction']()", "question_id": 3061 }, { "intent": "Checking if a website is up", "rewritten_intent": "Check the status code of url \"http://www.stackoverflow.com\"", "snippet": "urllib.request.urlopen('http://www.stackoverflow.com').getcode()", "question_id": 1949318 }, { "intent": "Checking if a website is up", "rewritten_intent": "Check the status code of url \"www.python.org\"", "snippet": "conn = httplib.HTTPConnection('www.python.org')\nconn.request('HEAD', '/')\nr1 = conn.getresponse()\nprint(r1.status, r1.reason)", "question_id": 1949318 }, { "intent": "Checking if a website is up", "rewritten_intent": "Check the status code of url `url`", "snippet": "r = requests.head(url)\nreturn (r.status_code == 200)", "question_id": 1949318 }, { "intent": "Checking if a website is up", "rewritten_intent": "Checking if website \"http://www.stackoverflow.com\" is up", "snippet": "print(urllib.request.urlopen('http://www.stackoverflow.com').getcode())", "question_id": 1949318 }, { "intent": "Selenium open pop up window [Python]", "rewritten_intent": "Selenium `driver` click a hyperlink with the pattern \"a[href^='javascript']\"", "snippet": "driver.find_element_by_css_selector(\"a[href^='javascript']\").click()", "question_id": 23931444 }, { "intent": "How to store data frame using PANDAS, Python", "rewritten_intent": "store data frame `df` to file `file_name` using pandas, python", "snippet": "df.to_pickle(file_name)", "question_id": 17098654 }, { "intent": "Pandas: Mean of columns with the same names", "rewritten_intent": "calculate the mean of columns with same name in dataframe `df`", "snippet": "df.groupby(by=df.columns, axis=1).mean()", "question_id": 40311987 }, { "intent": "How to perform double sort inside an array?", "rewritten_intent": "sort list `bar` by each element's attribute `attrb1` and attribute `attrb2` in reverse order", "snippet": "bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True)", "question_id": 4768151 }, { "intent": "How to get alpha value of a PNG image with PIL?", "rewritten_intent": "get alpha value `alpha` of a png image `img`", "snippet": "alpha = img.split()[-1]", "question_id": 1962795 }, { "intent": "How to get the length of words in a sentence?", "rewritten_intent": null, "snippet": "[len(x) for x in s.split()]", "question_id": 22749706 }, { "intent": "Find a specific tag with BeautifulSoup", "rewritten_intent": "BeautifulSoup find tag 'div' with styling 'width=300px;' in HTML string `soup`", "snippet": "soup.findAll('div', style='width=300px;')", "question_id": 3945750 }, { "intent": "Using a Python dict for a SQL INSERT statement", "rewritten_intent": "Execute SQL statement `sql` with values of dictionary `myDict` as parameters", "snippet": "cursor.execute(sql, list(myDict.values()))", "question_id": 9336270 }, { "intent": "Preserving Column Order - Python Pandas and Column Concat", "rewritten_intent": "Convert CSV file `Result.csv` to Pandas dataframe using separator ' '", "snippet": "df.to_csv('Result.csv', index=False, sep=' ')", "question_id": 32533944 }, { "intent": "Python: Extract variables out of namespace", "rewritten_intent": "update the `globals()` dictionary with the contents of the `vars(args)` dictionary", "snippet": "globals().update(vars(args))", "question_id": 8306171 }, { "intent": "Regular expression to return all characters between two special characters", "rewritten_intent": "find all substrings in `mystring` beginning and ending with square brackets", "snippet": "re.findall('\\\\[(.*?)\\\\]', mystring)", "question_id": 9889635 }, { "intent": "Python, print all floats to 2 decimal places in output", "rewritten_intent": "Format all floating variables `var1`, `var2`, `var3`, `var1` to print to two decimal places.", "snippet": "print('%.2f kg = %.2f lb = %.2f gal = %.2f l' % (var1, var2, var3, var4))", "question_id": 2075128 }, { "intent": "The best way to filter a dictionary in Python", "rewritten_intent": "Remove all items from a dictionary `d` where the values are less than `1`", "snippet": "d = dict((k, v) for k, v in d.items() if v > 0)", "question_id": 8425046 }, { "intent": "The best way to filter a dictionary in Python", "rewritten_intent": "Filter dictionary `d` to have items with value greater than 0", "snippet": "d = {k: v for k, v in list(d.items()) if v > 0}", "question_id": 8425046 }, { "intent": "In Pandas how do I convert a string of date strings to datetime objects and put them in a DataFrame?", "rewritten_intent": "convert a string of date strings `date_stngs ` to datetime objects and put them in a dataframe", "snippet": "pd.to_datetime(pd.Series(date_stngs))", "question_id": 17690738 }, { "intent": "Print the complete string of a pandas dataframe", "rewritten_intent": "get value at index `[2, 0]` in dataframe `df`", "snippet": "df.iloc[2, 0]", "question_id": 29902714 }, { "intent": "How to change the font size on a matplotlib plot", "rewritten_intent": "change the font size on plot `matplotlib` to 22", "snippet": "matplotlib.rcParams.update({'font.size': 22})", "question_id": 3899980 }, { "intent": "Convert Python dict into a dataframe", "rewritten_intent": "converting dictionary `d` into a dataframe `pd` with keys as data for column 'Date' and the corresponding values as data for column 'DateValue'", "snippet": "pd.DataFrame(list(d.items()), columns=['Date', 'DateValue'])", "question_id": 18837262 }, { "intent": "Pandas: Elementwise multiplication of two dataframes", "rewritten_intent": "create a dataframe containing the multiplication of element-wise in dataframe `df` and dataframe `df2` using index name and column labels of dataframe `df`", "snippet": "pd.DataFrame(df.values * df2.values, columns=df.columns, index=df.index)", "question_id": 21022865 }, { "intent": "How to extract a floating number from a string", "rewritten_intent": "extract floating number from string 'Current Level: 13.4 db.'", "snippet": "re.findall('\\\\d+\\\\.\\\\d+', 'Current Level: 13.4 db.')", "question_id": 4703390 }, { "intent": "How to extract a floating number from a string", "rewritten_intent": "extract floating point numbers from a string 'Current Level: -13.2 db or 14.2 or 3'", "snippet": "re.findall('[-+]?\\\\d*\\\\.\\\\d+|\\\\d+', 'Current Level: -13.2 db or 14.2 or 3')", "question_id": 4703390 }, { "intent": "Convert List to a list of tuples python", "rewritten_intent": "pair each element in list `it` 3 times into a tuple", "snippet": "zip(it, it, it)", "question_id": 23286254 }, { "intent": "How to lowercase a python dataframe string column if it has missing values?", "rewritten_intent": "lowercase a python dataframe string in column 'x' if it has missing values in dataframe `df`", "snippet": "df['x'].str.lower()", "question_id": 22245171 }, { "intent": "python append to array in json object", "rewritten_intent": "append dict `{'f': var6, 'g': var7, 'h': var8}` to value of key `e` in dict `jsobj['a']['b']`", "snippet": "jsobj['a']['b']['e'].append({'f': var6, 'g': var7, 'h': var8})", "question_id": 10895028 }, { "intent": "Most Pythonic way to concatenate strings", "rewritten_intent": "Concat a list of strings `lst` using string formatting", "snippet": "\"\"\"\"\"\".join(lst)", "question_id": 2133571 }, { "intent": "Python: Sum values in a dictionary based on condition", "rewritten_intent": "sum values greater than 0 in dictionary `d`", "snippet": "sum(v for v in list(d.values()) if v > 0)", "question_id": 15014276 }, { "intent": "Flask application traceback doesn't show up in server log", "rewritten_intent": "run flask application `app` in debug mode.", "snippet": "app.run(debug=True)", "question_id": 32722143 }, { "intent": "How to drop a list of rows from Pandas dataframe?", "rewritten_intent": "drop rows whose index value in list `[1, 3]` in dataframe `df`", "snippet": "df.drop(df.index[[1, 3]], inplace=True)", "question_id": 14661701 }, { "intent": "pandas DataFrame: replace nan values with average of columns", "rewritten_intent": "replace nan values in a pandas data frame with the average of columns", "snippet": "df.apply(lambda x: x.fillna(x.mean()), axis=0)", "question_id": 18689823 }, { "intent": "How to extract from a list of objects a list of specific attribute?", "rewritten_intent": "extract attribute `my_attr` from each object in list `my_list`", "snippet": "[o.my_attr for o in my_list]", "question_id": 677656 }, { "intent": "python get time stamp on file in mm/dd/yyyy format", "rewritten_intent": "python get time stamp on file `file` in '%m/%d/%Y' format", "snippet": "time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))", "question_id": 16994696 }, { "intent": "Python: Check if one dictionary is a subset of another larger dictionary", "rewritten_intent": "check if dictionary `subset` is a subset of dictionary `superset`", "snippet": "all(item in list(superset.items()) for item in list(subset.items()))", "question_id": 9323749 }, { "intent": "Python: for loop in index assignment", "rewritten_intent": "Convert integer elements in list `wordids` to strings", "snippet": "[str(wi) for wi in wordids]", "question_id": 7768859 }, { "intent": "Indexing a pandas dataframe by integer", "rewritten_intent": "Reset the indexes of a pandas data frame", "snippet": "df2 = df.reset_index()", "question_id": 11621165 }, { "intent": "Convert datetime object to a String of date only in Python", "rewritten_intent": "format datetime in `dt` as string in format `'%m/%d/%Y`", "snippet": "dt.strftime('%m/%d/%Y')", "question_id": 10624937 }, { "intent": "Python Add Comma Into Number String", "rewritten_intent": "format floating point number `TotalAmount` to be rounded off to two decimal places and have a comma thousands' seperator", "snippet": "print('Total cost is: ${:,.2f}'.format(TotalAmount))", "question_id": 5180365 }, { "intent": "Sum of Every Two Columns in Pandas dataframe", "rewritten_intent": "sum the values in each row of every two adjacent columns in dataframe `df`", "snippet": "df.groupby(np.arange(len(df.columns)) // 2 + 1, axis=1).sum().add_prefix('s')", "question_id": 40660956 }, { "intent": "creating list of random numbers in python", "rewritten_intent": "create list `randomList` with 10 random floating point numbers between 0.0 and 1.0", "snippet": "randomList = [random.random() for _ in range(10)]", "question_id": 20733827 }, { "intent": "beautifulsoup can't find href in file using regular expression", "rewritten_intent": "find href value that has string 'follow?page' inside it", "snippet": "print(soup.find('a', href=re.compile('.*follow\\\\?page.*')))", "question_id": 11066874 }, { "intent": "In Python, why won't something print without a newline?", "rewritten_intent": "immediately see output of print statement that doesn't end in a newline", "snippet": "sys.stdout.flush()", "question_id": 5917537 }, { "intent": "How to get a random value in python dictionary", "rewritten_intent": "get a random key `country` and value `capital` form a dictionary `d`", "snippet": "country, capital = random.choice(list(d.items()))", "question_id": 4859292 }, { "intent": "Is there a function in python to split a word into a list?", "rewritten_intent": "split string `Word to Split` into a list of characters", "snippet": "list('Word to Split')", "question_id": 113655 }, { "intent": "Regex: How to match words without consecutive vowels?", "rewritten_intent": "Create a list containing words that contain vowel letter followed by the same vowel in file 'file.text'", "snippet": "[w for w in open('file.txt') if not re.search('[aeiou]{2}', w)]", "question_id": 38862349 }, { "intent": "Using a RegEx to match IP addresses in Python", "rewritten_intent": "Validate IP address using Regex", "snippet": "pat = re.compile('^\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}$')", "question_id": 11264005 }, { "intent": "How to execute a file within the python interpreter?", "rewritten_intent": "execute file 'filename.py'", "snippet": "exec(compile(open('filename.py').read(), 'filename.py', 'exec'))", "question_id": 1027714 }, { "intent": "Returning distinct rows in SQLAlchemy with SQLite", "rewritten_intent": "SQLAlchemy count the number of rows with distinct values in column `name` of table `Tag`", "snippet": "session.query(Tag).distinct(Tag.name).group_by(Tag.name).count()", "question_id": 17223174 }, { "intent": "Remove NULL columns in a dataframe Pandas?", "rewritten_intent": "remove null columns in a dataframe `df`", "snippet": "df = df.dropna(axis=1, how='all')", "question_id": 10857924 }, { "intent": "Python counting elements of a list within a list", "rewritten_intent": "check if all lists in list `L` have three elements of integer 1", "snippet": "all(x.count(1) == 3 for x in L)", "question_id": 12310141 }, { "intent": "Comparing elements between elements in two lists of tuples", "rewritten_intent": "Get a list comparing two lists of tuples `l1` and `l2` if any first value in `l1` matches with first value in `l2`", "snippet": "[x[0] for x in l1 if any(x[0] == y[0] for y in l2)]", "question_id": 13168252 }, { "intent": "how to clear/delete the Textbox in tkinter python on Ubuntu", "rewritten_intent": "clear the textbox `text` in tkinter", "snippet": "tex.delete('1.0', END)", "question_id": 27966626 }, { "intent": "Python convert long to date", "rewritten_intent": "Convert long int `myNumber` into date and time represented in the the string format '%Y-%m-%d %H:%M:%S'", "snippet": "datetime.datetime.fromtimestamp(myNumber).strftime('%Y-%m-%d %H:%M:%S')", "question_id": 10664430 }, { "intent": "How can I start a Python thread FROM C++?", "rewritten_intent": "Spawn a process to run python script `myscript.py` in C++", "snippet": "system('python myscript.py')", "question_id": 41246071 }, { "intent": "sorting a list with objects of a class as its items", "rewritten_intent": "sort a list `your_list` of class objects by their values for the attribute `anniversary_score`", "snippet": "your_list.sort(key=operator.attrgetter('anniversary_score'))", "question_id": 17038639 }, { "intent": "sorting a list with objects of a class as its items", "rewritten_intent": "sort list `your_list` by the `anniversary_score` attribute of each object", "snippet": "your_list.sort(key=lambda x: x.anniversary_score)", "question_id": 17038639 }, { "intent": "How can I convert a tensor into a numpy array in TensorFlow?", "rewritten_intent": "convert a tensor with list of constants `[1, 2, 3]` into a numpy array in tensorflow", "snippet": "print(type(tf.Session().run(tf.constant([1, 2, 3]))))", "question_id": 34097281 }, { "intent": "in Python, How to join a list of tuples into one list?", "rewritten_intent": "convert list `a` from being consecutive sequences of tuples into a single sequence of elements", "snippet": "list(itertools.chain(*a))", "question_id": 15269161 }, { "intent": "How do I pythonically set a value in a dictionary if it is None?", "rewritten_intent": "Set value for key `a` in dict `count` to `0` if key `a` does not exist or if value is `none`", "snippet": "count.setdefault('a', 0)", "question_id": 18663026 }, { "intent": "Python Pandas : group by in group by and average?", "rewritten_intent": "Do group by on `cluster` column in `df` and get its mean", "snippet": "df.groupby(['cluster']).mean()", "question_id": 30328646 }, { "intent": "from list of integers, get number closest to a given value", "rewritten_intent": "get number in list `myList` closest in value to number `myNumber`", "snippet": "min(myList, key=lambda x: abs(x - myNumber))", "question_id": 12141150 }, { "intent": "Find array item in a string", "rewritten_intent": "check if any of the items in `search` appear in `string`", "snippet": "any(x in string for x in search)", "question_id": 5858916 }, { "intent": "Find string with regular expression in python", "rewritten_intent": "search for occurrences of regex pattern `pattern` in string `url`", "snippet": "print(pattern.search(url).group(1))", "question_id": 32792602 }, { "intent": "How do I convert all strings (like \"Fault\") and into a unique float?", "rewritten_intent": "factorize all string values in dataframe `s` into floats", "snippet": "(s.factorize()[0] + 1).astype('float')", "question_id": 42458734 }, { "intent": "Subtract values in one list from corresponding values in another list - Python", "rewritten_intent": "Get a list `C` by subtracting values in one list `B` from corresponding values in another list `A`", "snippet": "C = [(a - b) for a, b in zip(A, B)]", "question_id": 11677860 }, { "intent": "How to derive the week start for a given (iso) weeknumber / year in python", "rewritten_intent": "derive the week start for the given week number and year \u20182011, 4, 0\u2019", "snippet": "datetime.datetime.strptime('2011, 4, 0', '%Y, %U, %w')", "question_id": 4793617 }, { "intent": "Python: How do I convert an array of strings to an array of numbers?", "rewritten_intent": "convert a list of strings `['1', '-1', '1']` to a list of numbers", "snippet": "map(int, ['1', '-1', '1'])", "question_id": 5306079 }, { "intent": "How to create datetime object from \"16SEP2012\" in python", "rewritten_intent": "create datetime object from \"16sep2012\"", "snippet": "datetime.datetime.strptime('16Sep2012', '%d%b%Y')", "question_id": 18684397 }, { "intent": "How do I use a dictionary to update fields in Django models?", "rewritten_intent": "update fields in Django model `Book` with arguments in dictionary `d` where primary key is equal to `pk`", "snippet": "Book.objects.filter(pk=pk).update(**d)", "question_id": 5503925 }, { "intent": "How do I use a dictionary to update fields in Django models?", "rewritten_intent": "update the fields in django model `Book` using dictionary `d`", "snippet": "Book.objects.create(**d)", "question_id": 5503925 }, { "intent": "Precision in python", "rewritten_intent": "print a digit `your_number` with exactly 2 digits after decimal", "snippet": "print('{0:.2f}'.format(your_number))", "question_id": 5229425 }, { "intent": "Python: How to generate a 12-digit random number?", "rewritten_intent": "generate a 12-digit random number", "snippet": "random.randint(100000000000, 999999999999)", "question_id": 13496087 }, { "intent": "Python: How to generate a 12-digit random number?", "rewritten_intent": "generate a random 12-digit number", "snippet": "int(''.join(str(random.randint(0, 9)) for _ in range(12)))", "question_id": 13496087 }, { "intent": "Python: How to generate a 12-digit random number?", "rewritten_intent": "generate a random 12-digit number", "snippet": "\"\"\"\"\"\".join(str(random.randint(0, 9)) for _ in range(12))", "question_id": 13496087 }, { "intent": "Python: How to generate a 12-digit random number?", "rewritten_intent": "generate a 12-digit random number", "snippet": "'%0.12d' % random.randint(0, 999999999999)", "question_id": 13496087 }, { "intent": "How to remove specific elements in a numpy array", "rewritten_intent": "remove specific elements in a numpy array `a`", "snippet": "numpy.delete(a, index)", "question_id": 10996140 }, { "intent": "Sort a list based on dictionary values in python?", "rewritten_intent": "sort list `trial_list` based on values of dictionary `trail_dict`", "snippet": "sorted(trial_list, key=lambda x: trial_dict[x])", "question_id": 12987178 }, { "intent": "read a single character from the user", "rewritten_intent": "read a single character from stdin", "snippet": "sys.stdin.read(1)", "question_id": 510357 }, { "intent": "How to get a list of matchable characters from a regex class", "rewritten_intent": "get a list of characters in string `x` matching regex pattern `pattern`", "snippet": "print(re.findall(pattern, x))", "question_id": 40094588 }, { "intent": "how to get the context of a search in BeautifulSoup?", "rewritten_intent": "get the context of a search by keyword 'My keywords' in beautifulsoup `soup`", "snippet": "k = soup.find(text=re.compile('My keywords')).parent.text", "question_id": 28780956 }, { "intent": "Convert a row in pandas into list", "rewritten_intent": "convert rows in pandas data frame `df` into list", "snippet": "df.apply(lambda x: x.tolist(), axis=1)", "question_id": 19585280 }, { "intent": "Convert a 1D array to a 2D array in numpy", "rewritten_intent": "convert a 1d `A` array to a 2d array `B`", "snippet": "B = np.reshape(A, (-1, 2))", "question_id": 12575421 }, { "intent": "Flask - How to make an app externally visible through a router?", "rewritten_intent": "run app `app` on host '192.168.0.58' and port 9000 in Flask", "snippet": "app.run(host='192.168.0.58', port=9000, debug=False)", "question_id": 30241279 }, { "intent": "Stdout encoding in python", "rewritten_intent": "encode unicode string '\\xc5\\xc4\\xd6' to utf-8 code", "snippet": "print('\\xc5\\xc4\\xd6'.encode('UTF8'))", "question_id": 15740236 }, { "intent": "Best way to get the nth element of each tuple from a list of tuples in Python", "rewritten_intent": "get the first element of each tuple from a list of tuples `G`", "snippet": "[x[0] for x in G]", "question_id": 12440342 }, { "intent": "Regular expression matching all but a string", "rewritten_intent": "regular expression matching all but 'aa' and 'bb' for string `string`", "snippet": "re.findall('-(?!aa-|bb-)([^-]+)', string)", "question_id": 39600161 }, { "intent": "Regular expression matching all but a string", "rewritten_intent": "regular expression matching all but 'aa' and 'bb'", "snippet": "re.findall('-(?!aa|bb)([^-]+)', string)", "question_id": 39600161 }, { "intent": "Removing entries from a dictionary based on values", "rewritten_intent": "remove false entries from a dictionary `hand`", "snippet": "{k: v for k, v in list(hand.items()) if v}", "question_id": 15158599 }, { "intent": "Removing entries from a dictionary based on values", "rewritten_intent": "Get a dictionary from a dictionary `hand` where the values are present", "snippet": "dict((k, v) for k, v in hand.items() if v)", "question_id": 15158599 }, { "intent": "Python sorting - A list of objects", "rewritten_intent": "sort list `L` based on the value of variable 'resultType' for each object in list `L`", "snippet": "sorted(L, key=operator.itemgetter('resultType'))", "question_id": 2338531 }, { "intent": "Python sorting - A list of objects", "rewritten_intent": "sort a list of objects `s` by a member variable 'resultType'", "snippet": "s.sort(key=operator.attrgetter('resultType'))", "question_id": 2338531 }, { "intent": "Python sorting - A list of objects", "rewritten_intent": "sort a list of objects 'somelist' where the object has member number variable `resultType`", "snippet": "somelist.sort(key=lambda x: x.resultType)", "question_id": 2338531 }, { "intent": "pandas joining multiple dataframes on columns", "rewritten_intent": "join multiple dataframes `d1`, `d2`, and `d3` on column 'name'", "snippet": "df1.merge(df2, on='name').merge(df3, on='name')", "question_id": 23668427 }, { "intent": "random Decimal in python", "rewritten_intent": "generate random Decimal", "snippet": "decimal.Decimal(random.randrange(10000)) / 100", "question_id": 439115 }, { "intent": "list all files of a directory", "rewritten_intent": "list all files of a directory `mypath`", "snippet": "onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]", "question_id": 3207219 }, { "intent": "list all files of a directory", "rewritten_intent": "list all files of a directory `mypath`", "snippet": "f = []\nfor (dirpath, dirnames, filenames) in walk(mypath):\n f.extend(filenames)\n break", "question_id": 3207219 }, { "intent": "list all files of a directory", "rewritten_intent": "list all \".txt\" files of a directory \"/home/adam/\"", "snippet": "print(glob.glob('/home/adam/*.txt'))", "question_id": 3207219 }, { "intent": "list all files of a directory", "rewritten_intent": "list all files of a directory \"somedirectory\"", "snippet": "os.listdir('somedirectory')", "question_id": 3207219 }, { "intent": "psycopg2: insert multiple rows with one query", "rewritten_intent": "execute sql query 'INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)' with all parameters in list `tup`", "snippet": "cur.executemany('INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)', tup)", "question_id": 8134602 }, { "intent": "get key by value in dictionary with same value in python?", "rewritten_intent": "get keys with same value in dictionary `d`", "snippet": "print([key for key in d if d[key] == 1])", "question_id": 24958010 }, { "intent": "get key by value in dictionary with same value in python?", "rewritten_intent": "get keys with same value in dictionary `d`", "snippet": "print([key for key, value in d.items() if value == 1])", "question_id": 24958010 }, { "intent": "get key by value in dictionary with same value in python?", "rewritten_intent": "Get keys from a dictionary 'd' where the value is '1'.", "snippet": "print([key for key, value in list(d.items()) if value == 1])", "question_id": 24958010 }, { "intent": "What is the best way to create a string array in python?", "rewritten_intent": "create list of 'size' empty strings", "snippet": "strs = ['' for x in range(size)]", "question_id": 6376886 }, { "intent": "generate pdf from markdown file", "rewritten_intent": "generate pdf file `output_filename` from markdown file `input_filename`", "snippet": "with open(input_filename, 'r') as f:\n html_text = markdown(f.read(), output_format='html4')\npdfkit.from_string(html_text, output_filename)", "question_id": 4135344 }, { "intent": "Remove duplicate dict in list in Python", "rewritten_intent": "remove duplicate dict in list `l`", "snippet": "[dict(t) for t in set([tuple(d.items()) for d in l])]", "question_id": 9427163 }, { "intent": "How to set the timezone in Django?", "rewritten_intent": "Set time zone `Europe/Istanbul` in Django", "snippet": "TIME_ZONE = 'Europe/Istanbul'", "question_id": 29311354 }, { "intent": "Appending to list in Python dictionary", "rewritten_intent": "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", "snippet": "dates_dict.setdefault(key, []).append(date)", "question_id": 26367812 }, { "intent": "How to do this GROUP BY query in Django's ORM with annotate and aggregate", "rewritten_intent": "Group the values from django model `Article` with group by value `pub_date` and annotate by `title`", "snippet": "Article.objects.values('pub_date').annotate(article_count=Count('title'))", "question_id": 1908741 }, { "intent": "How to clear Tkinter Canvas?", "rewritten_intent": "clear Tkinter Canvas `canvas`", "snippet": "canvas.delete('all')", "question_id": 15839491 }, { "intent": "How to add a specific number of characters to the end of string in Pandas?", "rewritten_intent": "Initialize a pandas series object `s` with columns `['A', 'B', 'A1R', 'B2', 'AABB4']`", "snippet": "s = pd.Series(['A', 'B', 'A1R', 'B2', 'AABB4'])", "question_id": 39816795 }, { "intent": "How do I translate a ISO 8601 datetime string into a Python datetime object?", "rewritten_intent": "None", "snippet": "datetime.datetime.strptime('2007-03-04T21:08:12', '%Y-%m-%dT%H:%M:%S')", "question_id": 969285 }, { "intent": "How to sort a list according to another list?", "rewritten_intent": "sort list `a` using the first dimension of the element as the key to list `b`", "snippet": "a.sort(key=lambda x: b.index(x[0]))", "question_id": 12814667 }, { "intent": "How to sort a list according to another list?", "rewritten_intent": null, "snippet": "a.sort(key=lambda x_y: b.index(x_y[0]))", "question_id": 12814667 }, { "intent": "Matplotlib - How to plot a high resolution graph?", "rewritten_intent": "Save plot `plt` as png file 'filename.png'", "snippet": "plt.savefig('filename.png')", "question_id": 39870642 }, { "intent": "Matplotlib - How to plot a high resolution graph?", "rewritten_intent": "Save matplotlib graph to image file `filename.png` at a resolution of `300 dpi`", "snippet": "plt.savefig('filename.png', dpi=300)", "question_id": 39870642 }, { "intent": "How to get output of exe in python script?", "rewritten_intent": "get output from process `p1`", "snippet": "p1.communicate()[0]", "question_id": 748028 }, { "intent": "How to get output of exe in python script?", "rewritten_intent": null, "snippet": "output = subprocess.Popen(['mycmd', 'myarg'], stdout=PIPE).communicate()[0]", "question_id": 748028 }, { "intent": "Using BeautifulSoup to search html for string", "rewritten_intent": "searche in HTML string for elements that have text 'Python'", "snippet": "soup.body.findAll(text='Python')", "question_id": 8936030 }, { "intent": "Using BeautifulSoup to search html for string", "rewritten_intent": "BeautifulSoup find string 'Python Jobs' in HTML body `body`", "snippet": "soup.body.findAll(text='Python Jobs')", "question_id": 8936030 }, { "intent": "Python: sorting items in a dictionary by a part of a key?", "rewritten_intent": "Sort items in dictionary `d` using the first part of the key after splitting the key", "snippet": "sorted(list(d.items()), key=lambda name_num: (name_num[0].rsplit(None, 1)[0], name_num[1]))", "question_id": 15795525 }, { "intent": "Find non-common elements in lists", "rewritten_intent": "create a set that is the exclusive or of [1, 2, 3] and [3, 4, 5]", "snippet": "set([1, 2, 3]) ^ set([3, 4, 5])", "question_id": 11348347 }, { "intent": "retrieving list items from request.POST in django/python", "rewritten_intent": "Get a list values of a dictionary item `pass_id` from post requests in django", "snippet": "request.POST.getlist('pass_id')", "question_id": 5430470 }, { "intent": "How do I remove dicts from a list with duplicate fields in python?", "rewritten_intent": "Filter duplicate entries w.r.t. value in 'id' from a list of dictionaries 'L'", "snippet": "list(dict((x['id'], x) for x in L).values())", "question_id": 11114358 }, { "intent": "Merge Columns within a DataFrame that have the Same Name", "rewritten_intent": "Get pandas GroupBy object with sum over the rows with same column names within dataframe `df`", "snippet": "df.groupby(df.columns, axis=1).sum()", "question_id": 13078751 }, { "intent": "python dict comprehension with two ranges", "rewritten_intent": "convert the zip of range `(1, 5)` and range `(7, 11)` into a dictionary", "snippet": "dict(zip(list(range(1, 5)), list(range(7, 11))))", "question_id": 18789262 }, { "intent": "How to turn a boolean array into index array in numpy", "rewritten_intent": "Get all indexes of boolean numpy array where boolean value `mask` is True", "snippet": "numpy.where(mask)", "question_id": 8218032 }, { "intent": "case insensitive string comparison", "rewritten_intent": "case insensitive comparison of strings `string1` and `string2`", "snippet": "if (string1.lower() == string2.lower()):\n print('The strings are the same (case insensitive)')\nelse:\n print('The strings are not the same (case insensitive)')", "question_id": 319426 }, { "intent": "case insensitive string comparison", "rewritten_intent": "case insensitive string comparison between `string1` and `string2`", "snippet": "if (string1.lower() == string2.lower()):\n pass", "question_id": 319426 }, { "intent": "case insensitive string comparison", "rewritten_intent": "case insensitive string comparison between `string1` and `string2`", "snippet": "(string1.lower() == string2.lower())", "question_id": 319426 }, { "intent": "case insensitive string comparison", "rewritten_intent": "case insensitive string comparison between `first` and `second`", "snippet": "(first.lower() == second.lower())", "question_id": 319426 }, { "intent": "case insensitive string comparison", "rewritten_intent": "case insensitive comparison between strings `first` and `second`", "snippet": "(first.upper() == second.upper())", "question_id": 319426 }, { "intent": "Taking the results of a bash command and using it in python", "rewritten_intent": "Taking the results of a bash command \"awk '{print $10, $11}' test.txt > test2.txt\"", "snippet": "os.system(\"awk '{print $10, $11}' test.txt > test2.txt\")", "question_id": 5744980 }, { "intent": "How to remove multiple indexes from a list at the same time?", "rewritten_intent": "remove multiple values from a list `my_list` at the same time with index starting at `2` and ending just before `6`.", "snippet": "del my_list[2:6]", "question_id": 11303225 }, { "intent": "How to convert a string to its Base-10 representation?", "rewritten_intent": "convert a string `s` to its base-10 representation", "snippet": "int(s.encode('hex'), 16)", "question_id": 10716796 }, { "intent": "Python regular expression with codons", "rewritten_intent": "match regex pattern 'TAA(?:[ATGC]{3})+?TAA' on string `seq`", "snippet": "re.findall('TAA(?:[ATGC]{3})+?TAA', seq)", "question_id": 9618050 }, { "intent": "Sorting a set of values", "rewritten_intent": "sort a set `s` by numerical value", "snippet": "sorted(s, key=float)", "question_id": 17457793 }, { "intent": "convert an int to a hex string", "rewritten_intent": "convert an int 65 to hex string", "snippet": "hex(65)", "question_id": 2269827 }, { "intent": "Simple way to append a pandas series with same index", "rewritten_intent": "append a pandas series `b` to the series `a` and get a continuous index", "snippet": "a.append(b).reset_index(drop=True)", "question_id": 20400135 }, { "intent": "Simple way to append a pandas series with same index", "rewritten_intent": "simple way to append a pandas series `a` and `b` with same index", "snippet": "pd.concat([a, b], ignore_index=True)", "question_id": 20400135 }, { "intent": "In Python, is there a concise way to use a list comprehension with multiple iterators?", "rewritten_intent": "Get a list of tuples with multiple iterators using list comprehension", "snippet": "[(i, j) for i in range(1, 3) for j in range(1, 5)]", "question_id": 329886 }, { "intent": "sorting values of python dict using sorted builtin function", "rewritten_intent": "reverse sort items in dictionary `mydict` by value", "snippet": "sorted(iter(mydict.items()), key=itemgetter(1), reverse=True)", "question_id": 9849192 }, { "intent": "How can I select 'last business day of the month' in Pandas?", "rewritten_intent": "select the last business day of the month for each month in 2014 in pandas", "snippet": "pd.date_range('1/1/2014', periods=12, freq='BM')", "question_id": 27218543 }, { "intent": "How do I disable the security certificate check in Python requests", "rewritten_intent": "disable the certificate check in https requests for url `https://kennethreitz.com`", "snippet": "requests.get('https://kennethreitz.com', verify=False)", "question_id": 15445981 }, { "intent": "dropping a row in pandas with dates indexes, python", "rewritten_intent": "return dataframe `df` with last row dropped", "snippet": "df.ix[:-1]", "question_id": 11414596 }, { "intent": "string contains substring", "rewritten_intent": "check if \"blah\" is in string `somestring`", "snippet": "if ('blah' not in somestring):\n pass", "question_id": 3437059 }, { "intent": "string contains substring", "rewritten_intent": "check if string `needle` is in `haystack`", "snippet": "if (needle in haystack):\n pass", "question_id": 3437059 }, { "intent": "string contains substring", "rewritten_intent": "check if string \"substring\" is in string", "snippet": "string.find('substring')", "question_id": 3437059 }, { "intent": "string contains substring method", "rewritten_intent": "check if string `s` contains \"is\"", "snippet": "if (s.find('is') == (-1)):\n print(\"No 'is' here!\")\nelse:\n print(\"Found 'is' in the string.\")", "question_id": 3437059 }, { "intent": "Extract first and last row of a dataframe in pandas", "rewritten_intent": "extract first and last row of a dataframe `df`", "snippet": "pd.concat([df.head(1), df.tail(1)])", "question_id": 36542169 }, { "intent": "Django - Filter queryset by CharField value length", "rewritten_intent": "filter a Django model `MyModel` to have charfield length of max `255`", "snippet": "MyModel.objects.extra(where=['CHAR_LENGTH(text) > 254'])", "question_id": 23351183 }, { "intent": "Django - Filter queryset by CharField value length", "rewritten_intent": "Filter queryset for all objects in Django model `MyModel` where texts length are greater than `254`", "snippet": "MyModel.objects.filter(text__regex='^.{254}.*')", "question_id": 23351183 }, { "intent": "Best way to count the number of rows with missing values in a pandas DataFrame", "rewritten_intent": "count the number of rows with missing values in a pandas dataframe `df`", "snippet": "sum(df.apply(lambda x: sum(x.isnull().values), axis=1) > 0)", "question_id": 28199524 }, { "intent": "Sorting while preserving order in python", "rewritten_intent": null, "snippet": "sorted(enumerate(a), key=lambda x: x[1])", "question_id": 3728017 }, { "intent": "How to set the font size of a Canvas' text item?", "rewritten_intent": "set the font 'Purisa' of size 12 for a canvas' text item `k`", "snippet": "canvas.create_text(x, y, font=('Purisa', 12), text=k)", "question_id": 15457504 }, { "intent": "Python: How to use a list comprehension here?", "rewritten_intent": "create a list containing all values associated with key 'baz' in dictionaries of list `foos` using list comprehension", "snippet": "[y['baz'] for x in foos for y in x['bar']]", "question_id": 4879641 }, { "intent": "pandas read csv with extra commas in column", "rewritten_intent": "read pandas data frame csv `comma.csv` with extra commas in column specifying string delimiter `'`", "snippet": "df = pd.read_csv('comma.csv', quotechar=\"'\")", "question_id": 32743479 }, { "intent": "avoiding regex in pandas str.replace", "rewritten_intent": "replace string 'in.' with ' in. ' in dataframe `df` column 'a'", "snippet": "df['a'] = df['a'].str.replace('in.', ' in. ')", "question_id": 36296993 }, { "intent": "Finding the index of elements based on a condition using python list comprehension", "rewritten_intent": "Get all indexes of a list `a` where each value is greater than `2`", "snippet": "[i for i in range(len(a)) if a[i] > 2]", "question_id": 7270321 }, { "intent": "check if a variable exists", "rewritten_intent": "check if a local variable `myVar` exists", "snippet": "('myVar' in locals())", "question_id": 843277 }, { "intent": "check if a variable exists", "rewritten_intent": "check if a global variable `myVar` exists", "snippet": "('myVar' in globals())", "question_id": 843277 }, { "intent": "check if a variable exists", "rewritten_intent": "check if object `obj` has attribute 'attr_name'", "snippet": "hasattr(obj, 'attr_name')", "question_id": 843277 }, { "intent": "check if a variable exists", "rewritten_intent": "check if a local variable 'myVar' exists", "snippet": "if ('myVar' in locals()):\n pass", "question_id": 843277 }, { "intent": "check if a variable exists", "rewritten_intent": "check if a global variable 'myVar' exists", "snippet": "if ('myVar' in globals()):\n pass", "question_id": 843277 }, { "intent": "Python lambda function", "rewritten_intent": "lambda function that adds two operands", "snippet": "lambda x, y: x + y", "question_id": 6243460 }, { "intent": "What's the shortest way to count the number of items in a generator/iterator?", "rewritten_intent": "count the number of items in a generator/iterator `it`", "snippet": "sum(1 for i in it)", "question_id": 5384570 }, { "intent": "how to get tuples from lists using list comprehension in python", "rewritten_intent": "get tuples of the corresponding elements from lists `lst` and `lst2`", "snippet": "[(x, lst2[i]) for i, x in enumerate(lst)]", "question_id": 18990069 }, { "intent": "how to get tuples from lists using list comprehension in python", "rewritten_intent": "create tuples containing elements that are at the same index of list `lst` and list `lst2`", "snippet": "[(i, j) for i, j in zip(lst, lst2)]", "question_id": 18990069 }, { "intent": "how to get tuples from lists using list comprehension in python", "rewritten_intent": "get tuples from lists `lst` and `lst2` using list comprehension in python 2", "snippet": "[(lst[i], lst2[i]) for i in range(len(lst))]", "question_id": 18990069 }, { "intent": "How do I convert a hex triplet to an RGB tuple and back?", "rewritten_intent": "convert hex triplet string `rgbstr` to rgb tuple", "snippet": "struct.unpack('BBB', rgbstr.decode('hex'))", "question_id": 4296249 }, { "intent": "Check if something is not in a list", "rewritten_intent": "Check if 3 is not in a list [2, 3, 4]", "snippet": "(3 not in [2, 3, 4])", "question_id": 10406130 }, { "intent": "Check if something is not in a list", "rewritten_intent": "Check if tuple (2, 3) is not in a list [(2, 3), (5, 6), (9, 1)]", "snippet": "((2, 3) not in [(2, 3), (5, 6), (9, 1)])", "question_id": 10406130 }, { "intent": "Check if something is not in a list", "rewritten_intent": "Check if tuple (2, 3) is not in a list [(2, 7), (7, 3), \"hi\"]", "snippet": "((2, 3) not in [(2, 7), (7, 3), 'hi'])", "question_id": 10406130 }, { "intent": "Check if something is not in a list", "rewritten_intent": "Check if 3 is not in the list [4,5,6]", "snippet": "(3 not in [4, 5, 6])", "question_id": 10406130 }, { "intent": "Create new list by taking first item from first list, and last item from second list", "rewritten_intent": "create a list by appending components from list `a` and reversed list `b` interchangeably", "snippet": "[value for pair in zip(a, b[::-1]) for value in pair]", "question_id": 35797523 }, { "intent": "Remove one column for a numpy array", "rewritten_intent": "delete the last column of numpy array `a` and assign resulting array to `b`", "snippet": "b = np.delete(a, -1, 1)", "question_id": 6710684 }, { "intent": "Python mySQL Update, Working but not updating table", "rewritten_intent": "commit all the changes after executing a query.", "snippet": "dbb.commit()", "question_id": 15271907 }, { "intent": "How do I join two dataframes based on values in selected columns?", "rewritten_intent": "join two dataframes based on values in selected columns", "snippet": "pd.merge(a, b, on=['A', 'B'], how='outer')", "question_id": 40221516 }, { "intent": "How to change QPushButton text and background color", "rewritten_intent": "set text color as `red` and background color as `#A3C1DA` in qpushbutton", "snippet": "setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')", "question_id": 24659239 }, { "intent": "Finding the average of a list", "rewritten_intent": "find the mean of elements in list `l`", "snippet": "sum(l) / float(len(l))", "question_id": 9039961 }, { "intent": "Python: Finding a (string) key in a dictionary that contains a substring", "rewritten_intent": "Find all the items from a dictionary `D` if the key contains the string `Light`", "snippet": "[(k, v) for k, v in D.items() if 'Light' in k]", "question_id": 3252590 }, { "intent": "How do I use a MD5 hash (or other binary data) as a key name?", "rewritten_intent": "Get a md5 hash from string `thecakeisalie`", "snippet": "k = hashlib.md5('thecakeisalie').hexdigest()", "question_id": 4508155 }, { "intent": "How to get only the last part of a path in Python?", "rewritten_intent": null, "snippet": "os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))", "question_id": 3925096 }, { "intent": "Sorting datetime objects while ignoring the year?", "rewritten_intent": "sort datetime objects `birthdays` by `month` and `day`", "snippet": "birthdays.sort(key=lambda d: (d.month, d.day))", "question_id": 2040038 }, { "intent": "How do I extract table data in pairs using BeautifulSoup?", "rewritten_intent": "extract table data from table `rows` using beautifulsoup", "snippet": "[[td.findNext(text=True) for td in tr.findAll('td')] for tr in rows]", "question_id": 8139797 }, { "intent": "python: rstrip one exact string, respecting order", "rewritten_intent": "strip the string `.txt` from anywhere in the string `Boat.txt.txt`", "snippet": "\"\"\"Boat.txt.txt\"\"\".replace('.txt', '')", "question_id": 18723580 }, { "intent": "Python Pandas: How to get the row names from index of a dataframe?", "rewritten_intent": "get a list of the row names from index of a pandas data frame", "snippet": "list(df.index)", "question_id": 26640145 }, { "intent": "Python Pandas: How to get the row names from index of a dataframe?", "rewritten_intent": "get the row names from index in a pandas data frame", "snippet": "df.index", "question_id": 26640145 }, { "intent": "List of all unique characters in a string?", "rewritten_intent": "create a list of all unique characters in string 'aaabcabccd'", "snippet": "\"\"\"\"\"\".join(list(OrderedDict.fromkeys('aaabcabccd').keys()))", "question_id": 13902805 }, { "intent": "List of all unique characters in a string?", "rewritten_intent": "get list of all unique characters in a string 'aaabcabccd'", "snippet": "list(set('aaabcabccd'))", "question_id": 13902805 }, { "intent": "List of all unique characters in a string?", "rewritten_intent": null, "snippet": "\"\"\"\"\"\".join(set('aaabcabccd'))", "question_id": 13902805 }, { "intent": "Find rows with non zero values in a subset of columns in pandas dataframe", "rewritten_intent": "find rows with non zero values in a subset of columns where `df.dtypes` is not equal to `object` in pandas dataframe", "snippet": "df.loc[(df.loc[:, (df.dtypes != object)] != 0).any(1)]", "question_id": 39187788 }, { "intent": "upload file with Python Mechanize", "rewritten_intent": null, "snippet": "br.form.add_file(open(filename), 'text/plain', filename)", "question_id": 1299855 }, { "intent": "Multiple 'in' operators in Python?", "rewritten_intent": "check if dictionary `d` contains all keys in list `['somekey', 'someotherkey', 'somekeyggg']`", "snippet": "all(word in d for word in ['somekey', 'someotherkey', 'somekeyggg'])", "question_id": 7128153 }, { "intent": "How to hide output of subprocess in Python 2.7", "rewritten_intent": "hide output of subprocess `['espeak', text]`", "snippet": "subprocess.check_output(['espeak', text], stderr=subprocess.STDOUT)", "question_id": 11269575 }, { "intent": "How to replace NaNs by preceding values in pandas DataFrame?", "rewritten_intent": "replace nans by preceding values in pandas dataframe `df`", "snippet": "df.fillna(method='ffill', inplace=True)", "question_id": 27905295 }, { "intent": "How to create range of numbers in Python like in MATLAB", "rewritten_intent": "create 4 numbers in range between 1 and 3", "snippet": "print(np.linspace(1, 3, num=4, endpoint=False))", "question_id": 31143732 }, { "intent": "How to create range of numbers in Python like in MATLAB", "rewritten_intent": "Create numpy array of `5` numbers starting from `1` with interval of `3`", "snippet": "print(np.linspace(1, 3, num=5))", "question_id": 31143732 }, { "intent": "Symlinks on windows?", "rewritten_intent": "create a symlink directory `D:\\\\testdirLink` for directory `D:\\\\testdir` with unicode support using ctypes library", "snippet": "kdll.CreateSymbolicLinkW('D:\\\\testdirLink', 'D:\\\\testdir', 1)", "question_id": 1447575 }, { "intent": "Python: slicing a multi-dimensional array", "rewritten_intent": "get a list `slice` of array slices of the first two rows and columns from array `arr`", "snippet": "slice = [arr[i][0:2] for i in range(0, 2)]", "question_id": 17277100 }, { "intent": "Upload files to Google cloud storage from appengine app", "rewritten_intent": "upload uploaded file from path '/upload' to Google cloud storage 'my_bucket' bucket", "snippet": "upload_url = blobstore.create_upload_url('/upload', gs_bucket_name='my_bucket')", "question_id": 23823206 }, { "intent": "Change directory to the directory of a Python script", "rewritten_intent": "change directory to the directory of a python script", "snippet": "os.chdir(os.path.dirname(__file__))", "question_id": 509742 }, { "intent": "Call a function with argument list in python", "rewritten_intent": "call a function with argument list `args`", "snippet": "func(*args)", "question_id": 817087 }, { "intent": "Pandas DataFrame, how do i split a column into two", "rewritten_intent": "split column 'AB' in dataframe `df` into two columns by first whitespace ' '", "snippet": "df['AB'].str.split(' ', 1, expand=True)", "question_id": 14745022 }, { "intent": "Pandas DataFrame, how do i split a column into two", "rewritten_intent": "pandas dataframe, how do i split a column 'AB' into two 'A' and 'B' on delimiter ' '", "snippet": "df['A'], df['B'] = df['AB'].str.split(' ', 1).str", "question_id": 14745022 }, { "intent": "Sorting Python list based on the length of the string", "rewritten_intent": "sort list `xs` based on the length of its elements", "snippet": "print(sorted(xs, key=len))", "question_id": 2587402 }, { "intent": "Sorting Python list based on the length of the string", "rewritten_intent": "sort list `xs` in ascending order of length of elements", "snippet": "xs.sort(lambda x, y: cmp(len(x), len(y)))", "question_id": 2587402 }, { "intent": "Sorting Python list based on the length of the string", "rewritten_intent": "sort list of strings `xs` by the length of string", "snippet": "xs.sort(key=lambda s: len(s))", "question_id": 2587402 }, { "intent": "how to plot arbitrary markers on a pandas data series?", "rewritten_intent": "plot point marker '.' on series `ts`", "snippet": "ts.plot(marker='.')", "question_id": 19939084 }, { "intent": "get all combination of n binary value", "rewritten_intent": "get all combination of n binary values", "snippet": "lst = list(itertools.product([0, 1], repeat=n))", "question_id": 14931769 }, { "intent": "get all combination of n binary value", "rewritten_intent": "get all combination of n binary values", "snippet": "lst = map(list, itertools.product([0, 1], repeat=n))", "question_id": 14931769 }, { "intent": "get all combination of n binary value", "rewritten_intent": "get all combination of 3 binary values", "snippet": "bin = [0, 1]\n[(x, y, z) for x in bin for y in bin for z in bin]", "question_id": 14931769 }, { "intent": "get all combination of n binary value", "rewritten_intent": "get all combination of 3 binary values", "snippet": "lst = list(itertools.product([0, 1], repeat=3))", "question_id": 14931769 }, { "intent": "Append string to the start of each value in a said column of a pandas dataframe (elegantly)", "rewritten_intent": "append string 'str' at the beginning of each value in column 'col' of dataframe `df`", "snippet": "df['col'] = 'str' + df['col'].astype(str)", "question_id": 20025882 }, { "intent": "How to get a variable name as a string in Python?", "rewritten_intent": "get a dict of variable names `['some', 'list', 'of', 'vars']` as a string and their values", "snippet": "dict((name, eval(name)) for name in ['some', 'list', 'of', 'vars'])", "question_id": 2553354 }, { "intent": "How to add a colorbar for a hist2d plot", "rewritten_intent": "add a colorbar to plot `plt` using image `im` on axes `ax`", "snippet": "plt.colorbar(im, ax=ax)", "question_id": 42387471 }, { "intent": "How to get every element in a list of list of lists?", "rewritten_intent": "convert nested list 'Cards' into a flat list", "snippet": "[a for c in Cards for b in c for a in b]", "question_id": 16734590 }, { "intent": "Sorting dictionary keys in python", "rewritten_intent": "create a list containing keys of dictionary `d` and sort it alphabetically", "snippet": "sorted(d, key=d.get)", "question_id": 575819 }, { "intent": "How to count the number of occurences of `None` in a list?", "rewritten_intent": "print the number of occurences of not `none` in a list `lst` in Python 2", "snippet": "print(len([x for x in lst if x is not None]))", "question_id": 29422691 }, { "intent": "Accessing dictionary by key in Django template", "rewritten_intent": "lookup dictionary key `key1` in Django template `json`", "snippet": "{{json.key1}}", "question_id": 19745091 }, { "intent": "Get unique values from a list in python", "rewritten_intent": "remove duplicates from list `myset`", "snippet": "mynewlist = list(myset)", "question_id": 12897374 }, { "intent": "Get unique values from a list in python", "rewritten_intent": "get unique values from the list `['a', 'b', 'c', 'd']`", "snippet": "set(['a', 'b', 'c', 'd'])", "question_id": 12897374 }, { "intent": "Python: A4 size for a plot", "rewritten_intent": "set size of `figure` to landscape A4 i.e. `11.69, 8.27` inches", "snippet": "figure(figsize=(11.69, 8.27))", "question_id": 15571267 }, { "intent": "How to get everything after last slash in a URL?", "rewritten_intent": "get every thing after last `/`", "snippet": "url.rsplit('/', 1)", "question_id": 7253803 }, { "intent": "How to get everything after last slash in a URL?", "rewritten_intent": "get everything after last slash in a url stored in variable 'url'", "snippet": "url.rsplit('/', 1)[-1]", "question_id": 7253803 }, { "intent": "how to read a file in other directory in python", "rewritten_intent": "open file '5_1.txt' in directory `direct`", "snippet": "x_file = open(os.path.join(direct, '5_1.txt'), 'r')", "question_id": 13223737 }, { "intent": "How to create a list with the characters of a string?", "rewritten_intent": "create a list with the characters of a string `5+6`", "snippet": "list('5+6')", "question_id": 5501641 }, { "intent": "Flattening a list of NumPy arrays?", "rewritten_intent": "concatenate a list of numpy arrays `input_list` together into a flattened list of values", "snippet": "np.concatenate(input_list).ravel().tolist()", "question_id": 33711985 }, { "intent": "Converting a dict into a list", "rewritten_intent": "convert dictionary `dict` into a flat list", "snippet": "print([y for x in list(dict.items()) for y in x])", "question_id": 11351874 }, { "intent": "Converting a dict into a list", "rewritten_intent": "Convert a dictionary `dict` into a list with key and values as list items.", "snippet": "[y for x in list(dict.items()) for y in x]", "question_id": 11351874 }, { "intent": "How to pull a random record using Django's ORM?", "rewritten_intent": "get a random record from model 'MyModel' using django's orm", "snippet": "MyModel.objects.order_by('?').first()", "question_id": 962619 }, { "intent": "change current working directory in python", "rewritten_intent": "change current working directory to directory 'chapter3'", "snippet": "os.chdir('chapter3')", "question_id": 20796355 }, { "intent": "change current working directory in python", "rewritten_intent": "change current working directory", "snippet": "os.chdir('C:\\\\Users\\\\username\\\\Desktop\\\\headfirstpython\\\\chapter3')", "question_id": 20796355 }, { "intent": "change current working directory in python", "rewritten_intent": "change current working directory", "snippet": "os.chdir('.\\\\chapter3')", "question_id": 20796355 }, { "intent": "How to create single Python dict from a list of dicts by summing values with common keys?", "rewritten_intent": "create a flat dictionary by summing values associated with similar keys in each dictionary of list `dictlist`", "snippet": "dict((key, sum(d[key] for d in dictList)) for key in dictList[0])", "question_id": 974678 }, { "intent": "How to sort pandas data frame using values from several columns?", "rewritten_intent": "sort pandas data frame `df` using values from columns `c1` and `c2` in ascending order", "snippet": "df.sort(['c1', 'c2'], ascending=[True, True])", "question_id": 17618981 }, { "intent": "Converting string series to float list", "rewritten_intent": "Converting string lists `s` to float list", "snippet": "floats = [float(x) for x in s.split()]", "question_id": 4004550 }, { "intent": "Converting string series to float list", "rewritten_intent": "Converting string lists `s` to float list", "snippet": "floats = map(float, s.split())", "question_id": 4004550 }, { "intent": "How to set \"step\" on axis X in my figure in matplotlib python 2.6.6?", "rewritten_intent": "set labels `[1, 2, 3, 4, 5]` on axis X in plot `plt`", "snippet": "plt.xticks([1, 2, 3, 4, 5])", "question_id": 10839719 }, { "intent": "read from stdin", "rewritten_intent": "read line by line from stdin", "snippet": "for line in fileinput.input():\n pass", "question_id": 1450393 }, { "intent": "read from stdin", "rewritten_intent": "read line by line from stdin", "snippet": "for line in sys.stdin:\n pass", "question_id": 1450393 }, { "intent": "How to check if a value exists in a dictionary (python)", "rewritten_intent": "check if string `one` exists in the values of dictionary `d`", "snippet": "'one' in list(d.values())", "question_id": 8214932 }, { "intent": "How to check if a value exists in a dictionary (python)", "rewritten_intent": "Check if value 'one' is among the values of dictionary `d`", "snippet": "'one' in iter(d.values())", "question_id": 8214932 }, { "intent": "Calling a parent class constructor from a child class in python", "rewritten_intent": "call parent class `Instructor` of child class constructor", "snippet": "super(Instructor, self).__init__(name, year)", "question_id": 12557612 }, { "intent": "how to create a dictionary using two lists in python?", "rewritten_intent": "create a dictionary using two lists`x` and `y`", "snippet": "dict(zip(x, y))", "question_id": 15183084 }, { "intent": "Sorting a list of dicts by dict values", "rewritten_intent": "sort a list of dictionaries `a` by dictionary values in descending order", "snippet": "sorted(a, key=lambda i: list(i.values())[0], reverse=True)", "question_id": 10915391 }, { "intent": "Sorting a list of dicts by dict values", "rewritten_intent": "sorting a list of dictionary `a` by values in descending order", "snippet": "sorted(a, key=dict.values, reverse=True)", "question_id": 10915391 }, { "intent": "pandas: how to do multiple groupby-apply operations", "rewritten_intent": "Use multiple groupby and agg operations `sum`, `count`, `std` for pandas data frame `df`", "snippet": "df.groupby(level=0).agg(['sum', 'count', 'std'])", "question_id": 39159475 }, { "intent": "How to add multiple values to a dictionary key in python?", "rewritten_intent": "for a dictionary `a`, set default value for key `somekey` as list and append value `bob` in that key", "snippet": "a.setdefault('somekey', []).append('bob')", "question_id": 20585920 }, { "intent": "Python - sum values in dictionary", "rewritten_intent": "sum values in list of dictionaries `example_list` with key 'gold'", "snippet": "sum(item['gold'] for item in example_list)", "question_id": 11692613 }, { "intent": "Python - sum values in dictionary", "rewritten_intent": "get a sum of all values from key `gold` in a list of dictionary `example_list`", "snippet": "sum([item['gold'] for item in example_list])", "question_id": 11692613 }, { "intent": "Python - sum values in dictionary", "rewritten_intent": "Get all the values in key `gold` summed from a list of dictionary `myLIst`", "snippet": "sum(item['gold'] for item in myLIst)", "question_id": 11692613 }, { "intent": "writing string to a file on a new line everytime?", "rewritten_intent": "writing string 'text to write\\n' to file `f`", "snippet": "f.write('text to write\\n')", "question_id": 2918362 }, { "intent": "writing string to a file on a new line everytime?", "rewritten_intent": "Write a string `My String` to a file `file` including new line character", "snippet": "file.write('My String\\n')", "question_id": 2918362 }, { "intent": "Finding consecutive segments in a pandas data frame", "rewritten_intent": "find consecutive segments from a column 'A' in a pandas data frame 'df'", "snippet": "df.reset_index().groupby('A')['index'].apply(np.array)", "question_id": 14358567 }, { "intent": "Python - how to refer to relative paths of resources when working with code repository", "rewritten_intent": "get a relative path of file 'my_file' into variable `fn`", "snippet": "fn = os.path.join(os.path.dirname(__file__), 'my_file')", "question_id": 1270951 }, { "intent": "How to retrieve an element from a set without removing it?", "rewritten_intent": "retrieve an element from a set `s` without removing it", "snippet": "e = next(iter(s))", "question_id": 59825 }, { "intent": "How to execute a command prompt command from python", "rewritten_intent": "execute a command in the command prompt to list directory contents of the c drive `c:\\\\'", "snippet": "os.system('dir c:\\\\')", "question_id": 5486725 }, { "intent": "How to auto-scroll a gtk.scrolledwindow?", "rewritten_intent": "Make a auto scrolled window to the end of the list in gtk", "snippet": "self.treeview.connect('size-allocate', self.treeview_changed)", "question_id": 5218948 }, { "intent": "Python: Find in list", "rewritten_intent": "check if 3 is inside list `[1, 2, 3]`", "snippet": "3 in [1, 2, 3]", "question_id": 9542738 }, { "intent": "Convert date format python", "rewritten_intent": "Represent DateTime object '10/05/2012' with format '%d/%m/%Y' into format '%Y-%m-%d'", "snippet": "datetime.datetime.strptime('10/05/2012', '%d/%m/%Y').strftime('%Y-%m-%d')", "question_id": 10541640 }, { "intent": "python : how to convert string literal to raw string literal?", "rewritten_intent": "convert a string literal `s` with values `\\\\` to raw string literal", "snippet": "s = s.replace('\\\\', '\\\\\\\\')", "question_id": 7262828 }, { "intent": "Get output of python script from within python script", "rewritten_intent": "get output of script `proc`", "snippet": "print(proc.communicate()[0])", "question_id": 6086047 }, { "intent": "Getting pandas dataframe from list of nested dictionaries", "rewritten_intent": "create a pandas data frame from list of nested dictionaries `my_list`", "snippet": "pd.concat([pd.DataFrame(l) for l in my_list], axis=1).T", "question_id": 41946927 }, { "intent": "Delete Column in Pandas based on Condition", "rewritten_intent": "delete all columns in DataFrame `df` that do not hold a non-zero value in its records", "snippet": "df.loc[:, ((df != 0).any(axis=0))]", "question_id": 21164910 }, { "intent": "How to sort multidimensional array by column?", "rewritten_intent": "sort a multidimensional array `a` by column with index 1", "snippet": "sorted(a, key=lambda x: x[1])", "question_id": 20183069 }, { "intent": "string to list conversion in python", "rewritten_intent": "split string `s` to list conversion by ','", "snippet": "[x.strip() for x in s.split(',')]", "question_id": 9905471 }, { "intent": "Get list item by attribute in Python", "rewritten_intent": "Get a list of items in the list `container` with attribute equal to `value`", "snippet": "items = [item for item in container if item.attribute == value]", "question_id": 9089043 }, { "intent": "Python: Write a list of tuples to a file", "rewritten_intent": "create a file 'filename' with each tuple in the list `mylist` written to a line", "snippet": "open('filename', 'w').write('\\n'.join('%s %s' % x for x in mylist))", "question_id": 3820312 }, { "intent": "Python regex to match multiple times", "rewritten_intent": "Get multiple matched strings using regex pattern `(?:review: )?(http://url.com/(\\\\d+))\\\\s?`", "snippet": "pattern = re.compile('(?:review: )?(http://url.com/(\\\\d+))\\\\s?', re.IGNORECASE)", "question_id": 17407691 }, { "intent": "How do I read a text file into a string variable in Python", "rewritten_intent": "read a text file 'very_Important.txt' into a string variable `str`", "snippet": "str = open('very_Important.txt', 'r').read()", "question_id": 8369219 }, { "intent": "Grouping dataframes in pandas?", "rewritten_intent": "Return values for column `C` after group by on column `A` and `B` in dataframe `df`", "snippet": "df.groupby(['A', 'B'])['C'].unique()", "question_id": 33680914 }, { "intent": "read a file line by line into a list", "rewritten_intent": "read file `fname` line by line into a list `content`", "snippet": "with open(fname) as f:\n content = f.readlines()", "question_id": 3277503 }, { "intent": "read a file line by line into a list", "rewritten_intent": "read file 'filename' line by line into a list `lines`", "snippet": "with open('filename') as f:\n lines = f.readlines()", "question_id": 3277503 }, { "intent": "read a file line by line into a list", "rewritten_intent": "read file 'filename' line by line into a list `lines`", "snippet": "lines = [line.rstrip('\\n') for line in open('filename')]", "question_id": 3277503 }, { "intent": "read a file line by line into a list", "rewritten_intent": "read file \"file.txt\" line by line into a list `array`", "snippet": "with open('file.txt', 'r') as ins:\n array = []\n for line in ins:\n array.append(line)", "question_id": 3277503 }, { "intent": "Convert DataFrame column type from string to datetime", "rewritten_intent": "convert the dataframe column 'col' from string types to datetime types", "snippet": "df['col'] = pd.to_datetime(df['col'])", "question_id": 17134716 }, { "intent": "Can a list of all member-dict keys be created from a dict of dicts using a list comprehension?", "rewritten_intent": "get a list of the keys in each dictionary in a dictionary of dictionaries `foo`", "snippet": "[k for d in list(foo.values()) for k in d]", "question_id": 41251391 }, { "intent": "Possible to get user input without inserting a new line?", "rewritten_intent": "get user input using message 'Enter name here: ' and insert it to the first placeholder in string 'Hello, {0}, how do you do?'", "snippet": "print('Hello, {0}, how do you do?'.format(input('Enter name here: ')))", "question_id": 7173850 }, { "intent": "Create Pandas DataFrame from txt file with specific pattern", "rewritten_intent": "create pandas data frame `df` from txt file `filename.txt` with column `Region Name` and separator `;`", "snippet": "df = pd.read_csv('filename.txt', sep=';', names=['Region Name'])", "question_id": 41386443 }, { "intent": "Pandas: How can I use the apply() function for a single column?", "rewritten_intent": null, "snippet": "df['a'] = df['a'].apply(lambda x: x + 1)", "question_id": 34962104 }, { "intent": "How to check whether the system is FreeBSD in a python script?", "rewritten_intent": "get the platform OS name", "snippet": "platform.system()", "question_id": 30015665 }, { "intent": "How to sort python list of strings of numbers", "rewritten_intent": "sort list `a` in ascending order based on its elements' float values", "snippet": "a = sorted(a, key=lambda x: float(x))", "question_id": 17474211 }, { "intent": "Finding words after keyword in python", "rewritten_intent": "finding words in string `s` after keyword 'name'", "snippet": "re.search('name (.*)', s)", "question_id": 6633678 }, { "intent": "Removing _id element from Pymongo results", "rewritten_intent": "Find all records from collection `collection` without extracting mongo id `_id`", "snippet": "db.collection.find({}, {'_id': False})", "question_id": 12345387 }, { "intent": "How do you extract a column from a multi-dimensional array?", "rewritten_intent": "Get all the second values from a list of lists `A`", "snippet": "[row[1] for row in A]", "question_id": 903853 }, { "intent": "How do you extract a column from a multi-dimensional array?", "rewritten_intent": "extract first column from a multi-dimensional array `a`", "snippet": "[row[0] for row in a]", "question_id": 903853 }, { "intent": "Python - how to sort a list of numerical values in ascending order", "rewritten_intent": "sort list `['10', '3', '2']` in ascending order based on the integer value of its elements", "snippet": "sorted(['10', '3', '2'], key=int)", "question_id": 9758959 }, { "intent": "How can I tell if a file is a descendant of a given directory?", "rewritten_intent": "check if file `filename` is descendant of directory '/the/dir/'", "snippet": "os.path.commonprefix(['/the/dir/', os.path.realpath(filename)]) == '/the/dir/'", "question_id": 3328012 }, { "intent": "Python: How to check a string for substrings from a list?", "rewritten_intent": "check if any element of list `substring_list` are in string `string`", "snippet": "any(substring in string for substring in substring_list)", "question_id": 8122079 }, { "intent": "Construct pandas DataFrame from list of tuples", "rewritten_intent": "construct pandas dataframe from a list of tuples", "snippet": "df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])", "question_id": 19961490 }, { "intent": "How to find and replace nth occurence of word in a sentence using python regular expression?", "rewritten_intent": "find and replace 2nd occurrence of word 'cat' by 'Bull' in a sentence 's'", "snippet": "re.sub('^((?:(?!cat).)*cat(?:(?!cat).)*)cat', '\\\\1Bull', s)", "question_id": 27589325 }, { "intent": "How to find and replace nth occurence of word in a sentence using python regular expression?", "rewritten_intent": "find and replace 2nd occurrence of word 'cat' by 'Bull' in a sentence 's'", "snippet": "re.sub('^((.*?cat.*?){1})cat', '\\\\1Bull', s)", "question_id": 27589325 }, { "intent": "Sort list of strings by integer suffix in python", "rewritten_intent": "sort list of strings in list `the_list` by integer suffix", "snippet": "sorted(the_list, key=lambda k: int(k.split('_')[1]))", "question_id": 4287209 }, { "intent": "Sort list of strings by integer suffix in python", "rewritten_intent": "sort list of strings `the_list` by integer suffix before \"_\"", "snippet": "sorted(the_list, key=lambda x: int(x.split('_')[1]))", "question_id": 4287209 }, { "intent": "How to group similar items in a list?", "rewritten_intent": "make a list of lists in which each list `g` are the elements from list `test` which have the same characters up to the first `_` character", "snippet": "[list(g) for _, g in itertools.groupby(test, lambda x: x.split('_')[0])]", "question_id": 27659153 }, { "intent": "How to group similar items in a list?", "rewritten_intent": null, "snippet": "[list(g) for _, g in itertools.groupby(test, lambda x: x.partition('_')[0])]", "question_id": 27659153 }, { "intent": "How do I use the HTMLUnit driver with Selenium from Python?", "rewritten_intent": "Load the url `http://www.google.com` in selenium webdriver `driver`", "snippet": "driver.get('http://www.google.com')", "question_id": 4618373 }, { "intent": "Using Python's datetime module, can I get the year that UTC-11 is currently in?", "rewritten_intent": "using python's datetime module, get the year that utc-11 is currently in", "snippet": "(datetime.datetime.utcnow() - datetime.timedelta(hours=11)).year", "question_id": 14043080 }, { "intent": "How to find the difference between 3 lists that may have duplicate numbers", "rewritten_intent": "Get the difference between two lists `[1, 2, 2, 2, 3]` and `[1, 2]` that may have duplicate values", "snippet": "Counter([1, 2, 2, 2, 3]) - Counter([1, 2])", "question_id": 33435418 }, { "intent": "How to remove tags from a string in python using regular expressions? (NOT in HTML)", "rewritten_intent": "remove tags from a string `mystring`", "snippet": "re.sub('<[^>]*>', '', mystring)", "question_id": 3662142 }, { "intent": "How can I unpack binary hex formatted data in Python?", "rewritten_intent": "encode string `data` as `hex`", "snippet": "data.encode('hex')", "question_id": 200738 }, { "intent": "How to do a less than or equal to filter in Django queryset?", "rewritten_intent": "filter `Users` by field `userprofile` with level greater than or equal to `0`", "snippet": "User.objects.filter(userprofile__level__gte=0)", "question_id": 10040143 }, { "intent": "How to use Beautiful Soup to find a tag with changing id?", "rewritten_intent": "BeautifulSoup find a tag whose id ends with string 'para'", "snippet": "soup.findAll(id=re.compile('para$'))", "question_id": 11924135 }, { "intent": "How to use Beautiful Soup to find a tag with changing id?", "rewritten_intent": "select `div` tags whose `id`s begin with `value_xxx_c_1_f_8_a_`", "snippet": "soup.select('div[id^=\"value_xxx_c_1_f_8_a_\"]')", "question_id": 11924135 }, { "intent": "How to delete an item in a list if it exists?", "rewritten_intent": "delete an item `thing` in a list `some_list` if it exists", "snippet": "cleaned_list = [x for x in some_list if x is not thing]", "question_id": 4915920 }, { "intent": "user input and commandline arguments", "rewritten_intent": "print \"Please enter something: \" to console, and read user input to `var`", "snippet": "var = input('Please enter something: ')", "question_id": 70797 }, { "intent": "Add to integers in a list", "rewritten_intent": "append 4 to list `foo`", "snippet": "foo.append(4)", "question_id": 4641765 }, { "intent": "Add to integers in a list", "rewritten_intent": "append a list [8, 7] to list `foo`", "snippet": "foo.append([8, 7])", "question_id": 4641765 }, { "intent": "Add to integers in a list", "rewritten_intent": "insert 77 to index 2 of list `x`", "snippet": "x.insert(2, 77)", "question_id": 4641765 }, { "intent": "Removing white space around a saved image in matplotlib", "rewritten_intent": "remove white space padding around a saved image `test.png` in matplotlib", "snippet": "plt.savefig('test.png', bbox_inches='tight')", "question_id": 11837979 }, { "intent": "concatenate lists", "rewritten_intent": "concatenate lists `listone` and `listtwo`", "snippet": "(listone + listtwo)", "question_id": 1720421 }, { "intent": "concatenate lists", "rewritten_intent": "iterate items in lists `listone` and `listtwo`", "snippet": "for item in itertools.chain(listone, listtwo):\n pass", "question_id": 1720421 }, { "intent": "how do you filter pandas dataframes by multiple columns", "rewritten_intent": "create dataframe `males` containing data of dataframe `df` where column `Gender` is equal to 'Male' and column `Year` is equal to 2014", "snippet": "males = df[(df[Gender] == 'Male') & (df[Year] == 2014)]", "question_id": 22086116 }, { "intent": "How to print backslash with Python?", "rewritten_intent": "print backslash", "snippet": "print('\\\\')", "question_id": 19095796 }, { "intent": "How to replace values with None in Pandas data frame in Python?", "rewritten_intent": "replace '-' in pandas dataframe `df` with `np.nan`", "snippet": "df.replace('-', np.nan)", "question_id": 17097236 }, { "intent": "Delete column from pandas DataFrame", "rewritten_intent": "delete column 'column_name' from dataframe `df`", "snippet": "df = df.drop('column_name', 1)", "question_id": 13411544 }, { "intent": "Delete column from pandas DataFrame", "rewritten_intent": "delete 1st, 2nd and 4th columns from dataframe `df`", "snippet": "df.drop(df.columns[[0, 1, 3]], axis=1)", "question_id": 13411544 }, { "intent": "Delete column from pandas DataFrame", "rewritten_intent": "delete a column `column_name` without having to reassign from pandas data frame `df`", "snippet": "df.drop('column_name', axis=1, inplace=True)", "question_id": 13411544 }, { "intent": "Disable abbreviation in argparse", "rewritten_intent": "disable abbreviation in argparse", "snippet": "parser = argparse.ArgumentParser(allow_abbrev=False)", "question_id": 10750802 }, { "intent": "Extract dictionary value from column in data frame", "rewritten_intent": "extract dictionary values by key 'Feature3' from data frame `df`", "snippet": "feature3 = [d.get('Feature3') for d in df.dic]", "question_id": 35711059 }, { "intent": "How to access pandas groupby dataframe by key", "rewritten_intent": "get data of column 'A' and column 'B' in dataframe `df` where column 'A' is equal to 'foo'", "snippet": "df.loc[gb.groups['foo'], ('A', 'B')]", "question_id": 14734533 }, { "intent": "String formatting in Python", "rewritten_intent": "print '[1, 2, 3]'", "snippet": "print('[%s, %s, %s]' % (1, 2, 3))", "question_id": 517355 }, { "intent": "String formatting in Python", "rewritten_intent": "Display `1 2 3` as a list of string", "snippet": "print('[{0}, {1}, {2}]'.format(1, 2, 3))", "question_id": 517355 }, { "intent": "Accessing Python dict values with the key start characters", "rewritten_intent": "get values from a dictionary `my_dict` whose key contains the string `Date`", "snippet": "[v for k, v in list(my_dict.items()) if 'Date' in k]", "question_id": 17106819 }, { "intent": "Python date string formatting", "rewritten_intent": null, "snippet": "\"\"\"{0.month}/{0.day}/{0.year}\"\"\".format(my_date)", "question_id": 18724607 }, { "intent": "Dropping a single (sub-) column from a MultiIndex", "rewritten_intent": "drop a single subcolumn 'a' in column 'col1' from a dataframe `df`", "snippet": "df.drop(('col1', 'a'), axis=1)", "question_id": 22397058 }, { "intent": "Dropping a single (sub-) column from a MultiIndex", "rewritten_intent": "dropping all columns named 'a' from a multiindex 'df', across all level.", "snippet": "df.drop('a', level=1, axis=1)", "question_id": 22397058 }, { "intent": "Build Dictionary in Python Loop - List and Dictionary Comprehensions", "rewritten_intent": "build dictionary with keys of dictionary `_container` as keys and values of returned value of function `_value` with correlating key as parameter", "snippet": "{_key: _value(_key) for _key in _container}", "question_id": 19121722 }, { "intent": "How to click on the text button using selenium python", "rewritten_intent": "click on the text button 'section-select-all' using selenium python", "snippet": "browser.find_element_by_class_name('section-select-all').click()", "question_id": 34527388 }, { "intent": "Python - Combine two dictionaries, concatenate string values?", "rewritten_intent": "combine two dictionaries `d ` and `d1`, concatenate string values with identical `keys`", "snippet": "dict((k, d.get(k, '') + d1.get(k, '')) for k in keys)", "question_id": 17604837 }, { "intent": "How to generate unique equal hash for equal dictionaries?", "rewritten_intent": "generate unique equal hash for equal dictionaries `a` and `b`", "snippet": "hash(pformat(a)) == hash(pformat(b))", "question_id": 16735786 }, { "intent": "How to convert nested list of lists into a list of tuples in python 3.3?", "rewritten_intent": "convert nested list of lists `[['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]` into a list of tuples", "snippet": "list(map(tuple, [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]))", "question_id": 18938276 }, { "intent": "Summing across rows of Pandas Dataframe", "rewritten_intent": "sum the column `positions` along the other columns `stock`, `same1`, `same2` in a pandas data frame `df`", "snippet": "df.groupby(['stock', 'same1', 'same2'], as_index=False)['positions'].sum()", "question_id": 17166601 }, { "intent": "Summing across rows of Pandas Dataframe", "rewritten_intent": null, "snippet": "df.groupby(['stock', 'same1', 'same2'])['positions'].sum().reset_index()", "question_id": 17166601 }, { "intent": "change a string into uppercase", "rewritten_intent": "change string `s` to upper case", "snippet": "s.upper()", "question_id": 9257094 }, { "intent": "Splitting a semicolon-separated string to a dictionary, in Python", "rewritten_intent": "split a string `s` by ';' and convert to a dictionary", "snippet": "dict(item.split('=') for item in s.split(';'))", "question_id": 186857 }, { "intent": "how to set cookie in python mechanize", "rewritten_intent": "Add header `('Cookie', 'cookiename=cookie value')` to mechanize browser `br`", "snippet": "br.addheaders = [('Cookie', 'cookiename=cookie value')]", "question_id": 15459217 }, { "intent": "How to remove square bracket from pandas dataframe", "rewritten_intent": "set data in column 'value' of dataframe `df` equal to first element of each list", "snippet": "df['value'] = df['value'].str[0]", "question_id": 38147447 }, { "intent": "How to remove square bracket from pandas dataframe", "rewritten_intent": "get element at index 0 of each list in column 'value' of dataframe `df`", "snippet": "df['value'] = df['value'].str.get(0)", "question_id": 38147447 }, { "intent": "How to remove square bracket from pandas dataframe", "rewritten_intent": "remove square bracket '[]' from pandas dataframe `df` column 'value'", "snippet": "df['value'] = df['value'].str.strip('[]')", "question_id": 38147447 }, { "intent": "Python getting a string (key + value) from Python Dictionary", "rewritten_intent": "Get a string with string formatting from dictionary `d`", "snippet": "\"\"\", \"\"\".join(['{}_{}'.format(k, v) for k, v in d.items()])", "question_id": 17462994 }, { "intent": "Easier way to add multiple list items?", "rewritten_intent": "Sum of sums of each list, in a list of lists named 'lists'.", "snippet": "sum(sum(x) for x in lists)", "question_id": 15465204 }, { "intent": "testing whether a Numpy array contains a given row", "rewritten_intent": "Check whether a numpy array `a` contains a given row `[1, 2]`", "snippet": "any(np.equal(a, [1, 2]).all(1))", "question_id": 14766194 }, { "intent": "How do I check if all elements in a list are the same?", "rewritten_intent": "check if all elements in list `mylist` are the same", "snippet": "len(set(mylist)) == 1", "question_id": 22240602 }, { "intent": "How to split a string at line breaks in python?", "rewritten_intent": "split a string `s` at line breaks `\\r\\n`", "snippet": "[map(int, x.split('\\t')) for x in s.rstrip().split('\\r\\n')]", "question_id": 21205074 }, { "intent": "Create a hierarchy from a dictionary of lists", "rewritten_intent": "sort a dictionary `a` by values that are list type", "snippet": "t = sorted(list(a.items()), key=lambda x: x[1])", "question_id": 20230211 }, { "intent": "Search for string in txt file", "rewritten_intent": "Search for string 'blabla' in txt file 'example.txt'", "snippet": "if ('blabla' in open('example.txt').read()):\n pass", "question_id": 4940032 }, { "intent": "Search for string in txt file", "rewritten_intent": "Search for string 'blabla' in txt file 'example.txt'", "snippet": "f = open('example.txt')\ns = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)\nif (s.find('blabla') != (-1)):\n pass", "question_id": 4940032 }, { "intent": "Search for string in txt file", "rewritten_intent": "Search for string `blabla` in txt file 'example.txt'", "snippet": "datafile = file('example.txt')\nfound = False\nfor line in datafile:\n if (blabla in line):\n return True\nreturn False", "question_id": 4940032 }, { "intent": "Replacing the empty strings in a string", "rewritten_intent": "insert string `string1` after each character of `string2`", "snippet": "string2.replace('', string1)[len(string1):-len(string1)]", "question_id": 14431731 }, { "intent": "getting every possible combination in a list", "rewritten_intent": "getting every possible combination of two elements in a list", "snippet": "list(itertools.combinations([1, 2, 3, 4, 5, 6], 2))", "question_id": 5106228 }, { "intent": "Python 3: How do I get a string literal representation of a byte string?", "rewritten_intent": "get a utf-8 string literal representation of byte string `x`", "snippet": "\"\"\"x = {}\"\"\".format(x.decode('utf8')).encode('utf8')", "question_id": 15390374 }, { "intent": "Checking whether a variable is an integer", "rewritten_intent": "check if `x` is an integer", "snippet": "isinstance(x, int)", "question_id": 3501382 }, { "intent": "Checking whether a variable is an integer", "rewritten_intent": "check if `x` is an integer", "snippet": "(type(x) == int)", "question_id": 3501382 }, { "intent": "Play a Sound with Python", "rewritten_intent": "play the wav file 'sound.wav'", "snippet": "winsound.PlaySound('sound.wav', winsound.SND_FILENAME)", "question_id": 307305 }, { "intent": "How to get the n next values of a generator in a list (python)", "rewritten_intent": "create a list containing the `n` next values of generator `it`", "snippet": "[next(it) for _ in range(n)]", "question_id": 4152376 }, { "intent": "How to get the n next values of a generator in a list (python)", "rewritten_intent": "get list of n next values of a generator `it`", "snippet": "list(itertools.islice(it, 0, n, 1))", "question_id": 4152376 }, { "intent": "How can I compare two lists in python and return matches", "rewritten_intent": "compare two lists in python `a` and `b` and return matches", "snippet": "set(a).intersection(b)", "question_id": 1388818 }, { "intent": "How can I compare two lists in python and return matches", "rewritten_intent": null, "snippet": "[i for i, j in zip(a, b) if i == j]", "question_id": 1388818 }, { "intent": "How to print a list with integers without the brackets, commas and no quotes?", "rewritten_intent": "convert list `data` into a string of its elements", "snippet": "print(''.join(map(str, data)))", "question_id": 17757450 }, { "intent": "python regex: match a string with only one instance of a character", "rewritten_intent": "match regex pattern '\\\\$[0-9]+[^\\\\$]*$' on string '$1 off delicious $5 ham.'", "snippet": "re.match('\\\\$[0-9]+[^\\\\$]*$', '$1 off delicious $5 ham.')", "question_id": 3166619 }, { "intent": "How to import a module in Python with importlib.import_module", "rewritten_intent": "import a nested module `c.py` within `b` within `a` with importlib", "snippet": "importlib.import_module('.c', 'a.b')", "question_id": 10675054 }, { "intent": "How to import a module in Python with importlib.import_module", "rewritten_intent": "import a module 'a.b.c' with importlib.import_module in python 2", "snippet": "importlib.import_module('a.b.c')", "question_id": 10675054 }, { "intent": "how to convert 2d list to 2d numpy array?", "rewritten_intent": "Convert array `a` to numpy array", "snippet": "a = np.array(a)", "question_id": 7717380 }, { "intent": "Python regular expression for Beautiful Soup", "rewritten_intent": "Find all `div` tags whose classes has the value `comment-` in a beautiful soup object `soup`", "snippet": "soup.find_all('div', class_=re.compile('comment-'))", "question_id": 13794532 }, { "intent": "A sequence of empty lists of length n in Python?", "rewritten_intent": "a sequence of empty lists of length `n`", "snippet": "[[] for _ in range(n)]", "question_id": 23612271 }, { "intent": "create dictionary from list of variables", "rewritten_intent": "create dictionary from list of variables 'foo' and 'bar' already defined", "snippet": "dict((k, globals()[k]) for k in ('foo', 'bar'))", "question_id": 9495262 }, { "intent": "How to get two random records with Django", "rewritten_intent": "get two random records from model 'MyModel' in Django", "snippet": "MyModel.objects.order_by('?')[:2]", "question_id": 1731346 }, { "intent": "How to use a dot in Python format strings?", "rewritten_intent": "Print a dictionary `{'user': {'name': 'Markus'}}` with string formatting", "snippet": "\"\"\"Hello {user[name]}\"\"\".format(**{'user': {'name': 'Markus'}})", "question_id": 29035168 }, { "intent": "Python: using a dict to speed sorting of a list of tuples", "rewritten_intent": "create a dictionary `list_dict` containing each tuple in list `tuple_list` as values and the tuple's first element as the corresponding key", "snippet": "list_dict = {t[0]: t for t in tuple_list}", "question_id": 20059427 }, { "intent": "Generate random integers between 0 and 9", "rewritten_intent": "Generate a random integer between 0 and 9", "snippet": "randint(0, 9)", "question_id": 3996904 }, { "intent": "Generate random integers between 0 and 9", "rewritten_intent": "Generate a random integer between `a` and `b`", "snippet": "random.randint(a, b)", "question_id": 3996904 }, { "intent": "Generate random integers between 0 and 9", "rewritten_intent": "Generate random integers between 0 and 9", "snippet": "print((random.randint(0, 9)))", "question_id": 3996904 }, { "intent": "Reverse a string in Python two characters at a time (Network byte order)", "rewritten_intent": "reverse a string `a` by 2 characters at a time", "snippet": "\"\"\"\"\"\".join(reversed([a[i:i + 2] for i in range(0, len(a), 2)]))", "question_id": 5864271 }, { "intent": "How to transform a time series pandas dataframe using the index attributes?", "rewritten_intent": "transform time series `df` into a pivot table aggregated by column 'Close' using column `df.index.date` as index and values of column `df.index.time` as columns", "snippet": "pd.pivot_table(df, index=df.index.date, columns=df.index.time, values='Close')", "question_id": 28664103 }, { "intent": "How to check if all elements of a list matches a condition?", "rewritten_intent": "check if the third element of all the lists in a list \"items\" is equal to zero.", "snippet": "any(item[2] == 0 for item in items)", "question_id": 10666163 }, { "intent": "How to check if all elements of a list matches a condition?", "rewritten_intent": "Find all the lists from a lists of list 'items' if third element in all sub-lists is '0'", "snippet": "[x for x in items if x[2] == 0]", "question_id": 10666163 }, { "intent": "Python: sorting dictionary of dictionaries", "rewritten_intent": "sort dictionary of dictionaries `dic` according to the key 'Fisher'", "snippet": "sorted(list(dic.items()), key=lambda x: x[1]['Fisher'], reverse=True)", "question_id": 16412563 }, { "intent": "Logarithmic y-axis bins in python", "rewritten_intent": "plot a data logarithmically in y axis", "snippet": "plt.yscale('log', nonposy='clip')", "question_id": 17952279 }, { "intent": "extract digits in a simple way from a python string", "rewritten_intent": null, "snippet": "map(int, re.findall('\\\\d+', s))", "question_id": 10365225 }, { "intent": "How can I list the contents of a directory in Python?", "rewritten_intent": "list the contents of a directory '/home/username/www/'", "snippet": "os.listdir('/home/username/www/')", "question_id": 2759323 }, { "intent": "How can I list the contents of a directory in Python?", "rewritten_intent": "list all the contents of the directory 'path'.", "snippet": "os.listdir('path')", "question_id": 2759323 }, { "intent": "How to merge two DataFrames into single matching the column values", "rewritten_intent": "merge a pandas data frame `distancesDF` and column `dates` in pandas data frame `datesDF` into single", "snippet": "pd.concat([distancesDF, datesDF.dates], axis=1)", "question_id": 40076861 }, { "intent": "Python How to get every first element in 2 Dimensional List", "rewritten_intent": "get value of first index of each element in list `a`", "snippet": "[x[0] for x in a]", "question_id": 30062429 }, { "intent": "Python How to get every first element in 2 Dimensional List", "rewritten_intent": "python how to get every first element in 2 dimensional list `a`", "snippet": "[i[0] for i in a]", "question_id": 30062429 }, { "intent": "Regular expression to remove line breaks", "rewritten_intent": "remove line breaks from string `textblock` using regex", "snippet": "re.sub('(?<=[a-z])\\\\r?\\\\n', ' ', textblock)", "question_id": 5075247 }, { "intent": "Reading utf-8 characters from a gzip file in python", "rewritten_intent": "Open gzip-compressed file encoded as utf-8 'file.gz' in text mode", "snippet": "gzip.open('file.gz', 'rt', encoding='utf-8')", "question_id": 1883604 }, { "intent": "Can Python test the membership of multiple values in a list?", "rewritten_intent": "test if either of strings `a` or `b` are members of the set of strings, `['b', 'a', 'foo', 'bar']`", "snippet": "set(['a', 'b']).issubset(['b', 'a', 'foo', 'bar'])", "question_id": 6159313 }, { "intent": "Can Python test the membership of multiple values in a list?", "rewritten_intent": "Check if all the values in a list `['a', 'b']` are present in another list `['b', 'a', 'foo', 'bar']`", "snippet": "all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])", "question_id": 6159313 }, { "intent": "Remove specific characters from a string", "rewritten_intent": "Remove characters \"!@#$\" from a string `line`", "snippet": "line.translate(None, '!@#$')", "question_id": 3939361 }, { "intent": "Remove specific characters from a string", "rewritten_intent": "Remove characters \"!@#$\" from a string `line`", "snippet": "line = re.sub('[!@#$]', '', line)", "question_id": 3939361 }, { "intent": "Remove specific characters from a string", "rewritten_intent": "Remove string \"1\" from string `string`", "snippet": "string.replace('1', '')", "question_id": 3939361 }, { "intent": "Remove specific characters from a string", "rewritten_intent": "Remove character `char` from a string `a`", "snippet": "a = a.replace(char, '')", "question_id": 3939361 }, { "intent": "Remove specific characters from a string", "rewritten_intent": "Remove characters in `b` from a string `a`", "snippet": "a = a.replace(char, '')", "question_id": 3939361 }, { "intent": "Remove specific characters from a string", "rewritten_intent": "Remove characters in '!@#$' from a string `line`", "snippet": "line = line.translate(string.maketrans('', ''), '!@#$')", "question_id": 3939361 }, { "intent": "How to binarize the values in a pandas DataFrame?", "rewritten_intent": "binarize the values in columns of list `order` in a pandas data frame", "snippet": "pd.concat([df, pd.get_dummies(df, '', '').astype(int)], axis=1)[order]", "question_id": 38704545 }, { "intent": "Storing a collection of integers in a list", "rewritten_intent": "store integer 3, 4, 1 and 2 in a list", "snippet": "[3, 4, 1, 2]", "question_id": 19672101 }, { "intent": "Is it possible to define global variables in a function in Python", "rewritten_intent": "define global variable `something` with value `bob`", "snippet": "globals()['something'] = 'bob'", "question_id": 13627865 }, { "intent": "I'm looking for a pythonic way to insert a space before capital letters", "rewritten_intent": "insert spaces before capital letters in string `text`", "snippet": "re.sub('([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', '\\\\1 ', text)", "question_id": 199059 }, { "intent": "How can I convert Unicode to uppercase to print it?", "rewritten_intent": "print unicode string `ex\\xe1mple` in uppercase", "snippet": "print('ex\\xe1mple'.upper())", "question_id": 727507 }, { "intent": "Remove string from list if from substring list", "rewritten_intent": "get last element of string splitted by '\\\\' from list of strings `list_dirs`", "snippet": "[l.split('\\\\')[-1] for l in list_dirs]", "question_id": 28657018 }, { "intent": "What's the Pythonic way to combine two sequences into a dictionary?", "rewritten_intent": "combine two sequences into a dictionary", "snippet": "dict(zip(keys, values))", "question_id": 579856 }, { "intent": "How to Customize the time format for Python logging?", "rewritten_intent": "customize the time format in python logging", "snippet": "formatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s')", "question_id": 3220284 }, { "intent": "Python Regex replace", "rewritten_intent": "Replace comma with dot in a string `original_string` using regex", "snippet": "new_string = re.sub('\"(\\\\d+),(\\\\d+)\"', '\\\\1.\\\\2', original_string)", "question_id": 8172861 }, { "intent": "Can a python script execute a function inside a bash script?", "rewritten_intent": "call a function `otherfunc` inside a bash script `test.sh` using subprocess", "snippet": "subprocess.call('test.sh otherfunc')", "question_id": 5826427 }, { "intent": "Can a python script execute a function inside a bash script?", "rewritten_intent": null, "snippet": "subprocess.Popen(['bash', '-c', '. foo.sh; go'])", "question_id": 5826427 }, { "intent": "A simple way to remove multiple spaces in a string in Python", "rewritten_intent": "remove multiple spaces in a string `foo`", "snippet": "\"\"\" \"\"\".join(foo.split())", "question_id": 1546226 }, { "intent": "How to convert decimal to binary list in python", "rewritten_intent": "convert decimal 8 to a list of its binary values", "snippet": "list('{0:0b}'.format(8))", "question_id": 13557937 }, { "intent": "How to convert decimal to binary list in python", "rewritten_intent": "convert decimal integer 8 to a list of its binary values as elements", "snippet": "[int(x) for x in list('{0:0b}'.format(8))]", "question_id": 13557937 }, { "intent": "How to convert decimal to binary list in python", "rewritten_intent": "convert decimal `8` to binary list", "snippet": "[int(x) for x in bin(8)[2:]]", "question_id": 13557937 }, { "intent": "Is it possible to take an ordered \"slice\" of a dictionary in Python based on a list of keys?", "rewritten_intent": "get key-value pairs in dictionary `my_dictionary` for all keys in list `my_list` in the order they appear in `my_list`", "snippet": "dict(zip(my_list, map(my_dictionary.get, my_list)))", "question_id": 9932549 }, { "intent": "Numpy: cartesian product of x and y array points into single array of 2D points", "rewritten_intent": "cartesian product of `x` and `y` array points into single array of 2d points", "snippet": "numpy.dstack(numpy.meshgrid(x, y)).reshape(-1, 2)", "question_id": 11144513 }, { "intent": "Selenium Webdriver - NoSuchElementExceptions", "rewritten_intent": "selenium wait for driver `driver` 60 seconds before throwing a NoSuchElementExceptions exception", "snippet": "driver.implicitly_wait(60)", "question_id": 16739319 }, { "intent": "Selenium Webdriver - NoSuchElementExceptions", "rewritten_intent": "selenium webdriver switch to frame 'frameName'", "snippet": "driver.switch_to_frame('frameName')", "question_id": 16739319 }, { "intent": "Format time string in Python 3.3", "rewritten_intent": "format current date to pattern '{%Y-%m-%d %H:%M:%S}'", "snippet": "time.strftime('{%Y-%m-%d %H:%M:%S}')", "question_id": 21618351 }, { "intent": "How do I sort a Python list of time values?", "rewritten_intent": "sort list `['14:10:01', '03:12:08']`", "snippet": "sorted(['14:10:01', '03:12:08'])", "question_id": 17713873 }, { "intent": "Regex for location matching - Python", "rewritten_intent": "find all occurrences of regex pattern '(?:\\\\w+(?:\\\\s+\\\\w+)*,\\\\s)+(?:\\\\w+(?:\\\\s\\\\w+)*)' in string `x`", "snippet": "re.findall('(?:\\\\w+(?:\\\\s+\\\\w+)*,\\\\s)+(?:\\\\w+(?:\\\\s\\\\w+)*)', x)", "question_id": 20778951 }, { "intent": "Pandas: How can I remove duplicate rows from DataFrame and calculate their frequency?", "rewritten_intent": "remove duplicate rows from dataframe `df1` and calculate their frequency", "snippet": "df1.groupby(['key', 'year']).size().reset_index()", "question_id": 21558999 }, { "intent": "How do I iterate over a Python dictionary, ordered by values?", "rewritten_intent": "sort dictionary `dictionary` in ascending order by its values", "snippet": "sorted(list(dictionary.items()), key=operator.itemgetter(1))", "question_id": 674509 }, { "intent": "How do I iterate over a Python dictionary, ordered by values?", "rewritten_intent": "Iterate over dictionary `d` in ascending order of values", "snippet": "sorted(iter(d.items()), key=lambda x: x[1])", "question_id": 674509 }, { "intent": "How do I iterate over a Python dictionary, ordered by values?", "rewritten_intent": "iterate over a python dictionary, ordered by values", "snippet": "sorted(list(dictionary.items()), key=lambda x: x[1])", "question_id": 674509 }, { "intent": "How to split 1D array into 2D array in NumPy by splitting the array at the last element?", "rewritten_intent": "split 1d array `a` into 2d array at the last element", "snippet": "np.split(a, [-1])", "question_id": 42098487 }, { "intent": "Python pandas - grouping by and summarizing on a field", "rewritten_intent": "convert dataframe `df` into a pivot table using column 'order' as index and values of column 'sample' as columns", "snippet": "df.pivot(index='order', columns='sample')", "question_id": 30406725 }, { "intent": "selecting across multiple columns with python pandas?", "rewritten_intent": "select all rows from pandas DataFrame 'df' where the value in column 'A' is greater than 1 or less than -1 in column 'B'.", "snippet": "df[(df['A'] > 1) | (df['B'] < -1)]", "question_id": 8916302 }, { "intent": "Zip with list output instead of tuple", "rewritten_intent": "Get the zip output as list from the lists `[1, 2, 3]`, `[4, 5, 6]`, `[7, 8, 9]`", "snippet": "[list(a) for a in zip([1, 2, 3], [4, 5, 6], [7, 8, 9])]", "question_id": 8372399 }, { "intent": "Select rows from a DataFrame based on values in a column in pandas", "rewritten_intent": "select rows of dataframe `df` whose value for column `A` is `foo`", "snippet": "print(df.loc[df['A'] == 'foo'])", "question_id": 17071871 }, { "intent": "Select rows from a DataFrame based on values in a column in pandas", "rewritten_intent": "select rows whose column value in column `column_name` does not equal `some_value` in pandas data frame", "snippet": "df.loc[df['column_name'] != some_value]", "question_id": 17071871 }, { "intent": "Select rows from a DataFrame based on values in a column in pandas", "rewritten_intent": "select rows from a dataframe `df` whose value for column `column_name` is not in `some_values`", "snippet": "df.loc[~df['column_name'].isin(some_values)]", "question_id": 17071871 }, { "intent": "Select rows from a DataFrame based on values in a column in pandas", "rewritten_intent": "select all rows whose values in a column `column_name` equals a scalar `some_value` in pandas data frame object `df`", "snippet": "df.loc[df['column_name'] == some_value]", "question_id": 17071871 }, { "intent": "Select rows from a DataFrame based on values in a column in pandas", "rewritten_intent": "Select rows whose value of the \"B\" column is \"one\" or \"three\" in the DataFrame `df`", "snippet": "print(df.loc[df['B'].isin(['one', 'three'])])", "question_id": 17071871 }, { "intent": "How to repeat individual characters in strings in Python", "rewritten_intent": "repeat every character for 7 times in string 'map'", "snippet": "\"\"\"\"\"\".join(map(lambda x: x * 7, 'map'))", "question_id": 38273353 }, { "intent": "Delete a file or folder", "rewritten_intent": "delete an empty directory", "snippet": "os.rmdir()", "question_id": 6996603 }, { "intent": "Delete a file or folder", "rewritten_intent": "recursively delete all contents in directory `path`", "snippet": "shutil.rmtree(path, ignore_errors=False, onerror=None)", "question_id": 6996603 }, { "intent": "Delete a file or folder", "rewritten_intent": "recursively remove folder `name`", "snippet": "os.removedirs(name)", "question_id": 6996603 }, { "intent": "How to add an extra row to a pandas dataframe", "rewritten_intent": "Add row `['8/19/2014', 'Jun', 'Fly', '98765']` to dataframe `df`", "snippet": "df.loc[len(df)] = ['8/19/2014', 'Jun', 'Fly', '98765']", "question_id": 19365513 }, { "intent": "listing files from a directory using glob python", "rewritten_intent": "list all files in a current directory", "snippet": "glob.glob('*')", "question_id": 22625616 }, { "intent": "listing files from a directory using glob python", "rewritten_intent": "List all the files that doesn't contain the name `hello`", "snippet": "glob.glob('[!hello]*.txt')", "question_id": 22625616 }, { "intent": "listing files from a directory using glob python", "rewritten_intent": "List all the files that matches the pattern `hello*.txt`", "snippet": "glob.glob('hello*.txt')", "question_id": 22625616 }, { "intent": "test a boolean expression in a Python string", "rewritten_intent": "evaluate the expression '20<30'", "snippet": "eval('20<30')", "question_id": 10586778 }, { "intent": "Python copy a list of lists", "rewritten_intent": "Copy list `old_list` and name it `new_list`", "snippet": "new_list = [x[:] for x in old_list]", "question_id": 28684154 }, { "intent": "Convert scientific notation to decimal - python", "rewritten_intent": "convert scientific notation of variable `a` to decimal", "snippet": "\"\"\"{:.50f}\"\"\".format(float(a[0] / a[1]))", "question_id": 16962512 }, { "intent": "How to remove 0's converting pandas dataframe to record", "rewritten_intent": "convert dataframe `df` to integer-type sparse object", "snippet": "df.to_sparse(0)", "question_id": 41154648 }, { "intent": "python - readable list of objects", "rewritten_intent": "display attribute `attr` for each object `obj` in list `my_list_of_objs`", "snippet": "print([obj.attr for obj in my_list_of_objs])", "question_id": 444058 }, { "intent": "get count of values associated with key in dict python", "rewritten_intent": "count the number of True values associated with key 'success' in dictionary `d`", "snippet": "sum(1 if d['success'] else 0 for d in s)", "question_id": 35269374 }, { "intent": "get count of values associated with key in dict python", "rewritten_intent": "get the sum of values associated with the key \u2018success\u2019 for a list of dictionaries `s`", "snippet": "sum(d['success'] for d in s)", "question_id": 35269374 }, { "intent": "get path from a module name", "rewritten_intent": "get complete path of a module named `os`", "snippet": "imp.find_module('os')[1]", "question_id": 9534608 }, { "intent": "get the logical xor of two variables", "rewritten_intent": "get logical xor of `a` and `b`", "snippet": "(bool(a) != bool(b))", "question_id": 432842 }, { "intent": "get the logical xor of two variables", "rewritten_intent": "get logical xor of `a` and `b`", "snippet": "((a and (not b)) or ((not a) and b))", "question_id": 432842 }, { "intent": "get the logical xor of two variables", "rewritten_intent": "get logical xor of `a` and `b`", "snippet": "(bool(a) ^ bool(b))", "question_id": 432842 }, { "intent": "get the logical xor of two variables", "rewritten_intent": "get logical xor of `a` and `b`", "snippet": "xor(bool(a), bool(b))", "question_id": 432842 }, { "intent": "get the logical xor of two variables", "rewritten_intent": "get the logical xor of two variables `str1` and `str2`", "snippet": "return (bool(str1) ^ bool(str2))", "question_id": 432842 }, { "intent": "How to alphabetically sort array of dictionaries on single key?", "rewritten_intent": "Sort list `my_list` in alphabetical order based on the values associated with key 'name' of each dictionary in the list", "snippet": "my_list.sort(key=operator.itemgetter('name'))", "question_id": 5048841 }, { "intent": "Python: Split string by list of separators", "rewritten_intent": "split a string `a , b; cdf` using both commas and semicolons as delimeters", "snippet": "re.split('\\\\s*,\\\\s*|\\\\s*;\\\\s*', 'a , b; cdf')", "question_id": 4697006 }, { "intent": "Python: Split string by list of separators", "rewritten_intent": "Split a string `string` by multiple separators `,` and `;`", "snippet": "[t.strip() for s in string.split(',') for t in s.split(';')]", "question_id": 4697006 }, { "intent": "lambda in python", "rewritten_intent": "make a function `f` that calculates the sum of two integer variables `x` and `y`", "snippet": "f = lambda x, y: x + y", "question_id": 7974442 }, { "intent": "Creating a list of objects in Python", "rewritten_intent": "Create list `instancelist` containing 29 objects of type MyClass", "snippet": "instancelist = [MyClass() for i in range(29)]", "question_id": 348196 }, { "intent": "Python 2.7: making a dictionary object from a specially-formatted list object", "rewritten_intent": "Make a dictionary from list `f` which is in the format of four sets of \"val, key, val\"", "snippet": "{f[i + 1]: [f[i], f[i + 2]] for i in range(0, len(f), 3)}", "question_id": 23914774 }, { "intent": "Shortest way to convert these bytes to int in python?", "rewritten_intent": "convert bytes string `s` to an unsigned integer", "snippet": "struct.unpack('>q', s)[0]", "question_id": 4433017 }, { "intent": "How can I concatenate a Series onto a DataFrame with Pandas?", "rewritten_intent": "concatenate a series `students` onto a dataframe `marks` with pandas", "snippet": "pd.concat([students, pd.DataFrame(marks)], axis=1)", "question_id": 20512297 }, { "intent": "Custom Python list sorting", "rewritten_intent": "Sort list `alist` in ascending order based on each of its elements' attribute `foo`", "snippet": "alist.sort(key=lambda x: x.foo)", "question_id": 11850425 }, { "intent": "How to get only div with id ending with a certain value in Beautiful Soup?", "rewritten_intent": "BeautifulSoup select 'div' elements with an id attribute value ending with sub-string '_answer' in HTML parsed string `soup`", "snippet": "soup.select('div[id$=_answer]')", "question_id": 42180455 }, { "intent": "How can I solve system of linear equations in SymPy?", "rewritten_intent": "sympy solve matrix of linear equations `(([1, 1, 1, 1], [1, 1, 2, 3]))` with variables `(x, y, z)`", "snippet": "linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))", "question_id": 31547657 }, { "intent": "best way to extract subset of key-value pairs from python dictionary object", "rewritten_intent": "best way to extract subset of key-value pairs with keys matching 'l', 'm', or 'n' from python dictionary object", "snippet": "{k: bigdict[k] for k in list(bigdict.keys()) & {'l', 'm', 'n'}}", "question_id": 5352546 }, { "intent": "best way to extract subset of key-value pairs from python dictionary object", "rewritten_intent": "extract subset of key-value pairs with keys as `('l', 'm', 'n')` from dictionary object `bigdict`", "snippet": "dict((k, bigdict[k]) for k in ('l', 'm', 'n'))", "question_id": 5352546 }, { "intent": "best way to extract subset of key-value pairs from python dictionary object", "rewritten_intent": "Get items from a dictionary `bigdict` where the keys are present in `('l', 'm', 'n')`", "snippet": "{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}", "question_id": 5352546 }, { "intent": "best way to extract subset of key-value pairs from python dictionary object", "rewritten_intent": "Extract subset of key value pair for keys 'l', 'm', 'n' from `bigdict` in python 3", "snippet": "{k: bigdict[k] for k in ('l', 'm', 'n')}", "question_id": 5352546 }, { "intent": "Get contents of entire page using Selenium", "rewritten_intent": "Selenium get the entire `driver` page text", "snippet": "driver.page_source", "question_id": 16114244 }, { "intent": "Extracting specific columns in numpy array", "rewritten_intent": "extracting column `1` and `9` from array `data`", "snippet": "data[:, ([1, 9])]", "question_id": 8386675 }, { "intent": "Remove string between 2 characters from text string", "rewritten_intent": "remove all square brackets from string 'abcd[e]yth[ac]ytwec'", "snippet": "re.sub('\\\\[.*?\\\\]', '', 'abcd[e]yth[ac]ytwec')", "question_id": 9470142 }, { "intent": "How can I resize the root window in Tkinter?", "rewritten_intent": null, "snippet": "root.geometry('500x500')", "question_id": 2261011 }, { "intent": "How to capture the entire string while using 'lookaround' with chars in regex?", "rewritten_intent": "find all substrings in string `mystring` composed only of letters `a` and `b` where each `a` is directly preceded and succeeded by `b`", "snippet": "re.findall('\\\\b(?:b+a)+b+\\\\b', mystring)", "question_id": 32926587 }, { "intent": "in Python, how to convert list of float numbers to string with certain format?", "rewritten_intent": "convert list `lst` of tuples of floats to list `str_list` of tuples of strings of floats in scientific notation with eight decimal point precision", "snippet": "str_list = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in lst]", "question_id": 16127862 }, { "intent": "in Python, how to convert list of float numbers to string with certain format?", "rewritten_intent": "convert list of sublists `lst` of floats to a list of sublists `str_list` of strings of integers in scientific notation with 8 decimal points", "snippet": "str_list = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in lst]", "question_id": 16127862 }, { "intent": "Getting the first elements per row in an array in Python?", "rewritten_intent": "Create a tuple `t` containing first element of each tuple in tuple `s`", "snippet": "t = tuple(x[0] for x in s)", "question_id": 2054416 }, { "intent": "How to obtain the day of the week in a 3 letter format from a datetime object in python?", "rewritten_intent": "obtain the current day of the week in a 3 letter format from a datetime object", "snippet": "datetime.datetime.now().strftime('%a')", "question_id": 15509617 }, { "intent": "get the ASCII value of a character as an int", "rewritten_intent": "get the ASCII value of a character 'a' as an int", "snippet": "ord('a')", "question_id": 227459 }, { "intent": "get the ASCII value of a character as an int", "rewritten_intent": "get the ASCII value of a character u'\u3042' as an int", "snippet": "ord('\\u3042')", "question_id": 227459 }, { "intent": "get the ASCII value of a character as an int", "rewritten_intent": "get the ASCII value of a character as an int", "snippet": "ord()", "question_id": 227459 }, { "intent": "decode JSON", "rewritten_intent": "decode JSON string `u` to a dictionary", "snippet": "json.load(u)", "question_id": 2331943 }, { "intent": "Deleting mulitple columns in Pandas", "rewritten_intent": "Delete mulitple columns `columnheading1`, `columnheading2` in pandas data frame `yourdf`", "snippet": "yourdf.drop(['columnheading1', 'columnheading2'], axis=1, inplace=True)", "question_id": 28538536 }, { "intent": "How to read formatted input in python?", "rewritten_intent": "get a list of of elements resulting from splitting user input by commas and stripping white space from each resulting string `s`", "snippet": "[s.strip() for s in input().split(',')]", "question_id": 1397827 }, { "intent": "Convert binary to list of digits Python", "rewritten_intent": "create a list containing the digits values from binary string `x` as elements", "snippet": "[int(d) for d in str(bin(x))[2:]]", "question_id": 13081090 }, { "intent": "How to get a max string length in nested lists", "rewritten_intent": "get the max string length in list `i`", "snippet": "max(len(word) for word in i)", "question_id": 39373620 }, { "intent": "How to get a max string length in nested lists", "rewritten_intent": "get the maximum string length in nested list `i`", "snippet": "len(max(i, key=len))", "question_id": 39373620 }, { "intent": "Python: How to Redirect Output with Subprocess?", "rewritten_intent": "execute os command `my_cmd`", "snippet": "os.system(my_cmd)", "question_id": 4965159 }, { "intent": "How do I sort a list of strings in Python?", "rewritten_intent": "sort list `mylist` alphabetically", "snippet": "mylist.sort(key=lambda x: x.lower())", "question_id": 36139 }, { "intent": "How do I sort a list of strings in Python?", "rewritten_intent": "sort list `mylist` in alphabetical order", "snippet": "mylist.sort(key=str.lower)", "question_id": 36139 }, { "intent": "How do I sort a list of strings in Python?", "rewritten_intent": "sort a list of strings 'mylist'.", "snippet": "mylist.sort()", "question_id": 36139 }, { "intent": "How do I sort a list of strings in Python?", "rewritten_intent": "sort a list of strings `list`", "snippet": "list.sort()", "question_id": 36139 }, { "intent": "set multi index of an existing data frame in pandas", "rewritten_intent": "Set multi index on columns 'Company' and 'date' of data frame `df` in pandas.", "snippet": "df.set_index(['Company', 'date'], inplace=True)", "question_id": 24041436 }, { "intent": "How can I use a string with the same name of an object in Python to access the object itself?", "rewritten_intent": "get the attribute `x` from object `your_obj`", "snippet": "getattr(your_obj, x)", "question_id": 9396706 }, { "intent": "Remove the first word in a Python string?", "rewritten_intent": "remove first word in string `s`", "snippet": "s.split(' ', 1)[1]", "question_id": 12883376 }, { "intent": "How to save Xlsxwriter file in certain path?", "rewritten_intent": "save xlsxwriter file in 'app/smth1/smth2/Expenses01.xlsx' path and assign to variable `workbook`", "snippet": "workbook = xlsxwriter.Workbook('app/smth1/smth2/Expenses01.xlsx')", "question_id": 22904654 }, { "intent": "How to save Xlsxwriter file in certain path?", "rewritten_intent": "save xlsxwriter file to 'C:/Users/Steven/Documents/demo.xlsx' path", "snippet": "workbook = xlsxwriter.Workbook('C:/Users/Steven/Documents/demo.xlsx')", "question_id": 22904654 }, { "intent": "How to change legend size with matplotlib.pyplot", "rewritten_intent": "change legend size to 'x-small' in upper-left location", "snippet": "pyplot.legend(loc=2, fontsize='x-small')", "question_id": 7125009 }, { "intent": "How to change legend size with matplotlib.pyplot", "rewritten_intent": "change legend font size with matplotlib.pyplot to 6", "snippet": "plot.legend(loc=2, prop={'size': 6})", "question_id": 7125009 }, { "intent": "How do you split a list into evenly sized chunks?", "rewritten_intent": "split list `l` into `n` sized lists", "snippet": "[l[i:i + n] for i in range(0, len(l), n)]", "question_id": 312443 }, { "intent": "How do you split a list into evenly sized chunks?", "rewritten_intent": "split a list `l` into evenly sized chunks `n`", "snippet": "[l[i:i + n] for i in range(0, len(l), n)]", "question_id": 312443 }, { "intent": "How to check if character exists in DataFrame cell", "rewritten_intent": "check if character '-' exists in a dataframe `df` cell 'a'", "snippet": "df['a'].str.contains('-')", "question_id": 39299703 }, { "intent": "Python Regex - Remove special characters but preserve apostraphes", "rewritten_intent": "remove all non -word, -whitespace, or -apostrophe characters from string `doesn't this mean it -technically- works?`", "snippet": "re.sub(\"[^\\\\w' ]\", '', \"doesn't this mean it -technically- works?\")", "question_id": 11403474 }, { "intent": "find all digits between a character in python", "rewritten_intent": "find all digits between two characters `\\xab` and `\\xbb`in a string `text`", "snippet": "print(re.findall('\\\\d+', '\\n'.join(re.findall('\\xab([\\\\s\\\\S]*?)\\xbb', text))))", "question_id": 31650399 }, { "intent": "Use index in pandas to plot data", "rewritten_intent": "plot data of column 'index' versus column 'A' of dataframe `monthly_mean` after resetting its index", "snippet": "monthly_mean.reset_index().plot(x='index', y='A')", "question_id": 20084487 }, { "intent": "How to get data from command line from within a Python program?", "rewritten_intent": "get the output of a subprocess command `echo \"foo\"` in command line", "snippet": "subprocess.check_output('echo \"foo\"', shell=True)", "question_id": 8217613 }, { "intent": "Easy way to convert a unicode list to a list containing python strings?", "rewritten_intent": "Encode each value to 'UTF8' in the list `EmployeeList`", "snippet": "[x.encode('UTF8') for x in EmployeeList]", "question_id": 18272066 }, { "intent": "pandas: combine two columns in a DataFrame", "rewritten_intent": "combine two columns `foo` and `bar` in a pandas data frame", "snippet": "pandas.concat([df['foo'].dropna(), df['bar'].dropna()]).reindex_like(df)", "question_id": 10972410 }, { "intent": "How can I generate a list of consecutive numbers?", "rewritten_intent": "generate a list of consecutive integers from 0 to 8", "snippet": "list(range(9))", "question_id": 29558007 }, { "intent": "How to make a Python string out of non-ascii \"bytes\"", "rewritten_intent": "convert list `myintegers` into a unicode string", "snippet": "\"\"\"\"\"\".join(chr(i) for i in myintegers)", "question_id": 3855093 }, { "intent": "Using inheritance in python", "rewritten_intent": "inherit from class `Executive`", "snippet": "super(Executive, self).__init__(*args)", "question_id": 16128833 }, { "intent": "Removing items from unnamed lists in Python", "rewritten_intent": "Remove the string value `item` from a list of strings `my_sequence`", "snippet": "[item for item in my_sequence if item != 'item']", "question_id": 14961014 }, { "intent": "randomly select an item from a list", "rewritten_intent": "randomly select an item from list `foo`", "snippet": "random.choice(foo)", "question_id": 306400 }, { "intent": "Python Check if all of the following items is in a list", "rewritten_intent": "check if all of the following items in list `['a', 'b']` are in a list `['a', 'b', 'c']`", "snippet": "set(['a', 'b']).issubset(['a', 'b', 'c'])", "question_id": 3931541 }, { "intent": "Python Check if all of the following items is in a list", "rewritten_intent": "Check if all the items in a list `['a', 'b']` exists in another list `l`", "snippet": "set(['a', 'b']).issubset(set(l))", "question_id": 3931541 }, { "intent": "pass a string into subprocess.Popen", "rewritten_intent": "set the stdin of the process 'grep f' to be b'one\\ntwo\\nthree\\nfour\\nfive\\nsix\\n'", "snippet": "p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)\ngrep_stdout = p.communicate(input='one\\ntwo\\nthree\\nfour\\nfive\\nsix\\n')[0]", "question_id": 163542 }, { "intent": "pass a string into subprocess.Popen", "rewritten_intent": "set the stdin of the process 'grep f' to be 'one\\ntwo\\nthree\\nfour\\nfive\\nsix\\n'", "snippet": "p = subprocess.Popen(['grep', 'f'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)\np.stdin.write('one\\ntwo\\nthree\\nfour\\nfive\\nsix\\n')\np.communicate()[0]\np.stdin.close()", "question_id": 163542 }, { "intent": "Most pythonic way to convert a list of tuples", "rewritten_intent": "to convert a list of tuples `list_of_tuples` into list of lists", "snippet": "[list(t) for t in zip(*list_of_tuples)]", "question_id": 18637651 }, { "intent": "Most pythonic way to convert a list of tuples", "rewritten_intent": "group a list `list_of_tuples` of tuples by values", "snippet": "zip(*list_of_tuples)", "question_id": 18637651 }, { "intent": "simple/efficient way to expand a pandas dataframe", "rewritten_intent": "merge pandas dataframe `x` with columns 'a' and 'b' and dataframe `y` with column 'y'", "snippet": "pd.merge(y, x, on='k')[['a', 'b', 'y']]", "question_id": 20504881 }, { "intent": "Splitting string and removing whitespace Python", "rewritten_intent": "Split string with comma (,) and remove whitespace from a string 'my_string'", "snippet": "[item.strip() for item in my_string.split(',')]", "question_id": 21261330 }, { "intent": "Get all object attributes", "rewritten_intent": "Get all object attributes of object `obj`", "snippet": "print((obj.__dict__))", "question_id": 6886493 }, { "intent": "Get all object attributes", "rewritten_intent": "Get all object attributes of an object", "snippet": "dir()", "question_id": 6886493 }, { "intent": "Get all object attributes", "rewritten_intent": "Get all object attributes of an object", "snippet": "dir()", "question_id": 6886493 }, { "intent": "How to center a window with PyGObject", "rewritten_intent": "pygobject center window `window`", "snippet": "window.set_position(Gtk.WindowPosition.CENTER)", "question_id": 16389188 }, { "intent": "how to change the size of the sci notation above the y axis in matplotlib?", "rewritten_intent": "change the size of the sci notation to '30' above the y axis in matplotlib `plt`", "snippet": "plt.rc('font', **{'size': '30'})", "question_id": 14159753 }, { "intent": "Python pandas: check if any value is NaN in DataFrame", "rewritten_intent": "check if datafram `df` has any NaN vlaues", "snippet": "df.isnull().values.any()", "question_id": 29530232 }, { "intent": "Python - use list as function parameters", "rewritten_intent": "unpack the arguments out of list `params` to function `some_func`", "snippet": "some_func(*params)", "question_id": 4979542 }, { "intent": "How to decode encodeURIComponent in GAE (python)?", "rewritten_intent": "decode encodeuricomponent in GAE", "snippet": "urllib.parse.unquote(h.path.encode('utf-8')).decode('utf-8')", "question_id": 9880173 }, { "intent": "Percentage match in pandas Dataframe", "rewritten_intent": "get proportion of rows in dataframe `trace_df` whose values for column `ratio` are greater than 0", "snippet": "(trace_df['ratio'] > 0).mean()", "question_id": 41178532 }, { "intent": "How to convert a tuple to a string in Python?", "rewritten_intent": "convert a set of tuples `queryresult` to a string `emaillist`", "snippet": "emaillist = '\\n'.join(item[0] for item in queryresult)", "question_id": 8704952 }, { "intent": "How to convert a tuple to a string in Python?", "rewritten_intent": "convert a set of tuples `queryresult` to a list of strings", "snippet": "[item[0] for item in queryresult]", "question_id": 8704952 }, { "intent": "How to convert a tuple to a string in Python?", "rewritten_intent": "convert a list of tuples `queryresult` to a string from the first indexes.", "snippet": "emaillist = '\\n'.join([item[0] for item in queryresult])", "question_id": 8704952 }, { "intent": "Python get focused entry name", "rewritten_intent": "get the widget which has currently the focus in tkinter instance `window2`", "snippet": "print(('focus object class:', window2.focus_get().__class__))", "question_id": 27867754 }, { "intent": "How to declare an array in python", "rewritten_intent": "Initialize a list `a` with `10000` items and each item's value `0`", "snippet": "a = [0] * 10000", "question_id": 36113747 }, { "intent": "How can I remove duplicate words in a string with Python?", "rewritten_intent": "Keep only unique words in list of words `words` and join into string", "snippet": "print(' '.join(sorted(set(words), key=words.index)))", "question_id": 7794208 }, { "intent": "How to generate random numbers that are different?", "rewritten_intent": "generate 6 random numbers between 1 and 50", "snippet": "random.sample(range(1, 50), 6)", "question_id": 13628725 }, { "intent": "How to generate random numbers that are different?", "rewritten_intent": "generate six unique random numbers in the range of 1 to 49.", "snippet": "random.sample(range(1, 50), 6)", "question_id": 13628725 }, { "intent": "Dictionary to lowercase in Python", "rewritten_intent": "lowercase keys and values in dictionary `{'My Key': 'My Value'}`", "snippet": "{k.lower(): v.lower() for k, v in list({'My Key': 'My Value'}.items())}", "question_id": 764235 }, { "intent": "Dictionary to lowercase in Python", "rewritten_intent": "lowercase all keys and values in dictionary `{'My Key': 'My Value'}`", "snippet": "dict((k.lower(), v) for k, v in {'My Key': 'My Value'}.items())", "question_id": 764235 }, { "intent": "Dictionary to lowercase in Python", "rewritten_intent": "Convert each key,value pair in a dictionary `{'My Key': 'My Value'}` to lowercase", "snippet": "dict((k.lower(), v.lower()) for k, v in {'My Key': 'My Value'}.items())", "question_id": 764235 }, { "intent": "sorting list of list in python", "rewritten_intent": "sorting the lists in list of lists `data`", "snippet": "[sorted(item) for item in data]", "question_id": 34197047 }, { "intent": "Is there a way to get a list of column names in sqlite?", "rewritten_intent": "SQLite get a list of column names from cursor object `cursor`", "snippet": "names = list(map(lambda x: x[0], cursor.description))", "question_id": 7831371 }, { "intent": "finding out absolute path to a file from python", "rewritten_intent": "get the absolute path of a running python script", "snippet": "os.path.abspath(__file__)", "question_id": 3283306 }, { "intent": "how to sort 2d array by row in python?", "rewritten_intent": "sort 2d array `matrix` by row with index 1", "snippet": "sorted(matrix, key=itemgetter(1))", "question_id": 2173797 }, { "intent": "Finding index of the same elements in a list", "rewritten_intent": "Get all indexes of a letter `e` from a string `word`", "snippet": "[index for index, letter in enumerate(word) if letter == 'e']", "question_id": 7658932 }, { "intent": "How to print container object with unicode-containing values?", "rewritten_intent": "decode utf-8 code `x` into a raw unicode literal", "snippet": "print(str(x).decode('raw_unicode_escape'))", "question_id": 8901996 }, { "intent": "Python regular expressions - how to capture multiple groups from a wildcard expression?", "rewritten_intent": "split string 'abcdefg' into a list of characters", "snippet": "re.findall('\\\\w', 'abcdefg')", "question_id": 464736 }, { "intent": "check whether a file exists", "rewritten_intent": "check whether a file `fname` exists", "snippet": "os.path.isfile(fname)", "question_id": 82831 }, { "intent": "check whether a file exists", "rewritten_intent": "check whether file \"/path/to/file\" exists", "snippet": "my_file = Path('/path/to/file')\nif my_file.is_file():\n pass", "question_id": 82831 }, { "intent": "check whether a file exists", "rewritten_intent": "check whether file `file_path` exists", "snippet": "os.path.exists(file_path)", "question_id": 82831 }, { "intent": "check whether a file exists", "rewritten_intent": "check whether a file \"/etc/password.txt\" exists", "snippet": "print(os.path.isfile('/etc/password.txt'))", "question_id": 82831 }, { "intent": "check whether a file exists", "rewritten_intent": "check whether a file \"/etc\" exists", "snippet": "print(os.path.isfile('/etc'))", "question_id": 82831 }, { "intent": "check whether a file exists", "rewritten_intent": "check whether a path \"/does/not/exist\" exists", "snippet": "print(os.path.exists('/does/not/exist'))", "question_id": 82831 }, { "intent": "check whether a file exists", "rewritten_intent": "check whether a file \"/does/not/exist\" exists", "snippet": "print(os.path.isfile('/does/not/exist'))", "question_id": 82831 }, { "intent": "check whether a file exists", "rewritten_intent": "check whether a path \"/etc\" exists", "snippet": "print(os.path.exists('/etc'))", "question_id": 82831 }, { "intent": "check whether a file exists", "rewritten_intent": "check whether a path \"/etc/password.txt\" exists", "snippet": "print(os.path.exists('/etc/password.txt'))", "question_id": 82831 }, { "intent": "Split Strings with Multiple Delimiters?", "rewritten_intent": "split string \"a;bcd,ef g\" on delimiters ';' and ','", "snippet": "\"\"\"a;bcd,ef g\"\"\".replace(';', ' ').replace(',', ' ').split()", "question_id": 1059559 }, { "intent": "Why can you loop through an implicit tuple in a for loop, but not a comprehension in Python?", "rewritten_intent": "get a list each value `i` in the implicit tuple `range(3)`", "snippet": "list(i for i in range(3))", "question_id": 41127441 }, { "intent": "Pythonically add header to a csv file", "rewritten_intent": "add field names as headers in csv constructor `writer`", "snippet": "writer.writeheader()", "question_id": 20347766 }, { "intent": "How to flatten a tuple in python", "rewritten_intent": "flatten a tuple `l`", "snippet": "[(a, b, c) for a, (b, c) in l]", "question_id": 18500541 }, { "intent": "Python - how to convert int to string represent a 32bit Hex number", "rewritten_intent": "convert 3652458 to string represent a 32bit hex number", "snippet": "\"\"\"0x{0:08X}\"\"\".format(3652458)", "question_id": 7253907 }, { "intent": "How can I convert a Python dictionary to a list of tuples?", "rewritten_intent": "convert a python dictionary `d` to a list of tuples", "snippet": "[(v, k) for k, v in list(d.items())]", "question_id": 674519 }, { "intent": "How can I convert a Python dictionary to a list of tuples?", "rewritten_intent": "convert dictionary of pairs `d` to a list of tuples", "snippet": "[(v, k) for k, v in d.items()]", "question_id": 674519 }, { "intent": "How can I convert a Python dictionary to a list of tuples?", "rewritten_intent": "convert python 2 dictionary `a` to a list of tuples where the value is the first tuple element and the key is the second tuple element", "snippet": "[(v, k) for k, v in a.items()]", "question_id": 674519 }, { "intent": "How can I convert a Python dictionary to a list of tuples?", "rewritten_intent": "convert a python dictionary 'a' to a list of tuples", "snippet": "[(k, v) for k, v in a.items()]", "question_id": 674519 }, { "intent": "What's the easiest way to convert a list of hex byte strings to a list of hex integers?", "rewritten_intent": "convert a list of hex byte strings `['BB', 'A7', 'F6', '9E']` to a list of hex integers", "snippet": "[int(x, 16) for x in ['BB', 'A7', 'F6', '9E']]", "question_id": 2397687 }, { "intent": "What's the easiest way to convert a list of hex byte strings to a list of hex integers?", "rewritten_intent": "convert the elements of list `L` from hex byte strings to hex integers", "snippet": "[int(x, 16) for x in L]", "question_id": 2397687 }, { "intent": "Two values from one input in python?", "rewritten_intent": "assign values to two variables, `var1` and `var2` from user input response to `'Enter two numbers here: ` split on whitespace", "snippet": "var1, var2 = input('Enter two numbers here: ').split()", "question_id": 961263 }, { "intent": "Django filter JSONField list of dicts", "rewritten_intent": "Filter a json from a key-value pair as `{'fixed_key_1': 'foo2'}` in Django", "snippet": "Test.objects.filter(actions__contains=[{'fixed_key_1': 'foo2'}])", "question_id": 34358278 }, { "intent": "Is there a cleaner way to iterate through all binary 4-tuples?", "rewritten_intent": "create a list containing a four elements long tuples of permutations of binary values", "snippet": "itertools.product(list(range(2)), repeat=4)", "question_id": 32292554 }, { "intent": "Python - Get Yesterday's date as a string in YYYY-MM-DD format", "rewritten_intent": "get yesterday's date as a string in `YYYY-MM-DD` format using timedelta", "snippet": "(datetime.now() - timedelta(1)).strftime('%Y-%m-%d')", "question_id": 30483977 }, { "intent": "Python 3: Multiply a vector by a matrix without NumPy", "rewritten_intent": "Get the dot product of matrix `[1,0,0,1,0,0]` and matrix `[[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]]`", "snippet": "np.dot([1, 0, 0, 1, 0, 0], [[0, 1], [1, 1], [1, 0], [1, 0], [1, 1], [0, 1]])", "question_id": 28253102 }, { "intent": "Parse_dates in Pandas", "rewritten_intent": "convert date strings in pandas dataframe column`df['date']` to pandas timestamps using the format '%d%b%Y'", "snippet": "df['date'] = pd.to_datetime(df['date'], format='%d%b%Y')", "question_id": 23797491 }, { "intent": "Importing files from different folder", "rewritten_intent": "Importing file `file` from folder '/path/to/application/app/folder'", "snippet": "sys.path.insert(0, '/path/to/application/app/folder')\nimport file", "question_id": 4383571 }, { "intent": "How can a pandas merge preserve order?", "rewritten_intent": "do a `left` merge of dataframes `x` and `y` on the column `state` and sort by `index`", "snippet": "x.reset_index().merge(y, how='left', on='state', sort=False).sort('index')", "question_id": 20206615 }, { "intent": "How can i create the empty json object in python", "rewritten_intent": "Create a default empty json object if no json is available in request parameter `mydata`", "snippet": "json.loads(request.POST.get('mydata', '{}'))", "question_id": 16436133 }, { "intent": "Slicing a list into a list of sub-lists", "rewritten_intent": "get a list of tuples of every three consecutive items in list `[1, 2, 3, 4, 5, 6, 7, 8, 9]`", "snippet": "list(zip(*((iter([1, 2, 3, 4, 5, 6, 7, 8, 9]),) * 3)))", "question_id": 2231663 }, { "intent": "Slicing a list into a list of sub-lists", "rewritten_intent": "slice list `[1, 2, 3, 4, 5, 6, 7]` into lists of two elements each", "snippet": "list(grouper(2, [1, 2, 3, 4, 5, 6, 7]))", "question_id": 2231663 }, { "intent": "Slicing a list into a list of sub-lists", "rewritten_intent": null, "snippet": "[input[i:i + n] for i in range(0, len(input), n)]", "question_id": 2231663 }, { "intent": "Sorting numbers in string format with Python", "rewritten_intent": "Sort list `keys` based on its elements' dot-seperated numbers", "snippet": "keys.sort(key=lambda x: map(int, x.split('.')))", "question_id": 2597099 }, { "intent": "Sorting numbers in string format with Python", "rewritten_intent": "Sort a list of integers `keys` where each value is in string format", "snippet": "keys.sort(key=lambda x: [int(y) for y in x.split('.')])", "question_id": 2597099 }, { "intent": "numpy with python: convert 3d array to 2d", "rewritten_intent": "convert a 3d array `img` of dimensions 4x2x3 to a 2d array of dimensions 3x8", "snippet": "img.transpose(2, 0, 1).reshape(3, -1)", "question_id": 32838802 }, { "intent": "Replacing few values in a pandas dataframe column with another value", "rewritten_intent": "replacing 'ABC' and 'AB' values in column 'BrandName' of dataframe `df` with 'A'", "snippet": "df['BrandName'].replace(['ABC', 'AB'], 'A')", "question_id": 27060098 }, { "intent": "Replacing few values in a pandas dataframe column with another value", "rewritten_intent": "replace values `['ABC', 'AB']` in a column 'BrandName' of pandas dataframe `df` with another value 'A'", "snippet": "df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')", "question_id": 27060098 }, { "intent": "Pandas: Subtract row mean from each element in row", "rewritten_intent": "Subtract the mean of each row in dataframe `df` from the corresponding row's elements", "snippet": "df.sub(df.mean(axis=1), axis=0)", "question_id": 26081300 }, { "intent": "Python, remove all non-alphabet chars from string", "rewritten_intent": "remove all non-alphabet chars from string `s`", "snippet": "\"\"\"\"\"\".join([i for i in s if i.isalpha()])", "question_id": 22520932 }, { "intent": "How to split a string into integers in Python?", "rewritten_intent": "split a string `s` into integers", "snippet": "l = (int(x) for x in s.split())", "question_id": 6429638 }, { "intent": "How to split a string into integers in Python?", "rewritten_intent": "split a string `42 0` by white spaces.", "snippet": "\"\"\"42 0\"\"\".split()", "question_id": 6429638 }, { "intent": "How to split a string into integers in Python?", "rewritten_intent": null, "snippet": "map(int, '42 0'.split())", "question_id": 6429638 }, { "intent": "Get the indexes of truthy elements of a boolean list as a list/tuple", "rewritten_intent": "get indexes of all true boolean values from a list `bool_list`", "snippet": "[i for i, elem in enumerate(bool_list, 1) if elem]", "question_id": 13076560 }, { "intent": "How to group pandas DataFrame entries by date in a non-unique column", "rewritten_intent": "group dataframe `data` entries by year value of the date in column 'date'", "snippet": "data.groupby(data['date'].map(lambda x: x.year))", "question_id": 11391969 }, { "intent": "Getting the indices of several elements in a NumPy array at once", "rewritten_intent": "Get the indices in array `b` of each element appearing in array `a`", "snippet": "np.in1d(b, a).nonzero()[0]", "question_id": 32191029 }, { "intent": "In Python, how to display current time in readable format", "rewritten_intent": "display current time in readable format", "snippet": "time.strftime('%l:%M%p %z on %b %d, %Y')", "question_id": 3961581 }, { "intent": "Rotate axis text in python matplotlib", "rewritten_intent": "rotate x-axis text labels of plot `ax` 45 degrees", "snippet": "ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)", "question_id": 10998621 }, { "intent": "How does python do string magic?", "rewritten_intent": "append array of strings `['x', 'x', 'x']` into one string", "snippet": "\"\"\"\"\"\".join(['x', 'x', 'x'])", "question_id": 25678689 }, { "intent": "Array indexing in numpy", "rewritten_intent": "retrieve all items in an numpy array 'x' except the item of the index 1", "snippet": "x[(np.arange(x.shape[0]) != 1), :, :]", "question_id": 8712332 }, { "intent": "How do I pull a recurring key from a JSON?", "rewritten_intent": "pull a value with key 'name' from a json object `item`", "snippet": "print(item['name'])", "question_id": 39605640 }, { "intent": "Read a File from redirected stdin with python", "rewritten_intent": "read a file from redirected stdin and save to variable `result`", "snippet": "result = sys.stdin.read()", "question_id": 27318022 }, { "intent": "How to get the content of a Html page in Python", "rewritten_intent": "Get all the texts without tags from beautiful soup object `soup`", "snippet": "\"\"\"\"\"\".join(soup.findAll(text=True))", "question_id": 2416823 }, { "intent": "Extracting all rows from pandas Dataframe that have certain value in a specific column", "rewritten_intent": "extract all rows from dataframe `data` where the value of column 'Value' is True", "snippet": "data[data['Value'] == True]", "question_id": 17424182 }, { "intent": "Removing duplicate characters from a string", "rewritten_intent": "removing duplicate characters from a string variable \"foo\"", "snippet": "\"\"\"\"\"\".join(set(foo))", "question_id": 9841303 }, { "intent": "how to sort by a computed value in django", "rewritten_intent": "sort objects in model `Profile` based on Theirs `reputation` attribute", "snippet": "sorted(Profile.objects.all(), key=lambda p: p.reputation)", "question_id": 930865 }, { "intent": "python pandas flatten a dataframe to a list", "rewritten_intent": "flatten a dataframe df to a list", "snippet": "df.values.flatten()", "question_id": 25440008 }, { "intent": "how do I sort a python list of dictionaries given a list of ids with the desired order?", "rewritten_intent": "sort list `users` using values associated with key 'id' according to elements in list `order`", "snippet": "users.sort(key=lambda x: order.index(x['id']))", "question_id": 17734779 }, { "intent": "how do I sort a python list of dictionaries given a list of ids with the desired order?", "rewritten_intent": "sort a python list of dictionaries `users` by a given list `order` of ids 'id' with the desired order", "snippet": "users.sort(key=lambda x: order.index(x['id']))", "question_id": 17734779 }, { "intent": "Python requests library how to pass Authorization header with single token", "rewritten_intent": "request URI '' and pass authorization token 'TOK:' to the header", "snippet": "r = requests.get('', headers={'Authorization': 'TOK:'})", "question_id": 19069701 }, { "intent": "How do I un-escape a backslash-escaped string in python?", "rewritten_intent": "un-escape a backslash-escaped string in `Hello,\\\\nworld!`", "snippet": "print('\"Hello,\\\\nworld!\"'.decode('string_escape'))", "question_id": 1885181 }, { "intent": "Can I have a non-greedy regex with dotall?", "rewritten_intent": "match regex pattern 'a*?bc*?' on string 'aabcc' with DOTALL enabled", "snippet": "re.findall('a*?bc*?', 'aabcc', re.DOTALL)", "question_id": 9507819 }, { "intent": "python/numpy: how to get 2D array column length?", "rewritten_intent": "get second array column length of array `a`", "snippet": "a.shape[1]", "question_id": 7670226 }, { "intent": "Adding calculated column(s) to a dataframe in pandas", "rewritten_intent": "use operations like max/min within a row to a dataframe 'd' in pandas", "snippet": "d.apply(lambda row: min([row['A'], row['B']]) - row['C'], axis=1)", "question_id": 12376863 }, { "intent": "Count number of occurrences of a given substring in a string", "rewritten_intent": "count number of occurrences of a substring 'ab' in a string \"abcdabcva\"", "snippet": "\"\"\"abcdabcva\"\"\".count('ab')", "question_id": 8899905 }, { "intent": "Get a list of values from a list of dictionaries in python", "rewritten_intent": "get a list of values with key 'key' from a list of dictionaries `l`", "snippet": "[d['key'] for d in l if 'key' in d]", "question_id": 25040875 }, { "intent": "Get a list of values from a list of dictionaries in python", "rewritten_intent": "get a list of values for key 'key' from a list of dictionaries `l`", "snippet": "[d['key'] for d in l]", "question_id": 25040875 }, { "intent": "Get a list of values from a list of dictionaries in python", "rewritten_intent": "get a list of values for key \"key\" from a list of dictionaries in `l`", "snippet": "[d['key'] for d in l]", "question_id": 25040875 }, { "intent": "How to order a list of lists by the first value", "rewritten_intent": "order a list of lists `l1` by the first value", "snippet": "l1.sort(key=lambda x: int(x[0]))", "question_id": 40744328 }, { "intent": "How to order a list of lists by the first value", "rewritten_intent": "order a list of lists `[[1, 'mike'], [1, 'bob']]` by the first value of individual list", "snippet": "sorted([[1, 'mike'], [1, 'bob']])", "question_id": 40744328 }, { "intent": "case sensitive string replacement in Python", "rewritten_intent": "replace a string `Abc` in case sensitive way using maketrans", "snippet": "\"\"\"Abc\"\"\".translate(maketrans('abcABC', 'defDEF'))", "question_id": 3008992 }, { "intent": "python: dictionary to string, custom format?", "rewritten_intent": "dictionary `d` to string, custom format", "snippet": "\"\"\"
\"\"\".join([('%s:: %s' % (key, value)) for key, value in list(d.items())])", "question_id": 8519599 }, { "intent": "how to write a unicode csv in Python 2.7", "rewritten_intent": null, "snippet": "self.writer.writerow([str(s).encode('utf-8') for s in row])", "question_id": 22733642 }, { "intent": "how to clear the screen in python", "rewritten_intent": "clear terminal screen on windows", "snippet": "os.system('cls')", "question_id": 4810537 }, { "intent": "how to clear the screen in python", "rewritten_intent": "clear the terminal screen in Linux", "snippet": "os.system('clear')", "question_id": 4810537 }, { "intent": "In python 2.4, how can I execute external commands with csh instead of bash?", "rewritten_intent": "execute external commands/script `your_own_script` with csh instead of bash", "snippet": "os.system('tcsh your_own_script')", "question_id": 533398 }, { "intent": "In python 2.4, how can I execute external commands with csh instead of bash?", "rewritten_intent": "execute command 'echo $0' in Z shell", "snippet": "os.system(\"zsh -c 'echo $0'\")", "question_id": 533398 }, { "intent": "Updating a list of python dictionaries with a key, value pair from another list", "rewritten_intent": "update a list `l1` dictionaries with a key `count` and value from list `l2`", "snippet": "[dict(d, count=n) for d, n in zip(l1, l2)]", "question_id": 10592674 }, { "intent": "sum each value in a list of tuples", "rewritten_intent": "create a list with the sum of respective elements of the tuples of list `l`", "snippet": "[sum(x) for x in zip(*l)]", "question_id": 14180866 }, { "intent": "sum each value in a list of tuples", "rewritten_intent": "sum each value in a list `l` of tuples", "snippet": "map(sum, zip(*l))", "question_id": 14180866 }, { "intent": "Counting the number of non-NaN elements in a numpy ndarray matrix in Python", "rewritten_intent": "count the number of non-nan elements in a numpy ndarray matrix `data`", "snippet": "np.count_nonzero(~np.isnan(data))", "question_id": 21778118 }, { "intent": "Python: transform a list of lists of tuples", "rewritten_intent": "Convert each list in list `main_list` into a tuple", "snippet": "map(list, zip(*main_list))", "question_id": 31676133 }, { "intent": "Django - taking values from POST request", "rewritten_intent": "django get the value of key 'title' from POST request `request` if exists, else return empty string ''", "snippet": "request.POST.get('title', '')", "question_id": 11336548 }, { "intent": "Check if string ends with one of the strings from a list", "rewritten_intent": "check if string `test.mp3` ends with one of the strings from a tuple `('.mp3', '.avi')`", "snippet": "\"\"\"test.mp3\"\"\".endswith(('.mp3', '.avi'))", "question_id": 18351951 }, { "intent": "Splitting strings in python", "rewritten_intent": "split a string 's' by space while ignoring spaces within square braces and quotes.", "snippet": "re.findall('\\\\[[^\\\\]]*\\\\]|\"[^\"]*\"|\\\\S+', s)", "question_id": 234512 }, { "intent": "Get top biggest values from each column of the pandas.DataFrame", "rewritten_intent": "get biggest 3 values from each column of the pandas dataframe `data`", "snippet": "data.apply(lambda x: sorted(x, 3))", "question_id": 20477190 }, { "intent": "How do I permanently set the current directory to the Desktop in Python?", "rewritten_intent": "permanently set the current directory to the 'C:/Users/Name/Desktop'", "snippet": "os.chdir('C:/Users/Name/Desktop')", "question_id": 30405804 }, { "intent": "getting string between 2 characters in python", "rewritten_intent": "get all characters between two `$` characters in string `string`", "snippet": "re.findall('\\\\$([^$]*)\\\\$', string)", "question_id": 15043326 }, { "intent": "getting string between 2 characters in python", "rewritten_intent": "getting the string between 2 '$' characters in '$sin (x)$ is an function of x'", "snippet": "re.findall('\\\\$(.*?)\\\\$', '$sin (x)$ is an function of x')", "question_id": 15043326 }, { "intent": "how to format date in ISO using python?", "rewritten_intent": "Format a date object `str_data` into iso fomrat", "snippet": "datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()", "question_id": 12772057 }, { "intent": "Selecting specific column in each row from array", "rewritten_intent": "get element at index 0 of first row and element at index 1 of second row in array `A`", "snippet": "A[[0, 1], [0, 1]]", "question_id": 2111163 }, { "intent": "Selecting specific column in each row from array", "rewritten_intent": "subset numpy array `a` by column and row, returning the values from the first row, first column and the second row, second column and the third row, first column.", "snippet": "a[np.arange(3), (0, 1, 0)]", "question_id": 2111163 }, { "intent": "Counting values in dictionary", "rewritten_intent": "Get a list of all keys from dictionary `dictA` where the number of occurrences of value `duck` in that key is more than `1`", "snippet": "[k for k, v in dictA.items() if v.count('duck') > 1]", "question_id": 14743454 }, { "intent": "Sub matrix of a list of lists (without numpy)", "rewritten_intent": "Create sub matrix of a list of lists `[[2, 3, 4], [2, 3, 4], [2, 3, 4]]` (without numpy)", "snippet": "[[2, 3, 4], [2, 3, 4], [2, 3, 4]]", "question_id": 15650538 }, { "intent": "How to call an element in an numpy array?", "rewritten_intent": "get an element at index `[1,1]`in a numpy array `arr`", "snippet": "print(arr[1, 1])", "question_id": 3582601 }, { "intent": "Setting matplotlib colorbar range", "rewritten_intent": "Set colorbar range from `0` to `15` for pyplot object `quadmesh` in matplotlib", "snippet": "quadmesh.set_clim(vmin=0, vmax=15)", "question_id": 15282189 }, { "intent": "read csv into record array in numpy", "rewritten_intent": "read csv file 'my_file.csv' into numpy array", "snippet": "my_data = genfromtxt('my_file.csv', delimiter=',')", "question_id": 3518778 }, { "intent": "read csv into record array in numpy", "rewritten_intent": "read csv file 'myfile.csv' into array", "snippet": "df = pd.read_csv('myfile.csv', sep=',', header=None)", "question_id": 3518778 }, { "intent": "read csv into record array in numpy", "rewritten_intent": "read csv file 'myfile.csv' into array", "snippet": "np.genfromtxt('myfile.csv', delimiter=',')", "question_id": 3518778 }, { "intent": "read csv into record array", "rewritten_intent": "read csv file 'myfile.csv' into array", "snippet": "np.genfromtxt('myfile.csv', delimiter=',', dtype=None)", "question_id": 3518778 }, { "intent": "How do I read the first line of a string?", "rewritten_intent": "read the first line of a string `my_string`", "snippet": "my_string.splitlines()[0]", "question_id": 11833266 }, { "intent": "How do I read the first line of a string?", "rewritten_intent": null, "snippet": "my_string.split('\\n', 1)[0]", "question_id": 11833266 }, { "intent": "How to generate a list from a pandas DataFrame with the column name and column values?", "rewritten_intent": "generate a list from a pandas dataframe `df` with the column name and column values", "snippet": "df.values.tolist()", "question_id": 11811392 }, { "intent": "How to replace repeated instances of a character with a single instance of that character in python", "rewritten_intent": "Replace repeated instances of a character '*' with a single instance in a string 'text'", "snippet": "re.sub('\\\\*\\\\*+', '*', text)", "question_id": 3878555 }, { "intent": "How to replace repeated instances of a character with a single instance of that character in python", "rewritten_intent": "replace repeated instances of \"*\" with a single instance of \"*\"", "snippet": "re.sub('\\\\*+', '*', text)", "question_id": 3878555 }, { "intent": "Multiplying values from two different dictionaries together in Python", "rewritten_intent": "multiply values of dictionary `dict` with their respective values in dictionary `dict2`", "snippet": "dict((k, v * dict2[k]) for k, v in list(dict1.items()) if k in dict2)", "question_id": 15334783 }, { "intent": "Random strings in Python", "rewritten_intent": "Get a random string of length `length`", "snippet": "return ''.join(random.choice(string.lowercase) for i in range(length))", "question_id": 2030053 }, { "intent": "How to count all elements in a nested dictionary?", "rewritten_intent": "Get total number of values in a nested dictionary `food_colors`", "snippet": "sum(len(x) for x in list(food_colors.values()))", "question_id": 4581646 }, { "intent": "How to count all elements in a nested dictionary?", "rewritten_intent": "count all elements in a nested dictionary `food_colors`", "snippet": "sum(len(v) for v in food_colors.values())", "question_id": 4581646 }, { "intent": "How to apply a logical operator to all elements in a python list", "rewritten_intent": "apply logical operator 'AND' to all elements in list `a_list`", "snippet": "all(a_list)", "question_id": 1790520 }, { "intent": "Removing characters from string Python", "rewritten_intent": "removing vowel characters 'aeiouAEIOU' from string `text`", "snippet": "\"\"\"\"\"\".join(c for c in text if c not in 'aeiouAEIOU')", "question_id": 41083229 }, { "intent": "Divide two lists in python", "rewritten_intent": "Divide elements in list `a` from elements at the same index in list `b`", "snippet": "[(x / y) for x, y in zip(a, b)]", "question_id": 16418415 }, { "intent": "Capturing group with findall?", "rewritten_intent": "match regex 'abc(de)fg(123)' on string 'abcdefg123 and again abcdefg123'", "snippet": "re.findall('abc(de)fg(123)', 'abcdefg123 and again abcdefg123')", "question_id": 6018340 }, { "intent": "applying functions to groups in pandas dataframe", "rewritten_intent": "apply function `log2` to the grouped values by 'type' in dataframe `df`", "snippet": "df.groupby('type').apply(lambda x: np.mean(np.log2(x['v'])))", "question_id": 18137341 }, { "intent": "Searching if the values on a list is in the dictionary whose format is key-string, value-list(strings)", "rewritten_intent": "get geys of dictionary `my_dict` that contain any values from list `lst`", "snippet": "[key for key, value in list(my_dict.items()) if set(value).intersection(lst)]", "question_id": 32792874 }, { "intent": "Searching if the values on a list is in the dictionary whose format is key-string, value-list(strings)", "rewritten_intent": "get list of keys in dictionary `my_dict` whose values contain values from list `lst`", "snippet": "[key for item in lst for key, value in list(my_dict.items()) if item in value]", "question_id": 32792874 }, { "intent": "Add tuple to a list of tuples", "rewritten_intent": "Sum elements of tuple `b` to their respective elements of each tuple in list `a`", "snippet": "c = [[(i + j) for i, j in zip(e, b)] for e in a]", "question_id": 40313203 }, { "intent": "Python: Get relative path from comparing two absolute paths", "rewritten_intent": "get the common prefix from comparing two absolute paths '/usr/var' and '/usr/var2/log'", "snippet": "os.path.commonprefix(['/usr/var', '/usr/var2/log'])", "question_id": 7287996 }, { "intent": "Python: Get relative path from comparing two absolute paths", "rewritten_intent": "get relative path of path '/usr/var' regarding path '/usr/var/log/'", "snippet": "print(os.path.relpath('/usr/var/log/', '/usr/var'))", "question_id": 7287996 }, { "intent": "filtering grouped df in pandas", "rewritten_intent": "filter dataframe `grouped` where the length of each group `x` is bigger than 1", "snippet": "grouped.filter(lambda x: len(x) > 1)", "question_id": 13167391 }, { "intent": "Python: sorting a dictionary of lists", "rewritten_intent": "sort dictionary of lists `myDict` by the third item in each list", "snippet": "sorted(list(myDict.items()), key=lambda e: e[1][2])", "question_id": 1217251 }, { "intent": "What is the most pythonic way to avoid specifying the same value in a string", "rewritten_intent": "Format string `hello {name}, how are you {name}, welcome {name}` to be interspersed by `name` three times, specifying the value as `john` only once", "snippet": "\"\"\"hello {name}, how are you {name}, welcome {name}\"\"\".format(name='john')", "question_id": 11921649 }, { "intent": "How to reorder indexed rows based on a list in Pandas data frame", "rewritten_intent": "reorder indexed rows `['Z', 'C', 'A']` based on a list in pandas data frame `df`", "snippet": "df.reindex(['Z', 'C', 'A'])", "question_id": 30009948 }, { "intent": "determine if a list contains other lists", "rewritten_intent": "check if any values in a list `input_list` is a list", "snippet": "any(isinstance(el, list) for el in input_list)", "question_id": 5251663 }, { "intent": "get the size of a list", "rewritten_intent": "get the size of list `items`", "snippet": "len(items)", "question_id": 1712227 }, { "intent": "get the size of a list", "rewritten_intent": "get the size of a list `[1,2,3]`", "snippet": "len([1, 2, 3])", "question_id": 1712227 }, { "intent": "get the size of a list", "rewritten_intent": "get the size of object `items`", "snippet": "items.__len__()", "question_id": 1712227 }, { "intent": "get the size of a list", "rewritten_intent": "function to get the size of object", "snippet": "len()", "question_id": 1712227 }, { "intent": "get the size of a list", "rewritten_intent": "get the size of list `s`", "snippet": "len(s)", "question_id": 1712227 }, { "intent": "Fastest way to sort each row in a pandas dataframe", "rewritten_intent": "sort each row in a pandas dataframe `df` in descending order", "snippet": "df.sort(axis=1, ascending=False)", "question_id": 25817930 }, { "intent": "Fastest way to sort each row in a pandas dataframe", "rewritten_intent": null, "snippet": "df.sort(df.columns, axis=1, ascending=False)", "question_id": 25817930 }, { "intent": "Pandas DataFrame Groupby two columns and get counts", "rewritten_intent": "get count of rows in each series grouped by column 'col5' and column 'col2' of dataframe `df`", "snippet": "df.groupby(['col5', 'col2']).size().groupby(level=1).max()", "question_id": 17679089 }, { "intent": "How would I check a string for a certain letter in Python?", "rewritten_intent": "check if string 'x' is in list `['x', 'd', 'a', 's', 'd', 's']`", "snippet": "'x' in ['x', 'd', 'a', 's', 'd', 's']", "question_id": 4877844 }, { "intent": "Delete a dictionary item if the key exists", "rewritten_intent": "Delete an item with key \"key\" from `mydict`", "snippet": "mydict.pop('key', None)", "question_id": 15411107 }, { "intent": "Delete a dictionary item if the key exists", "rewritten_intent": "Delete an item with key `key` from `mydict`", "snippet": "del mydict[key]", "question_id": 15411107 }, { "intent": "Delete a dictionary item if the key exists", "rewritten_intent": "Delete an item with key `key` from `mydict`", "snippet": "try:\n del mydict[key]\nexcept KeyError:\n pass\ntry:\n del mydict[key]\nexcept KeyError:\n pass", "question_id": 15411107 }, { "intent": "Multiple positional arguments with Python and argparse", "rewritten_intent": "specify multiple positional arguments with argparse", "snippet": "parser.add_argument('input', nargs='+')", "question_id": 5373474 }, { "intent": "How to avoid line color repetition in matplotlib.pyplot?", "rewritten_intent": "Plot using the color code `#112233` in matplotlib pyplot", "snippet": "pyplot.plot(x, y, color='#112233')", "question_id": 6027690 }, { "intent": "Strip HTML from strings in Python", "rewritten_intent": "strip html from strings", "snippet": "re.sub('<[^<]+?>', '', text)", "question_id": 753052 }, { "intent": "Align numpy array according to another array", "rewritten_intent": "align values in array `b` to the order of corresponding values in array `a`", "snippet": "a[np.in1d(a, b)]", "question_id": 41923906 }, { "intent": "how to split a string on the first instance of delimiter in python", "rewritten_intent": "split string \"jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,\" on the first occurrence of delimiter '='", "snippet": "\"\"\"jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,\"\"\".split('=', 1)", "question_id": 11009155 }, { "intent": "Control a print format when printing a list in Python", "rewritten_intent": "print numbers in list `list` with precision of 3 decimal places", "snippet": "print('[%s]' % ', '.join('%.3f' % val for val in list))", "question_id": 7351270 }, { "intent": "Control a print format when printing a list in Python", "rewritten_intent": "format print output of list of floats `l` to print only up to 3 decimal points", "snippet": "print('[' + ', '.join('%5.3f' % v for v in l) + ']')", "question_id": 7351270 }, { "intent": "Control a print format when printing a list in Python", "rewritten_intent": "print a list of floating numbers `l` using string formatting", "snippet": "print([('%5.3f' % val) for val in l])", "question_id": 7351270 }, { "intent": "How to move to one folder back in python", "rewritten_intent": "Change the current directory one level up", "snippet": "os.chdir('..')", "question_id": 12280143 }, { "intent": "Convert Unicode to UTF-8 Python", "rewritten_intent": "print a unicode string `text`", "snippet": "print(text.encode('windows-1252'))", "question_id": 6740865 }, { "intent": "How can I convert a binary to a float number", "rewritten_intent": "convert string representation `s2` of binary string rep of integer to floating point number", "snippet": "struct.unpack('d', struct.pack('Q', int(s2, 0)))[0]", "question_id": 8751653 }, { "intent": "How can I convert a binary to a float number", "rewritten_intent": "convert a binary '-0b1110' to a float number", "snippet": "float(int('-0b1110', 0))", "question_id": 8751653 }, { "intent": "How can I convert a binary to a float number", "rewritten_intent": "convert a binary `b8` to a float number", "snippet": "struct.unpack('d', b8)[0]", "question_id": 8751653 }, { "intent": "Plotting categorical data with pandas and matplotlib", "rewritten_intent": "plot a bar graph from the column 'color' in the DataFrame 'df'", "snippet": "df.colour.value_counts().plot(kind='bar')", "question_id": 31029560 }, { "intent": "Plotting categorical data with pandas and matplotlib", "rewritten_intent": "plot categorical data in series `df` with kind `bar` using pandas and matplotlib", "snippet": "df.groupby('colour').size().plot(kind='bar')", "question_id": 31029560 }, { "intent": "Read lines containing integers from a file in Python?", "rewritten_intent": "strip and split each line `line` on white spaces", "snippet": "line.strip().split(' ')", "question_id": 11354544 }, { "intent": "Pandas how to apply multiple functions to dataframe", "rewritten_intent": "apply functions `mean` and `std` to each column in dataframe `df`", "snippet": "df.groupby(lambda idx: 0).agg(['mean', 'std'])", "question_id": 22128218 }, { "intent": "sorting dictionary by numeric value", "rewritten_intent": "sort dictionary `tag_weight` in reverse order by values cast to integers", "snippet": "sorted(list(tag_weight.items()), key=lambda x: int(x[1]), reverse=True)", "question_id": 40208429 }, { "intent": "How do I find the largest integer less than x?", "rewritten_intent": "find the largest integer less than `x`", "snippet": "int(math.ceil(x)) - 1", "question_id": 27758657 }, { "intent": "check if the string is empty", "rewritten_intent": "check if the string `myString` is empty", "snippet": "if (not myString):\n pass", "question_id": 9573244 }, { "intent": "Most elegant way to check if the string is empty", "rewritten_intent": "check if string `some_string` is empty", "snippet": "if (not some_string):\n pass", "question_id": 9573244 }, { "intent": "Most elegant way to check if the string is empty", "rewritten_intent": "check if string `my_string` is empty", "snippet": "if (not my_string):\n pass", "question_id": 9573244 }, { "intent": "check if the string is empty", "rewritten_intent": "check if string `my_string` is empty", "snippet": "if some_string:\n pass", "question_id": 9573244 }, { "intent": "iterate over a dictionary in sorted order", "rewritten_intent": "iterate over a dictionary `d` in sorted order", "snippet": "it = iter(sorted(d.items()))", "question_id": 364519 }, { "intent": "iterate over a dictionary in sorted order", "rewritten_intent": "iterate over a dictionary `d` in sorted order", "snippet": "for (key, value) in sorted(d.items()):\n pass", "question_id": 364519 }, { "intent": "iterate over a dictionary in sorted order", "rewritten_intent": "iterate over a dictionary `dict` in sorted order", "snippet": "return sorted(dict.items())", "question_id": 364519 }, { "intent": "iterate over a dictionary in sorted order", "rewritten_intent": "iterate over a dictionary `dict` in sorted order", "snippet": "return iter(sorted(dict.items()))", "question_id": 364519 }, { "intent": "iterate over a dictionary in sorted order", "rewritten_intent": "iterate over a dictionary `foo` in sorted order", "snippet": "for (k, v) in sorted(foo.items()):\n pass", "question_id": 364519 }, { "intent": "iterate over a dictionary in sorted order", "rewritten_intent": "iterate over a dictionary `foo` sorted by the key", "snippet": "for k in sorted(foo.keys()):\n pass", "question_id": 364519 }, { "intent": "finding the last occurrence of an item in a list python", "rewritten_intent": "assign the index of the last occurence of `x` in list `s` to the variable `last`", "snippet": "last = len(s) - s[::-1].index(x) - 1", "question_id": 34438901 }, { "intent": "convert list to string", "rewritten_intent": "concatenating values in `list1` to a string", "snippet": "str1 = ''.join(list1)", "question_id": 5618878 }, { "intent": "convert list to string", "rewritten_intent": "concatenating values in list `L` to a string, separate by space", "snippet": "' '.join((str(x) for x in L))", "question_id": 5618878 }, { "intent": "convert list to string", "rewritten_intent": "concatenating values in `list1` to a string", "snippet": "str1 = ''.join((str(e) for e in list1))", "question_id": 5618878 }, { "intent": "convert list to string", "rewritten_intent": "concatenating values in list `L` to a string", "snippet": "makeitastring = ''.join(map(str, L))", "question_id": 5618878 }, { "intent": "remove None value from a list without removing the 0 value", "rewritten_intent": "remove None value from list `L`", "snippet": "[x for x in L if x is not None]", "question_id": 16096754 }, { "intent": "How do I select a random element from an array in Python?", "rewritten_intent": "select a random element from array `[1, 2, 3]`", "snippet": "random.choice([1, 2, 3])", "question_id": 1058712 }, { "intent": "Creating a 2d matrix in python", "rewritten_intent": "creating a 5x6 matrix filled with `None` and save it as `x`", "snippet": "x = [[None for _ in range(5)] for _ in range(6)]", "question_id": 4230000 }, { "intent": "Numpy: Get random set of rows from 2D array", "rewritten_intent": "create a new 2D array with 2 random rows from array `A`", "snippet": "A[(np.random.choice(A.shape[0], 2, replace=False)), :]", "question_id": 14262654 }, { "intent": "Numpy: Get random set of rows from 2D array", "rewritten_intent": "create a new 2 dimensional array containing two random rows from array `A`", "snippet": "A[(np.random.randint(A.shape[0], size=2)), :]", "question_id": 14262654 }, { "intent": "Combining rows in pandas", "rewritten_intent": "combining rows in pandas by adding their values", "snippet": "df.groupby(df.index).sum()", "question_id": 17438906 }, { "intent": "Parsing XML with namespace in Python via 'ElementTree'", "rewritten_intent": "find all `owl:Class` tags by parsing xml with namespace", "snippet": "root.findall('{http://www.w3.org/2002/07/owl#}Class')", "question_id": 14853243 }, { "intent": "How do I generate a random string (of length X, a-z only) in Python?", "rewritten_intent": "generate a random string of length `x` containing lower cased ASCII letters", "snippet": "\"\"\"\"\"\".join(random.choice(string.lowercase) for x in range(X))", "question_id": 1957273 }, { "intent": "Python cant find module in the same folder", "rewritten_intent": "add a path `/path/to/2014_07_13_test` to system path", "snippet": "sys.path.append('/path/to/2014_07_13_test')", "question_id": 24722212 }, { "intent": "round number to nearest integer", "rewritten_intent": "round number `x` to nearest integer", "snippet": "int(round(x))", "question_id": 31818050 }, { "intent": "round number to nearest integer", "rewritten_intent": "round number `h` to nearest integer", "snippet": "h = int(round(h))", "question_id": 31818050 }, { "intent": "round number to nearest integer", "rewritten_intent": "round number 32.268907563 up to 3 decimal points", "snippet": "round(32.268907563, 3)", "question_id": 31818050 }, { "intent": "round number to nearest integer", "rewritten_intent": "round number `value` up to `significantDigit` decimal places", "snippet": "round(value, significantDigit)", "question_id": 31818050 }, { "intent": "round number to nearest integer", "rewritten_intent": "round number 1.0005 up to 3 decimal places", "snippet": "round(1.0005, 3)", "question_id": 31818050 }, { "intent": "round number to nearest integer", "rewritten_intent": "round number 2.0005 up to 3 decimal places", "snippet": "round(2.0005, 3)", "question_id": 31818050 }, { "intent": "round number to nearest integer", "rewritten_intent": "round number 3.0005 up to 3 decimal places", "snippet": "round(3.0005, 3)", "question_id": 31818050 }, { "intent": "round number to nearest integer", "rewritten_intent": "round number 4.0005 up to 3 decimal places", "snippet": "round(4.0005, 3)", "question_id": 31818050 }, { "intent": "round number to nearest integer", "rewritten_intent": "round number 8.005 up to 2 decimal places", "snippet": "round(8.005, 2)", "question_id": 31818050 }, { "intent": "round number to nearest integer", "rewritten_intent": "round number 7.005 up to 2 decimal places", "snippet": "round(7.005, 2)", "question_id": 31818050 }, { "intent": "round number to nearest integer", "rewritten_intent": "round number 6.005 up to 2 decimal places", "snippet": "round(6.005, 2)", "question_id": 31818050 }, { "intent": "round number to nearest integer", "rewritten_intent": "round number 1.005 up to 2 decimal places", "snippet": "round(1.005, 2)", "question_id": 31818050 }, { "intent": "Pandas - FillNa with another column", "rewritten_intent": "fill missing value in one column 'Cat1' with the value of another column 'Cat2'", "snippet": "df['Cat1'].fillna(df['Cat2'])", "question_id": 30357276 }, { "intent": "Python: Logging TypeError: not all arguments converted during string formatting", "rewritten_intent": "convert the argument `date` with string formatting in logging", "snippet": "logging.info('date=%s', date)", "question_id": 12843099 }, { "intent": "Python: Logging TypeError: not all arguments converted during string formatting", "rewritten_intent": "Log message of level 'info' with value of `date` in the message", "snippet": "logging.info('date={}'.format(date))", "question_id": 12843099 }, { "intent": "In dictionary, converting the value from string to integer", "rewritten_intent": "convert values in dictionary `d` into integers", "snippet": "{k: int(v) for k, v in d.items()}", "question_id": 9224385 }, { "intent": "How can I add the corresponding elements of several lists of numbers?", "rewritten_intent": "sum elements at the same index of each list in list `lists`", "snippet": "map(sum, zip(*lists))", "question_id": 11280536 }, { "intent": "Python: How to convert a string containing hex bytes to a hex string", "rewritten_intent": "Convert a string `s` containing hex bytes to a hex string", "snippet": "s.decode('hex')", "question_id": 10824319 }, { "intent": "Python: How to convert a string containing hex bytes to a hex string", "rewritten_intent": "convert a string `s` containing hex bytes to a hex string", "snippet": "binascii.a2b_hex(s)", "question_id": 10824319 }, { "intent": "MITM proxy over SSL hangs on wrap_socket with client", "rewritten_intent": "send data 'HTTP/1.0 200 OK\\r\\n\\r\\n' to socket `connection`", "snippet": "connection.send('HTTP/1.0 200 established\\r\\n\\r\\n')", "question_id": 40851413 }, { "intent": "MITM proxy over SSL hangs on wrap_socket with client", "rewritten_intent": "send data 'HTTP/1.0 200 OK\\r\\n\\r\\n' to socket `connection`", "snippet": "connection.send('HTTP/1.0 200 OK\\r\\n\\r\\n')", "question_id": 40851413 }, { "intent": "Set value for particular cell in pandas DataFrame", "rewritten_intent": "set the value of cell `['x']['C']` equal to 10 in dataframe `df`", "snippet": "df['x']['C'] = 10", "question_id": 13842088 }, { "intent": "Norm along row in pandas", "rewritten_intent": "normalize the dataframe `df` along the rows", "snippet": "np.sqrt(np.square(df).sum(axis=1))", "question_id": 18524112 }, { "intent": "How do I remove identical items from a list and sort it in Python?", "rewritten_intent": "remove identical items from list `my_list` and sort it alphabetically", "snippet": "sorted(set(my_list))", "question_id": 22741068 }, { "intent": "Python Finding Index of Maximum in List", "rewritten_intent": "find the index of the element with the maximum value from a list 'a'.", "snippet": "max(enumerate(a), key=lambda x: x[1])[0]", "question_id": 11530799 }, { "intent": "Python Accessing Values in A List of Dictionaries", "rewritten_intent": "create a list where each element is a value of the key 'Name' for each dictionary `d` in the list `thisismylist`", "snippet": "[d['Name'] for d in thisismylist]", "question_id": 17117912 }, { "intent": "Python Accessing Values in A List of Dictionaries", "rewritten_intent": "create a list of tuples with the values of keys 'Name' and 'Age' from each dictionary `d` in the list `thisismylist`", "snippet": "[(d['Name'], d['Age']) for d in thisismylist]", "question_id": 17117912 }, { "intent": "How to grab one random item from a database in Django/postgreSQL?", "rewritten_intent": "grab one random item from a database `model` in django/postgresql", "snippet": "model.objects.all().order_by('?')[0]", "question_id": 9354127 }, { "intent": "Run a python script from another python script, passing in args", "rewritten_intent": "run python script 'script2.py' from another python script, passing in 1 as an argument", "snippet": "os.system('script2.py 1')", "question_id": 3781851 }, { "intent": "Python Regex for hyphenated words", "rewritten_intent": "python regex for hyphenated words in `text`", "snippet": "re.findall('\\\\w+(?:-\\\\w+)+', text)", "question_id": 8383213 }, { "intent": "Create variable key/value pairs with argparse (python)", "rewritten_intent": "create variable key/value pairs with argparse", "snippet": "parser.add_argument('--conf', nargs=2, action='append')", "question_id": 27146262 }, { "intent": "How do you pick \"x\" number of unique numbers from a list in Python?", "rewritten_intent": "Get `3` unique items from a list", "snippet": "random.sample(list(range(1, 16)), 3)", "question_id": 6494508 }, { "intent": "Sort a list of strings based on regular expression match or something similar", "rewritten_intent": "sort list `strings` in alphabetical order based on the letter after percent character `%` in each element", "snippet": "strings.sort(key=lambda str: re.sub('.*%(.).*', '\\\\1', str))", "question_id": 1082413 }, { "intent": "Sort a list of strings based on regular expression match or something similar", "rewritten_intent": "sort a list of strings `strings` based on regex match", "snippet": "strings.sort(key=lambda str: re.sub('.*%', '', str))", "question_id": 1082413 }, { "intent": "Appending to 2D lists in Python", "rewritten_intent": "Create list `listy` containing 3 empty lists", "snippet": "listy = [[] for i in range(3)]", "question_id": 7745562 }, { "intent": "Sort NumPy float array column by column", "rewritten_intent": "sort numpy float array `A` column by column", "snippet": "A = np.array(sorted(A, key=tuple))", "question_id": 12496531 }, { "intent": "Python list comprehension for loops", "rewritten_intent": "Get a list from two strings `12345` and `ab` with values as each character concatenated", "snippet": "[(x + y) for x in '12345' for y in 'ab']", "question_id": 18649884 }, { "intent": "Trimming a string", "rewritten_intent": "trim string \" Hello \"", "snippet": "' Hello '.strip()", "question_id": 761804 }, { "intent": "Trimming a string", "rewritten_intent": "trim string `myString `", "snippet": "myString.strip()", "question_id": 761804 }, { "intent": "Trimming a string", "rewritten_intent": "Trimming a string \" Hello \"", "snippet": "' Hello '.strip()", "question_id": 761804 }, { "intent": "Trimming a string", "rewritten_intent": "Trimming a string \" Hello\"", "snippet": "' Hello'.strip()", "question_id": 761804 }, { "intent": "Trimming a string", "rewritten_intent": "Trimming a string \"Bob has a cat\"", "snippet": "'Bob has a cat'.strip()", "question_id": 761804 }, { "intent": "Trimming a string", "rewritten_intent": "Trimming a string \" Hello \"", "snippet": "' Hello '.strip()", "question_id": 761804 }, { "intent": "Trimming a string", "rewritten_intent": "Trimming a string `str`", "snippet": "str.strip()", "question_id": 761804 }, { "intent": "Trimming a string", "rewritten_intent": "Trimming \"\\n\" from string `myString`", "snippet": "myString.strip('\\n')", "question_id": 761804 }, { "intent": "Trimming a string", "rewritten_intent": "left trimming \"\\n\\r\" from string `myString`", "snippet": "myString.lstrip('\\n\\r')", "question_id": 761804 }, { "intent": "Trimming a string", "rewritten_intent": "right trimming \"\\n\\t\" from string `myString`", "snippet": "myString.rstrip('\\n\\t')", "question_id": 761804 }, { "intent": "Trimming a string", "rewritten_intent": "Trimming a string \" Hello\\n\" by space", "snippet": "' Hello\\n'.strip(' ')", "question_id": 761804 }, { "intent": "Sort a list of tuples depending on two elements", "rewritten_intent": "sort a list of tuples 'unsorted' based on two elements, second and third", "snippet": "sorted(unsorted, key=lambda element: (element[1], element[2]))", "question_id": 9376384 }, { "intent": "Python, Encoding output to UTF-8", "rewritten_intent": "decode string `content` to UTF-8 code", "snippet": "print(content.decode('utf8'))", "question_id": 17577727 }, { "intent": "How do I vectorize this loop in numpy?", "rewritten_intent": "find the index of the maximum value in the array `arr` where the boolean condition in array `cond` is true", "snippet": "np.ma.array(np.tile(arr, 2).reshape(2, 3), mask=~cond).argmax(axis=1)", "question_id": 31767173 }, { "intent": "How to convert efficiently a dataframe column of string type into datetime in Python?", "rewritten_intent": "convert a dataframe `df`'s column `ID` into datetime, after removing the first and last 3 letters", "snippet": "pd.to_datetime(df.ID.str[1:-3])", "question_id": 42100344 }, { "intent": "How to gracefully fallback to `NaN` value while reading integers from a CSV with Pandas?", "rewritten_intent": "read CSV file 'my.csv' into a dataframe `df` with datatype of float for column 'my_column' considering character 'n/a' as NaN value", "snippet": "df = pd.read_csv('my.csv', dtype={'my_column': np.float64}, na_values=['n/a'])", "question_id": 30190459 }, { "intent": "How to gracefully fallback to `NaN` value while reading integers from a CSV with Pandas?", "rewritten_intent": "convert nan values to \u2018n/a\u2019 while reading rows from a csv `read_csv` with pandas", "snippet": "df = pd.read_csv('my.csv', na_values=['n/a'])", "question_id": 30190459 }, { "intent": "All combinations of a list of lists", "rewritten_intent": "create a list containing all cartesian products of elements in list `a`", "snippet": "list(itertools.product(*a))", "question_id": 798854 }, { "intent": "How to extract all UPPER from a string? Python", "rewritten_intent": "remove uppercased characters in string `s`", "snippet": "re.sub('[^A-Z]', '', s)", "question_id": 15886340 }, { "intent": "Get date from ISO week number in Python", "rewritten_intent": "convert string '2011221' into a DateTime object using format '%Y%W%w'", "snippet": "datetime.strptime('2011221', '%Y%W%w')", "question_id": 5882405 }, { "intent": "How to read a \"C source, ISO-8859 text\"", "rewritten_intent": "read file 'myfile' using encoding 'iso-8859-1'", "snippet": "codecs.open('myfile', 'r', 'iso-8859-1').read()", "question_id": 16883447 }, { "intent": "List Comprehensions in Python : efficient selection in a list", "rewritten_intent": "create a list containing elements from list `list` that are predicate to function `f`", "snippet": "[f(x) for x in list]", "question_id": 1222677 }, { "intent": "Regex matching 5-digit substrings not enclosed with digits", "rewritten_intent": "regex matching 5-digit substrings not enclosed with digits in `s`", "snippet": "re.findall('(? 10]", "question_id": 2655956 }, { "intent": "python: how to convert currency to decimal?", "rewritten_intent": "convert currency string `dollars` to decimal `cents_int`", "snippet": "cents_int = int(round(float(dollars.strip('$')) * 100))", "question_id": 3887469 }, { "intent": "Remove final characters from string recursively - What's the best way to do this?", "rewritten_intent": "remove letters from string `example_line` if the letter exist in list `bad_chars`", "snippet": "\"\"\"\"\"\".join(dropwhile(lambda x: x in bad_chars, example_line[::-1]))[::-1]", "question_id": 39532974 }, { "intent": "Creating an empty list", "rewritten_intent": "Creating an empty list `l`", "snippet": "l = []", "question_id": 2972212 }, { "intent": "Creating an empty list", "rewritten_intent": "Creating an empty list `l`", "snippet": "l = list()", "question_id": 2972212 }, { "intent": "Creating an empty list", "rewritten_intent": "Creating an empty list", "snippet": "list()", "question_id": 2972212 }, { "intent": "Creating an empty list", "rewritten_intent": "Creating an empty list", "snippet": "[]", "question_id": 2972212 }, { "intent": "How to properly quit a program in python", "rewritten_intent": "properly quit a program", "snippet": "sys.exit(0)", "question_id": 13022385 }, { "intent": "Add string in a certain position in Python", "rewritten_intent": "add string `-` in `4th` position of a string `s`", "snippet": "s[:4] + '-' + s[4:]", "question_id": 5254445 }, { "intent": "Python : how to append new elements in a list of list?", "rewritten_intent": "append 3 lists in one list", "snippet": "[[] for i in range(3)]", "question_id": 11219949 }, { "intent": "Python : how to append new elements in a list of list?", "rewritten_intent": "Initialize a list of empty lists `a` of size 3", "snippet": "a = [[] for i in range(3)]", "question_id": 11219949 }, { "intent": "Changing the referrer URL in python requests", "rewritten_intent": "request URL `url` using http header `{'referer': my_referer}`", "snippet": "requests.get(url, headers={'referer': my_referer})", "question_id": 20837786 }, { "intent": "Python, Matplotlib, subplot: How to set the axis range?", "rewritten_intent": "set the y axis range to `0, 1000` in subplot using pylab", "snippet": "pylab.ylim([0, 1000])", "question_id": 2849286 }, { "intent": "Pandas convert a column of list to dummies", "rewritten_intent": "convert a column of list in series `s` to dummies", "snippet": "pd.get_dummies(s.apply(pd.Series).stack()).sum(level=0)", "question_id": 29034928 }, { "intent": "Finding the largest delta between two integers in a list in python", "rewritten_intent": null, "snippet": "max(abs(x - y) for x, y in zip(values[1:], values[:-1]))", "question_id": 3428769 }, { "intent": "How to convert hex string to integer in Python?", "rewritten_intent": "convert a hex string `x` to string", "snippet": "y = str(int(x, 16))", "question_id": 2636755 }, { "intent": "check if a string is a number (float)", "rewritten_intent": "check if string `a` is an integer", "snippet": "a.isdigit()", "question_id": 354038 }, { "intent": "check if a string is a number", "rewritten_intent": "function to check if a string is a number", "snippet": "isdigit()", "question_id": 354038 }, { "intent": "check if a string is a number", "rewritten_intent": "check if string `b` is a number", "snippet": "b.isdigit()", "question_id": 354038 }, { "intent": "pandas.read_csv: how to skip comment lines", "rewritten_intent": "pandas read comma-separated CSV file `s` and skip commented lines starting with '#'", "snippet": "pd.read_csv(StringIO(s), sep=',', comment='#')", "question_id": 18366797 }, { "intent": "Pandas: how to change all the values of a column?", "rewritten_intent": "pandas: change all the values of a column 'Date' into \"int(str(x)[-4:])\"", "snippet": "df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))", "question_id": 12604909 }, { "intent": "sum a list of numbers in Python", "rewritten_intent": "sum a list of numbers `list_of_nums`", "snippet": "sum(list_of_nums)", "question_id": 4362586 }, { "intent": "how to get the index of dictionary with the highest value in a list of dictionary", "rewritten_intent": "Get an item from a list of dictionary `lst` which has maximum value in the key `score` using lambda function", "snippet": "max(lst, key=lambda x: x['score'])", "question_id": 6561653 }, { "intent": "Get data from the meta tags using BeautifulSoup", "rewritten_intent": "BeautifulSoup find all tags with attribute 'name' equal to 'description'", "snippet": "soup.findAll(attrs={'name': 'description'})", "question_id": 3774571 }, { "intent": "Python: how to get rid of spaces in str(dict)?", "rewritten_intent": "remove all spaces from a string converted from dictionary `{'a': 1, 'b': 'as df'}`", "snippet": "str({'a': 1, 'b': 'as df'}).replace(': ', ':').replace(', ', ',')", "question_id": 39268928 }, { "intent": "Python: how to get rid of spaces in str(dict)?", "rewritten_intent": "convert dictionary `dict` into a string formatted object", "snippet": "'{' + ','.join('{0!r}:{1!r}'.format(*x) for x in list(dct.items())) + '}'", "question_id": 39268928 }, { "intent": "Python- insert a character into a string", "rewritten_intent": "concatenate items from list `parts` into a string starting from the second element", "snippet": "\"\"\"\"\"\".join(parts[1:])", "question_id": 13655392 }, { "intent": "Python- insert a character into a string", "rewritten_intent": "insert a character ',' into a string in front of '+' character in second part of the string", "snippet": "\"\"\",+\"\"\".join(c.rsplit('+', 1))", "question_id": 13655392 }, { "intent": "How do I delete a row in a numpy array which contains a zero?", "rewritten_intent": "delete all rows in a numpy array `a` where any value in a row is zero `0`", "snippet": "a[np.all(a != 0, axis=1)]", "question_id": 18397805 }, { "intent": "Extracting only characters from a string in Python", "rewritten_intent": "extract only alphabetic characters from a string `your string`", "snippet": "\"\"\" \"\"\".join(re.split('[^a-zA-Z]*', 'your string'))", "question_id": 8199398 }, { "intent": "Extracting only characters from a string in Python", "rewritten_intent": "Extract only characters from a string as a list", "snippet": "re.split('[^a-zA-Z]*', 'your string')", "question_id": 8199398 }, { "intent": "Create Union of All Values Contained in Multiple Lists", "rewritten_intent": "get the union set from list of lists `results_list`", "snippet": "results_union = set().union(*results_list)", "question_id": 2151517 }, { "intent": "Create Union of All Values Contained in Multiple Lists", "rewritten_intent": "get the union of values in list of lists `result_list`", "snippet": "return list(set(itertools.chain(*result_list)))", "question_id": 2151517 }, { "intent": "python: check if an numpy array contains any element of another array", "rewritten_intent": "check if a numpy array `a1` contains any element of another array `a2`", "snippet": "np.any(np.in1d(a1, a2))", "question_id": 36190533 }, { "intent": "Removing control characters from a string in python", "rewritten_intent": "removing control characters from a string `s`", "snippet": "return ''.join(ch for ch in s if unicodedata.category(ch)[0] != 'C')", "question_id": 4324790 }, { "intent": "How to compare two lists in python", "rewritten_intent": "Compare if each value in list `a` is less than respective index value in list `b`", "snippet": "all(i < j for i, j in zip(a, b))", "question_id": 28767642 }, { "intent": "python selenium click on button", "rewritten_intent": "python selenium click on button '.button.c_button.s_button'", "snippet": "driver.find_element_by_css_selector('.button.c_button.s_button').click()", "question_id": 21350605 }, { "intent": "python selenium click on button", "rewritten_intent": null, "snippet": "driver.find_element_by_css_selector('.button .c_button .s_button').click()", "question_id": 21350605 }, { "intent": "Is it possible to kill a process on Windows from within Python?", "rewritten_intent": "kill a process `make.exe` from python script on windows", "snippet": "os.system('taskkill /im make.exe')", "question_id": 6278847 }, { "intent": "How to get current date and time from DB using SQLAlchemy", "rewritten_intent": "SQLAlchemy select records of columns of table `my_table` in addition to current date column", "snippet": "print(select([my_table, func.current_date()]).execute())", "question_id": 4552380 }, { "intent": "Remove duplicate chars using regex?", "rewritten_intent": "remove duplicate characters from string 'ffffffbbbbbbbqqq'", "snippet": "re.sub('([a-z])\\\\1+', '\\\\1', 'ffffffbbbbbbbqqq')", "question_id": 4574509 }, { "intent": "Regex to remove periods in acronyms?", "rewritten_intent": "remove periods inbetween capital letters that aren't immediately preceeded by word character(s) in a string `s` using regular expressions", "snippet": "re.sub('(?\\\\1'", "snippet": "re.sub('\\\\b(this|string)\\\\b', '\\\\1', 'this is my string')", "question_id": 4338032 }, { "intent": "Output data from all columns in a dataframe in pandas", "rewritten_intent": "output data of the first 7 columns of Pandas dataframe", "snippet": "pandas.set_option('display.max_columns', 7)", "question_id": 11361985 }, { "intent": "Output data from all columns in a dataframe in pandas", "rewritten_intent": "Display maximum output data of columns in dataframe `pandas` that will fit into the screen", "snippet": "pandas.set_option('display.max_columns', None)", "question_id": 11361985 }, { "intent": "Modifying a subset of rows in a pandas dataframe", "rewritten_intent": "set the value in column 'B' to NaN if the corresponding value in column 'A' is equal to 0 in pandas dataframe `df`", "snippet": "df.ix[df.A == 0, 'B'] = np.nan", "question_id": 12307099 }, { "intent": "Selecting Element followed by text with Selenium WebDriver", "rewritten_intent": "Selecting Element \"//li/label/input\" followed by text \"polishpottery\" with Selenium WebDriver `driver`", "snippet": "driver.find_element_by_xpath(\"//li/label/input[contains(..,'polishpottery')]\")", "question_id": 11406091 }, { "intent": "Ordering a list of dictionaries in python", "rewritten_intent": "Sort a list of dictionaries `mylist` by keys \"weight\" and \"factor\"", "snippet": "mylist.sort(key=operator.itemgetter('weight', 'factor'))", "question_id": 861190 }, { "intent": "Ordering a list of dictionaries in python", "rewritten_intent": "ordering a list of dictionaries `mylist` by elements 'weight' and 'factor'", "snippet": "mylist.sort(key=lambda d: (d['weight'], d['factor']))", "question_id": 861190 }, { "intent": "From a list of lists to a dictionary", "rewritten_intent": "Convert a list of lists `lol` to a dictionary with key as second value of a list and value as list itself", "snippet": "{x[1]: x for x in lol}", "question_id": 14986218 }, { "intent": "Sorting dictionary keys based on their values", "rewritten_intent": "sort keys of dictionary 'd' based on their values", "snippet": "sorted(d, key=lambda k: d[k][1])", "question_id": 4690094 }, { "intent": "Python: How to round 123 to 100 instead of 100.0?", "rewritten_intent": "round 123 to 100", "snippet": "int(round(123, -2))", "question_id": 2742784 }, { "intent": "How do I create a file in python without overwriting an existing file", "rewritten_intent": "create file 'x' if file 'x' does not exist", "snippet": "fd = os.open('x', os.O_WRONLY | os.O_CREAT | os.O_EXCL)", "question_id": 1348026 }, { "intent": "How to slice a list of strings with space delimiter?", "rewritten_intent": "get a list of last trailing words from another list of strings`Original_List`", "snippet": "new_list = [x.split()[-1] for x in Original_List]", "question_id": 40535203 }, { "intent": "Reverse a string", "rewritten_intent": "Reverse a string 'hello world'", "snippet": "'hello world'[::(-1)]", "question_id": 931092 }, { "intent": "Reverse a string", "rewritten_intent": "Reverse list `s`", "snippet": "s[::(-1)]", "question_id": 931092 }, { "intent": "Reverse a string", "rewritten_intent": "Reverse string 'foo'", "snippet": "''.join(reversed('foo'))", "question_id": 931092 }, { "intent": "Reverse a string", "rewritten_intent": "Reverse a string `string`", "snippet": "''.join(reversed(string))", "question_id": 931092 }, { "intent": "Reverse a string", "rewritten_intent": "Reverse a string \"foo\"", "snippet": "'foo'[::(-1)]", "question_id": 931092 }, { "intent": "Reverse a string", "rewritten_intent": "Reverse a string `a_string`", "snippet": "a_string[::(-1)]", "question_id": 931092 }, { "intent": "Reverse a string", "rewritten_intent": "Reverse a string `a_string`", "snippet": "def reversed_string(a_string):\n return a_string[::(-1)]", "question_id": 931092 }, { "intent": "Reverse a string", "rewritten_intent": "Reverse a string `s`", "snippet": "''.join(reversed(s))", "question_id": 931092 }, { "intent": "Generate a sequence of numbers in Python", "rewritten_intent": "generate a string of numbers separated by comma which is divisible by `4` with remainder `1` or `2`.", "snippet": "\"\"\",\"\"\".join(str(i) for i in range(100) if i % 4 in (1, 2))", "question_id": 11064917 }, { "intent": "How to convert this list into a dictionary", "rewritten_intent": "convert list `lst` of key, value pairs into a dictionary", "snippet": "dict([(e[0], int(e[1])) for e in lst])", "question_id": 33824334 }, { "intent": "sorting a list of tuples in Python", "rewritten_intent": "sorting a list of tuples `list_of_tuples` where each tuple is reversed", "snippet": "sorted(list_of_tuples, key=lambda tup: tup[::-1])", "question_id": 10213994 }, { "intent": "sorting a list of tuples in Python", "rewritten_intent": "sorting a list of tuples `list_of_tuples` by second key", "snippet": "sorted(list_of_tuples, key=lambda tup: tup[1])", "question_id": 10213994 }, { "intent": "Concatenating two one-dimensional NumPy arrays", "rewritten_intent": "Concatenating two one-dimensional NumPy arrays 'a' and 'b'.", "snippet": "numpy.concatenate([a, b])", "question_id": 9236926 }, { "intent": "Writing a list to a file with Python", "rewritten_intent": "writing items in list `thelist` to file `thefile`", "snippet": "for item in thelist:\n thefile.write(('%s\\n' % item))", "question_id": 899103 }, { "intent": "Writing a list to a file with Python", "rewritten_intent": "writing items in list `thelist` to file `thefile`", "snippet": "for item in thelist:\n pass", "question_id": 899103 }, { "intent": "Writing a list to a file with Python", "rewritten_intent": "serialize `itemlist` to file `outfile`", "snippet": "pickle.dump(itemlist, outfile)", "question_id": 899103 }, { "intent": "Writing a list to a file with Python", "rewritten_intent": "writing items in list `itemlist` to file `outfile`", "snippet": "outfile.write('\\n'.join(itemlist))", "question_id": 899103 }, { "intent": "SQLAlchemy: a better way for update with declarative?", "rewritten_intent": "Update a user's name as `Bob Marley` having id `123` in SQLAlchemy", "snippet": "session.query(User).filter_by(id=123).update({'name': 'Bob Marley'})", "question_id": 2631935 }, { "intent": "How to send cookies in a post request with the Python Requests library?", "rewritten_intent": "send cookies `cookie` in a post request to url 'http://wikipedia.org' with the python requests library", "snippet": "r = requests.post('http://wikipedia.org', cookies=cookie)", "question_id": 7164679 }, { "intent": "How to include third party Python libraries in Google App Engine?", "rewritten_intent": "insert directory 'libs' at the 0th index of current directory", "snippet": "sys.path.insert(0, 'libs')", "question_id": 14850853 }, { "intent": "get current time", "rewritten_intent": "get current date and time", "snippet": "datetime.datetime.now()", "question_id": 415511 }, { "intent": "get current time", "rewritten_intent": "get current time", "snippet": "datetime.datetime.now().time()", "question_id": 415511 }, { "intent": "get current time", "rewritten_intent": "get current time in pretty format", "snippet": "strftime('%Y-%m-%d %H:%M:%S', gmtime())", "question_id": 415511 }, { "intent": "get current time", "rewritten_intent": "get current time in string format", "snippet": "str(datetime.now())", "question_id": 415511 }, { "intent": "get current time", "rewritten_intent": "get current time", "snippet": "datetime.datetime.time(datetime.datetime.now())", "question_id": 415511 }, { "intent": "Converting hex to int in python", "rewritten_intent": "convert hex '\\xff' to integer", "snippet": "ord('\\xff')", "question_id": 19819863 }, { "intent": "Python Pandas Identify Duplicated rows with Additional Column", "rewritten_intent": "identify duplicated rows in columns 'PplNum' and 'RoomNum' with additional column in dataframe `df`", "snippet": "df.groupby(['PplNum', 'RoomNum']).cumcount() + 1", "question_id": 37497559 }, { "intent": "How to get UTC time in Python?", "rewritten_intent": "get current utc time", "snippet": "datetime.utcnow()", "question_id": 15940280 }, { "intent": "Python: Make last item of array become the first", "rewritten_intent": "move last item of array `a` to the first position", "snippet": "a[-1:] + a[:-1]", "question_id": 12845112 }, { "intent": "pandas: how to run a pivot with a multi-index?", "rewritten_intent": "Convert dataframe `df` to a pivot table using column 'year', 'month', and 'item' as indexes", "snippet": "df.set_index(['year', 'month', 'item']).unstack(level=-1)", "question_id": 35414625 }, { "intent": "pandas: how to run a pivot with a multi-index?", "rewritten_intent": "run a pivot with a multi-index `year` and `month` in a pandas data frame", "snippet": "df.pivot_table(values='value', index=['year', 'month'], columns='item')", "question_id": 35414625 }, { "intent": "How to print/show an expression in rational number form in python", "rewritten_intent": "print a rational number `3/2`", "snippet": "print('\\n\\x1b[4m' + '3' + '\\x1b[0m' + '\\n2')", "question_id": 39381222 }, { "intent": "What is the best way to sort list with custom sorting parameters in Python?", "rewritten_intent": null, "snippet": "li1.sort(key=lambda x: not x.startswith('b.'))", "question_id": 7996940 }, { "intent": "How to loop backwards in python?", "rewritten_intent": "iterate backwards from 10 to 0", "snippet": "range(10, 0, -1)", "question_id": 3476732 }, { "intent": "Get Element value with minidom with Python", "rewritten_intent": "get value of first child of xml node `name`", "snippet": "name[0].firstChild.nodeValue", "question_id": 317413 }, { "intent": "Simple threading in Python 2.6 using thread.start_new_thread()", "rewritten_intent": "start a new thread for `myfunction` with parameters 'MyStringHere' and 1", "snippet": "thread.start_new_thread(myfunction, ('MyStringHere', 1))", "question_id": 849674 }, { "intent": "Simple threading in Python 2.6 using thread.start_new_thread()", "rewritten_intent": "start a new thread for `myfunction` with parameters 'MyStringHere' and 1", "snippet": "thread.start_new_thread(myfunction, ('MyStringHere', 1))", "question_id": 849674 }, { "intent": "How to find all positions of the maximum value in a list?", "rewritten_intent": "get index of the first biggest element in list `a`", "snippet": "a.index(max(a))", "question_id": 3989016 }, { "intent": "Regex add character to matched string", "rewritten_intent": "replace periods `.` that are not followed by periods or spaces with a period and a space `. `", "snippet": "re.sub('\\\\.(?=[^ .])', '. ', para)", "question_id": 42731970 }, { "intent": "how to turn a string of letters embedded in squared brackets into embedded lists", "rewritten_intent": "convert a string `a` of letters embedded in squared brackets into embedded lists", "snippet": "[i.split() for i in re.findall('\\\\[([^\\\\[\\\\]]+)\\\\]', a)]", "question_id": 33147992 }, { "intent": "extract item from list of dictionaries", "rewritten_intent": "extract dictionary `d` from list `a` where the value associated with the key 'name' of dictionary `d` is equal to 'pluto'", "snippet": "[d for d in a if d['name'] == 'pluto']", "question_id": 7900882 }, { "intent": "extract item from list of dictionaries", "rewritten_intent": "extract dictionary from list of dictionaries based on a key's value.", "snippet": "[d for d in a if d['name'] == 'pluto']", "question_id": 7900882 }, { "intent": "Python: simplest way to get list of values from dict?", "rewritten_intent": "Retrieve list of values from dictionary 'd'", "snippet": "list(d.values())", "question_id": 16228248 }, { "intent": "String manipulation in Cython", "rewritten_intent": "replace occurrences of two whitespaces or more with one whitespace ' ' in string `s`", "snippet": "re.sub(' +', ' ', s)", "question_id": 943809 }, { "intent": "Set execute bit for a file using python", "rewritten_intent": "Change the mode of file 'my_script.sh' to permission number 484", "snippet": "os.chmod('my_script.sh', 484)", "question_id": 14104778 }, { "intent": "Pandas to_csv call is prepending a comma", "rewritten_intent": "write pandas dataframe `df` to the file 'c:\\\\data\\\\t.csv' without row names", "snippet": "df.to_csv('c:\\\\data\\\\t.csv', index=False)", "question_id": 30605909 }, { "intent": "Python regex to remove all words which contains number", "rewritten_intent": "remove all words which contains number from a string `words` using regex", "snippet": "re.sub('\\\\w*\\\\d\\\\w*', '', words).strip()", "question_id": 18082130 }, { "intent": "How can I control the keyboard and mouse with Python?", "rewritten_intent": "control the keyboard and mouse with dogtail in linux", "snippet": "dogtail.rawinput.click(100, 100)", "question_id": 1946181 }, { "intent": "How to parse dates with -0400 timezone string in python?", "rewritten_intent": "parse date string '2009/05/13 19:19:30 -0400' using format '%Y/%m/%d %H:%M:%S %z'", "snippet": "datetime.strptime('2009/05/13 19:19:30 -0400', '%Y/%m/%d %H:%M:%S %z')", "question_id": 1101508 }, { "intent": "Python - Locating the position of a regex match in a string?", "rewritten_intent": "Get the position of a regex match for word `is` in a string `String`", "snippet": "re.search('\\\\bis\\\\b', String).start()", "question_id": 2674391 }, { "intent": "Python - Locating the position of a regex match in a string?", "rewritten_intent": "Get the position of a regex match `is` in a string `String`", "snippet": "re.search('is', String).start()", "question_id": 2674391 }, { "intent": "How to input an integer tuple from user?", "rewritten_intent": "input an integer tuple from user", "snippet": "tuple(map(int, input().split(',')))", "question_id": 2233917 }, { "intent": "How to input an integer tuple from user?", "rewritten_intent": "input a tuple of integers from user", "snippet": "tuple(int(x.strip()) for x in input().split(','))", "question_id": 2233917 }, { "intent": "How to replace unicode characters in string with something else python?", "rewritten_intent": "replace unicode character '\\u2022' in string 'str' with '*'", "snippet": "str.decode('utf-8').replace('\\u2022', '*').encode('utf-8')", "question_id": 13093727 }, { "intent": "How to replace unicode characters in string with something else python?", "rewritten_intent": "replace unicode characters ''\\u2022' in string 'str' with '*'", "snippet": "str.decode('utf-8').replace('\\u2022', '*')", "question_id": 13093727 }, { "intent": "How to convert ndarray to array?", "rewritten_intent": "convert ndarray with shape 3x3 to array", "snippet": "np.zeros((3, 3)).ravel()", "question_id": 18200052 }, { "intent": "What OS am I running on", "rewritten_intent": "get os name", "snippet": "import platform\nplatform.system()", "question_id": 1854 }, { "intent": "What OS am I running on", "rewritten_intent": "get os version", "snippet": "import platform\nplatform.release()", "question_id": 1854 }, { "intent": "What OS am I running on", "rewritten_intent": "get the name of the OS", "snippet": "print(os.name)", "question_id": 1854 }, { "intent": "What is the most pythonic way to exclude elements of a list that start with a specific character?", "rewritten_intent": null, "snippet": "[x for x in my_list if not x.startswith('#')]", "question_id": 11791568 }, { "intent": "Python string formatting when string contains \"%s\" without escaping", "rewritten_intent": "replace fields delimited by braces {} in string \"Day old bread, 50% sale {0}\" with string 'today'", "snippet": "\"\"\"Day old bread, 50% sale {0}\"\"\".format('today')", "question_id": 2847272 }, { "intent": "List of Tuples (string, float)with NaN How to get the min value?", "rewritten_intent": "Get a minimum value from a list of tuples `list` with values of type `string` and `float` with nan", "snippet": "min(list, key=lambda x: float('inf') if math.isnan(x[1]) else x[1])", "question_id": 15148684 }, { "intent": "Python: Finding average of a nested list", "rewritten_intent": "Find average of a nested list `a`", "snippet": "a = [(sum(x) / len(x)) for x in zip(*a)]", "question_id": 2153444 }, { "intent": "How do I add custom field to Python log format string?", "rewritten_intent": "Log info message 'Log message' with attributes `{'app_name': 'myapp'}`", "snippet": "logging.info('Log message', extra={'app_name': 'myapp'})", "question_id": 17558552 }, { "intent": "finding non-numeric rows in dataframe in pandas?", "rewritten_intent": "replace values of dataframe `df` with True if numeric", "snippet": "df.applymap(lambda x: isinstance(x, (int, float)))", "question_id": 21771133 }, { "intent": "Sort list of mixed strings based on digits", "rewritten_intent": "sort list `l` based on its elements' digits", "snippet": "sorted(l, key=lambda x: int(re.search('\\\\d+', x).group(0)))", "question_id": 39129846 }, { "intent": "Function to close the window in Tkinter", "rewritten_intent": "close the window in tkinter", "snippet": "self.root.destroy()", "question_id": 8009176 }, { "intent": "Calcuate mean for selected rows for selected columns in pandas data frame", "rewritten_intent": "get mean of columns `2, 5, 6, 7, 8` for all rows in dataframe `df`", "snippet": "df.iloc[:, ([2, 5, 6, 7, 8])].mean(axis=1)", "question_id": 36454494 }, { "intent": "How to filter by sub-level index in Pandas", "rewritten_intent": "filter dataframe `df` by sub-level index '0630' in pandas", "snippet": "df[df.index.map(lambda x: x[1].endswith('0630'))]", "question_id": 12224778 }, { "intent": "Deleting row with Flask-SQLAlchemy", "rewritten_intent": "flask-sqlalchemy delete row `page`", "snippet": "db.session.delete(page)", "question_id": 4921038 }, { "intent": "How do I convert a unicode to a string at the Python level?", "rewritten_intent": "Format a string `u'Andr\\xc3\\xa9'` that has unicode characters", "snippet": "\"\"\"\"\"\".join(chr(ord(c)) for c in 'Andr\\xc3\\xa9')", "question_id": 2783079 }, { "intent": "How do I convert a unicode to a string at the Python level?", "rewritten_intent": "convert a unicode 'Andr\\xc3\\xa9' to a string", "snippet": "\"\"\"\"\"\".join(chr(ord(c)) for c in 'Andr\\xc3\\xa9').decode('utf8')", "question_id": 2783079 }, { "intent": "Directory listing", "rewritten_intent": "list all files in directory \".\"", "snippet": "for (dirname, dirnames, filenames) in os.walk('.'):\n for subdirname in dirnames:\n print(os.path.join(dirname, subdirname))\n for filename in filenames:\n pass", "question_id": 120656 }, { "intent": "Directory listing", "rewritten_intent": "list all files in directory `path`", "snippet": "os.listdir(path)", "question_id": 120656 }, { "intent": "How to rename all folders?", "rewritten_intent": "rename file `dir` to `dir` + '!'", "snippet": "os.rename(dir, dir + '!')", "question_id": 11816315 }, { "intent": "Pythonic way to insert every 2 elements in a string", "rewritten_intent": "Insert a character `-` after every two elements in a string `s`", "snippet": "\"\"\"-\"\"\".join(a + b for a, b in zip(s[::2], s[1::2]))", "question_id": 3258573 }, { "intent": "Printing numbers in python", "rewritten_intent": "printing numbers rounding up to third decimal place", "snippet": "print('%.3f' % 3.1415)", "question_id": 3241594 }, { "intent": "Add element to a json in python", "rewritten_intent": "add variable `var` to key 'f' of first element in JSON data `data`", "snippet": "data[0]['f'] = var", "question_id": 22296496 }, { "intent": "Retrieving python module path", "rewritten_intent": "get the path of module `a_module`", "snippet": "print(a_module.__file__)", "question_id": 247770 }, { "intent": "Retrieving python module path", "rewritten_intent": "get the path of the current python module", "snippet": "print(os.getcwd())", "question_id": 247770 }, { "intent": "Retrieving python module path", "rewritten_intent": "get the path of the python module `amodule`", "snippet": "path = os.path.abspath(amodule.__file__)", "question_id": 247770 }, { "intent": "Padding a list in python with particular value", "rewritten_intent": "fill list `myList` with 4 0's", "snippet": "self.myList.extend([0] * (4 - len(self.myList)))", "question_id": 7026131 }, { "intent": "Fastest Way to Drop Duplicated Index in a Pandas DataFrame", "rewritten_intent": "drop duplicate indexes in a pandas data frame `df`", "snippet": "df[~df.index.duplicated()]", "question_id": 22918212 }, { "intent": "Is there a more pythonic way of exploding a list over a function's arguments?", "rewritten_intent": "unpack elements of list `i` as arguments into function `foo`", "snippet": "foo(*i)", "question_id": 13891559 }, { "intent": "Generate list of numbers in specific format", "rewritten_intent": "generate list of numbers in specific format using string formatting precision.", "snippet": "[('%.2d' % i) for i in range(16)]", "question_id": 12030074 }, { "intent": "Summarizing a dictionary of arrays in Python", "rewritten_intent": "sort dictionary `mydict` in descending order based on the sum of each value in it", "snippet": "sorted(iter(mydict.items()), key=lambda tup: sum(tup[1]), reverse=True)[:3]", "question_id": 3411025 }, { "intent": "Summarizing a dictionary of arrays in Python", "rewritten_intent": "get top `3` items from a dictionary `mydict` with largest sum of values", "snippet": "heapq.nlargest(3, iter(mydict.items()), key=lambda tup: sum(tup[1]))", "question_id": 3411025 }, { "intent": "get index of character in python list", "rewritten_intent": "get index of character 'b' in list '['a', 'b']'", "snippet": "['a', 'b'].index('b')", "question_id": 3847472 }, { "intent": "How to set font size of Matplotlib axis Legend?", "rewritten_intent": "set font size of axis legend of plot `plt` to 'xx-small'", "snippet": "plt.setp(legend.get_title(), fontsize='xx-small')", "question_id": 12402561 }, { "intent": "Python: Convert a string to an integer", "rewritten_intent": null, "snippet": "int(' 23 ')", "question_id": 2508861 }, { "intent": "How to extract the n-th elements from a list of tuples in python?", "rewritten_intent": "extract the 2nd elements from a list of tuples", "snippet": "[x[1] for x in elements]", "question_id": 3308102 }, { "intent": "getting the opposite diagonal of a numpy array", "rewritten_intent": "get the opposite diagonal of a numpy array `array`", "snippet": "np.diag(np.rot90(array))", "question_id": 16114333 }, { "intent": "Convert list of tuples to list?", "rewritten_intent": "flatten list of tuples `a`", "snippet": "list(chain.from_iterable(a))", "question_id": 10941229 }, { "intent": "Removing white space from txt with python", "rewritten_intent": "substitute two or more whitespace characters with character '|' in string `line`", "snippet": "re.sub('\\\\s{2,}', '|', line.strip())", "question_id": 36957908 }, { "intent": "Limiting floats to two decimal points", "rewritten_intent": "print float `a` with two decimal points", "snippet": "print(('%.2f' % a))", "question_id": 455612 }, { "intent": "Limiting floats to two decimal points", "rewritten_intent": "print float `a` with two decimal points", "snippet": "print(('{0:.2f}'.format(a)))", "question_id": 455612 }, { "intent": "Limiting floats to two decimal points", "rewritten_intent": "print float `a` with two decimal points", "snippet": "print(('{0:.2f}'.format(round(a, 2))))", "question_id": 455612 }, { "intent": "Limiting floats to two decimal points", "rewritten_intent": "print float `a` with two decimal points", "snippet": "print(('%.2f' % round(a, 2)))", "question_id": 455612 }, { "intent": "Limiting floats to two decimal points", "rewritten_intent": "limit float 13.9499999 to two decimal points", "snippet": "('%.2f' % 13.9499999)", "question_id": 455612 }, { "intent": "Limiting floats to two decimal points", "rewritten_intent": "limit float 3.14159 to two decimal points", "snippet": "('%.2f' % 3.14159)", "question_id": 455612 }, { "intent": "Limiting floats to two decimal points", "rewritten_intent": "limit float 13.949999999999999 to two decimal points", "snippet": "float('{0:.2f}'.format(13.95))", "question_id": 455612 }, { "intent": "Limiting floats to two decimal points", "rewritten_intent": "limit float 13.949999999999999 to two decimal points", "snippet": "'{0:.2f}'.format(13.95)", "question_id": 455612 }, { "intent": "How to I load a tsv file into a Pandas DataFrame?", "rewritten_intent": "load a tsv file `c:/~/trainSetRel3.txt` into a pandas data frame", "snippet": "DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\\t')", "question_id": 9652832 }, { "intent": "How to set UTC offset for datetime?", "rewritten_intent": "set UTC offset by 9 hrs ahead for date '2013/09/11 00:17'", "snippet": "dateutil.parser.parse('2013/09/11 00:17 +0900')", "question_id": 18722196 }, { "intent": "Passing list of parameters to SQL in psycopg2", "rewritten_intent": "pass a list of parameters `((1, 2, 3),) to sql queue 'SELECT * FROM table WHERE column IN %s;'", "snippet": "cur.mogrify('SELECT * FROM table WHERE column IN %s;', ((1, 2, 3),))", "question_id": 8671702 }, { "intent": "How would I sum a multi-dimensional array in the most succinct python?", "rewritten_intent": "sum all elements of two-dimensions list `[[1, 2, 3, 4], [2, 4, 5, 6]]]`", "snippet": "sum([sum(x) for x in [[1, 2, 3, 4], [2, 4, 5, 6]]])", "question_id": 9497290 }, { "intent": "Access an arbitrary element in a dictionary in Python", "rewritten_intent": "Retrieve an arbitrary value from dictionary `dict`", "snippet": "next(iter(dict.values()))", "question_id": 3097866 }, { "intent": "Access an arbitrary element in a dictionary in Python", "rewritten_intent": "access an arbitrary value from dictionary `dict`", "snippet": "next(iter(list(dict.values())))", "question_id": 3097866 }, { "intent": "Pandas: aggregate based on filter on another column", "rewritten_intent": "group dataframe `df` by columns 'Month' and 'Fruit'", "snippet": "df.groupby(['Month', 'Fruit']).sum().unstack(level=0)", "question_id": 42012589 }, { "intent": "sorting list of tuples by arbitrary key", "rewritten_intent": "sort list `mylist` of tuples by arbitrary key from list `order`", "snippet": "sorted(mylist, key=lambda x: order.index(x[1]))", "question_id": 13408919 }, { "intent": "Python - Sort a list of dics by value of dict`s dict value", "rewritten_intent": "sort a list of dictionary `persons` according to the key `['passport']['birth_info']['date']`", "snippet": "sorted(persons, key=lambda x: x['passport']['birth_info']['date'])", "question_id": 39804375 }, { "intent": "How can I remove the fragment identifier from a URL?", "rewritten_intent": "remove the fragment identifier `#something` from a url `http://www.address.com/something#something`", "snippet": "urlparse.urldefrag('http://www.address.com/something#something')", "question_id": 6250046 }, { "intent": "How to download to a specific directory with Python?", "rewritten_intent": "download to a directory '/path/to/dir/filename.ext' from source 'http://example.com/file.ext'", "snippet": "urllib.request.urlretrieve('http://example.com/file.ext', '/path/to/dir/filename.ext')", "question_id": 21018612 }, { "intent": "removing duplicates of a list of sets", "rewritten_intent": "remove all duplicates from a list of sets `L`", "snippet": "list(set(frozenset(item) for item in L))", "question_id": 32296933 }, { "intent": "removing duplicates of a list of sets", "rewritten_intent": "remove duplicates from a list of sets 'L'", "snippet": "[set(item) for item in set(frozenset(item) for item in L)]", "question_id": 32296933 }, { "intent": "How to terminate process from Python using pid?", "rewritten_intent": "terminate process `p`", "snippet": "p.terminate()", "question_id": 17856928 }, { "intent": "Delete all objects in a list", "rewritten_intent": "delete all values in a list `mylist`", "snippet": "del mylist[:]", "question_id": 14465279 }, { "intent": "How to throw an error window in Python in Windows", "rewritten_intent": "throw an error window in python in windows", "snippet": "ctypes.windll.user32.MessageBoxW(0, 'Error', 'Error', 0)", "question_id": 3365673 }, { "intent": "Remove empty strings from a list of strings", "rewritten_intent": "remove empty strings from list `str_list`", "snippet": "str_list = list([_f for _f in str_list if _f])", "question_id": 3845423 }, { "intent": "How to remove whitespace in BeautifulSoup", "rewritten_intent": "remove newlines and whitespace from string `yourstring`", "snippet": "re.sub('[\\\\ \\\\n]{2,}', '', yourstring)", "question_id": 4270742 }, { "intent": "Dot notation string manipulation", "rewritten_intent": "remove the last dot and all text beyond it in string `s`", "snippet": "re.sub('\\\\.[^.]+$', '', s)", "question_id": 35118265 }, { "intent": "Removing elements from an array that are in another array", "rewritten_intent": "remove elements from an array `A` that are in array `B`", "snippet": "A[np.all(np.any(A - B[:, (None)], axis=2), axis=0)]", "question_id": 40055835 }, { "intent": "write to csv from DataFrame python pandas", "rewritten_intent": "Write column 'sum' of DataFrame `a` to csv file 'test.csv'", "snippet": "a.to_csv('test.csv', cols=['sum'])", "question_id": 21206395 }, { "intent": "call a Python script from another Python script", "rewritten_intent": "call a Python script \"test2.py\"", "snippet": "exec(compile(open('test2.py').read(), 'test2.py', 'exec'))", "question_id": 1186789 }, { "intent": "call a Python script from another Python script", "rewritten_intent": "call a Python script \"test1.py\"", "snippet": "subprocess.call('test1.py', shell=True)", "question_id": 1186789 }, { "intent": "How do I sort a zipped list in Python?", "rewritten_intent": "sort a zipped list `zipped` using lambda function", "snippet": "sorted(zipped, key=lambda x: x[1])", "question_id": 7142227 }, { "intent": "How do I sort a zipped list in Python?", "rewritten_intent": null, "snippet": "zipped.sort(key=lambda t: t[1])", "question_id": 7142227 }, { "intent": "Sorting a dictionary by value then by key", "rewritten_intent": "sort a dictionary `y` by value then by key", "snippet": "sorted(list(y.items()), key=lambda x: (x[1], x[0]), reverse=True)", "question_id": 7742752 }, { "intent": "Using BeautifulSoup to select div blocks within HTML", "rewritten_intent": "using beautifulsoup to select div blocks within html `soup`", "snippet": "soup.find_all('div', class_='crBlock ')", "question_id": 19011613 }, { "intent": "Remove list of indices from a list in Python", "rewritten_intent": "remove elements from list `centroids` the indexes of which are in array `index`", "snippet": "[element for i, element in enumerate(centroids) if i not in index]", "question_id": 31267493 }, { "intent": "Comparing two lists in Python", "rewritten_intent": "list duplicated elements in two lists `listA` and `listB`", "snippet": "list(set(listA) & set(listB))", "question_id": 11697709 }, { "intent": "http file downloading and saving", "rewritten_intent": "download \"http://randomsite.com/file.gz\" from http and save as \"file.gz\"", "snippet": "testfile = urllib.request.URLopener()\ntestfile.retrieve('http://randomsite.com/file.gz', 'file.gz')", "question_id": 19602931 }, { "intent": "http file downloading and saving", "rewritten_intent": "download file from http url \"http://randomsite.com/file.gz\" and save as \"file.gz\"", "snippet": "urllib.request.urlretrieve('http://randomsite.com/file.gz', 'file.gz')", "question_id": 19602931 }, { "intent": "http file downloading and saving", "rewritten_intent": "download file from http url `file_url`", "snippet": "file_name = wget.download(file_url)", "question_id": 19602931 }, { "intent": "Accented characters in Matplotlib", "rewritten_intent": "set an array of unicode characters `[u'\\xe9', u'\\xe3', u'\\xe2']` as labels in Matplotlib `ax`", "snippet": "ax.set_yticklabels(['\\xe9', '\\xe3', '\\xe2'])", "question_id": 2406700 }, { "intent": "How to get a list of all integer points in an n-dimensional cube using python?", "rewritten_intent": "get a list of all integer points in a `dim` dimensional hypercube with coordinates from `-x` to `y` for all dimensions", "snippet": "list(itertools.product(list(range(-x, y)), repeat=dim))", "question_id": 41727442 }, { "intent": "How can I convert a unicode string into string literals in Python 2.7?", "rewritten_intent": "convert unicode string `s` into string literals", "snippet": "print(s.encode('unicode_escape'))", "question_id": 20774910 }, { "intent": "python - How to format variable number of arguments into a string?", "rewritten_intent": "how to format a list of arguments `my_args` into a string", "snippet": "'Hello %s' % ', '.join(my_args)", "question_id": 18391059 }, { "intent": "Python regex search AND split", "rewritten_intent": "search and split string 'aaa bbb ccc ddd eee fff' by delimiter '(ddd)'", "snippet": "re.split('(ddd)', 'aaa bbb ccc ddd eee fff', 1)", "question_id": 8970524 }, { "intent": "Python regex search AND split", "rewritten_intent": "regex search and split string 'aaa bbb ccc ddd eee fff' by delimiter '(d(d)d)'", "snippet": "re.split('(d(d)d)', 'aaa bbb ccc ddd eee fff', 1)", "question_id": 8970524 }, { "intent": "Convert list of dictionaries to Dataframe", "rewritten_intent": "convert a list of dictionaries `d` to pandas data frame", "snippet": "pd.DataFrame(d)", "question_id": 20638006 }, { "intent": "How to split string into words that do not contain whitespaces in python?", "rewritten_intent": "split string \"This is a string\" into words that do not contain whitespaces", "snippet": "\"\"\"This is a string\"\"\".split()", "question_id": 9206964 }, { "intent": "How to split string into words that do not contain whitespaces in python?", "rewritten_intent": "split string \"This is a string\" into words that does not contain whitespaces", "snippet": "\"\"\"This is a string\"\"\".split()", "question_id": 9206964 }, { "intent": "python pandas: apply a function with arguments to a series", "rewritten_intent": null, "snippet": "my_series.apply(your_function, args=(2, 3, 4), extra_kw=1)", "question_id": 12182744 }, { "intent": "Python: How to remove all duplicate items from a list", "rewritten_intent": "remove all duplicate items from a list `lseperatedOrblist`", "snippet": "woduplicates = list(set(lseperatedOrblist))", "question_id": 6764909 }, { "intent": "Sum of product of combinations in a list", "rewritten_intent": "sum of product of combinations in a list `l`", "snippet": "sum([(i * j) for i, j in list(itertools.combinations(l, 2))])", "question_id": 34437284 }, { "intent": "Using variables in Python regular expression", "rewritten_intent": "regular expression for validating string 'user' containing a sequence of characters ending with '-' followed by any number of digits.", "snippet": "re.compile('{}-\\\\d*'.format(user))", "question_id": 5900683 }, { "intent": "In Python, how do I convert all of the items in a list to floats?", "rewritten_intent": "convert all of the items in a list `lst` to float", "snippet": "[float(i) for i in lst]", "question_id": 1614236 }, { "intent": "How can I multiply all items in a list together with Python?", "rewritten_intent": "multiply all items in a list `[1, 2, 3, 4, 5, 6]` together", "snippet": "from functools import reduce\nreduce(lambda x, y: x * y, [1, 2, 3, 4, 5, 6])", "question_id": 13840379 }, { "intent": "How to write a tuple of tuples to a CSV file using Python", "rewritten_intent": "write a tuple of tuples `A` to a csv file using python", "snippet": "writer.writerow(A)", "question_id": 8687568 }, { "intent": "How to write a tuple of tuples to a CSV file using Python", "rewritten_intent": "Write all tuple of tuples `A` at once into csv file", "snippet": "writer.writerows(A)", "question_id": 8687568 }, { "intent": "python, format string", "rewritten_intent": "python, format string \"{} %s {}\" to have 'foo' and 'bar' in the first and second positions", "snippet": "\"\"\"{} %s {}\"\"\".format('foo', 'bar')", "question_id": 4928526 }, { "intent": "Replace a string in list of lists", "rewritten_intent": "Truncate `\\r\\n` from each string in a list of string `example`", "snippet": "example = [x.replace('\\r\\n', '') for x in example]", "question_id": 13781828 }, { "intent": "Python: split elements of a list", "rewritten_intent": "split elements of a list `l` by '\\t'", "snippet": "[i.partition('\\t')[-1] for i in l if '\\t' in i]", "question_id": 23145240 }, { "intent": "Splitting a string by using two substrings in Python", "rewritten_intent": "search for regex pattern 'Test(.*)print' in string `testStr` including new line character '\\n'", "snippet": "re.search('Test(.*)print', testStr, re.DOTALL)", "question_id": 20062565 }, { "intent": "python, locating and clicking a specific button with selenium", "rewritten_intent": "find button that is in li class `next` and assign it to variable `next`", "snippet": "next = driver.find_element_by_css_selector('li.next>a')", "question_id": 20457174 }, { "intent": "Getting file size in Python?", "rewritten_intent": "get the size of file 'C:\\\\Python27\\\\Lib\\\\genericpath.py'", "snippet": "os.stat('C:\\\\Python27\\\\Lib\\\\genericpath.py').st_size", "question_id": 6591931 }, { "intent": "how do i return a string from a regex match in python", "rewritten_intent": "return a string from a regex match with pattern '' in string 'line'", "snippet": "imtag = re.match('', line).group(0)", "question_id": 18493677 }, { "intent": "How to change folder names in python?", "rewritten_intent": "Rename a folder `Joe Blow` to `Blow, Joe`", "snippet": "os.rename('Joe Blow', 'Blow, Joe')", "question_id": 8735312 }, { "intent": "How to find overlapping matches with a regexp?", "rewritten_intent": "find overlapping matches from a string `hello` using regex", "snippet": "re.findall('(?=(\\\\w\\\\w))', 'hello')", "question_id": 11430863 }, { "intent": "express binary literals", "rewritten_intent": "convert 173 to binary string", "snippet": "bin(173)", "question_id": 1476 }, { "intent": "express binary literals", "rewritten_intent": "convert binary string '01010101111' to integer", "snippet": "int('01010101111', 2)", "question_id": 1476 }, { "intent": "express binary literals", "rewritten_intent": "convert binary string '010101' to integer", "snippet": "int('010101', 2)", "question_id": 1476 }, { "intent": "express binary literals", "rewritten_intent": "convert binary string '0b0010101010' to integer", "snippet": "int('0b0010101010', 2)", "question_id": 1476 }, { "intent": "express binary literals", "rewritten_intent": "convert 21 to binary string", "snippet": "bin(21)", "question_id": 1476 }, { "intent": "express binary literals", "rewritten_intent": "convert binary string '11111111' to integer", "snippet": "int('11111111', 2)", "question_id": 1476 }, { "intent": "Delete digits in Python (Regex)", "rewritten_intent": "delete all digits in string `s` that are not directly attached to a word character", "snippet": "re.sub('$\\\\d+\\\\W+|\\\\b\\\\d+\\\\b|\\\\W+\\\\d+$', '', s)", "question_id": 817122 }, { "intent": "Delete digits in Python (Regex)", "rewritten_intent": "delete digits at the end of string `s`", "snippet": "re.sub('\\\\b\\\\d+\\\\b', '', s)", "question_id": 817122 }, { "intent": "Delete digits in Python (Regex)", "rewritten_intent": "Delete self-contained digits from string `s`", "snippet": "s = re.sub('^\\\\d+\\\\s|\\\\s\\\\d+\\\\s|\\\\s\\\\d+$', ' ', s)", "question_id": 817122 }, { "intent": "Python Split String", "rewritten_intent": "truncate string `s` up to character ':'", "snippet": "s.split(':', 1)[1]", "question_id": 436599 }, { "intent": "How can I split this comma-delimited string in Python?", "rewritten_intent": "print a string `s` by splitting with comma `,`", "snippet": "print(s.split(','))", "question_id": 5864485 }, { "intent": "How can I split this comma-delimited string in Python?", "rewritten_intent": "Create list by splitting string `mystring` using \",\" as delimiter", "snippet": "mystring.split(',')", "question_id": 5864485 }, { "intent": "How to remove parentheses only around single words in a string", "rewritten_intent": "remove parentheses only around single words in a string `s` using regex", "snippet": "re.sub('\\\\((\\\\w+)\\\\)', '\\\\1', s)", "question_id": 31405409 }, { "intent": "how to open a url in python", "rewritten_intent": "webbrowser open url `url`", "snippet": "webbrowser.open_new(url)", "question_id": 4302027 }, { "intent": "how to open a url in python", "rewritten_intent": "webbrowser open url 'http://example.com'", "snippet": "webbrowser.open('http://example.com')", "question_id": 4302027 }, { "intent": "PyQt QPushButton Background color", "rewritten_intent": "change the background colour of the button `pushbutton` to red", "snippet": "self.pushButton.setStyleSheet('background-color: red')", "question_id": 20668060 }, { "intent": "Zip and apply a list of functions over a list of values in Python", "rewritten_intent": "apply a list of functions named 'functions' over a list of values named 'values'", "snippet": "[x(y) for x, y in zip(functions, values)]", "question_id": 4231345 }, { "intent": "How do I modify the width of a TextCtrl in wxPython?", "rewritten_intent": "modify the width of a text control as `300` keeping default height in wxpython", "snippet": "wx.TextCtrl(self, -1, size=(300, -1))", "question_id": 14306852 }, { "intent": "Displaying a grayscale Image", "rewritten_intent": "display a grayscale image from array of pixels `imageArray`", "snippet": "imshow(imageArray, cmap='Greys_r')", "question_id": 14111705 }, { "intent": "How can I replace all the NaN values with Zero's in a column of a pandas dataframe", "rewritten_intent": "replace all the nan values with 0 in a pandas dataframe `df`", "snippet": "df.fillna(0)", "question_id": 13295735 }, { "intent": "how to export a table dataframe in pyspark to csv?", "rewritten_intent": "export a table dataframe `df` in pyspark to csv 'mycsv.csv'", "snippet": "df.toPandas().to_csv('mycsv.csv')", "question_id": 31385363 }, { "intent": "how to export a table dataframe in pyspark to csv?", "rewritten_intent": "Write DataFrame `df` to csv file 'mycsv.csv'", "snippet": "df.write.csv('mycsv.csv')", "question_id": 31385363 }, { "intent": "Sum the second value of each tuple in a list", "rewritten_intent": "get the sum of each second value from a list of tuple `structure`", "snippet": "sum(x[1] for x in structure)", "question_id": 12218112 }, { "intent": "How to sum the nlargest() integers in groupby", "rewritten_intent": "sum the 3 largest integers in groupby by 'STNAME' and 'COUNTY_POP'", "snippet": "df.groupby('STNAME')['COUNTY_POP'].agg(lambda x: x.nlargest(3).sum())", "question_id": 40517350 }, { "intent": "what would be the python code to add time to a specific timestamp?", "rewritten_intent": "Parse string '21/11/06 16:30' according to format '%d/%m/%y %H:%M'", "snippet": "datetime.strptime('21/11/06 16:30', '%d/%m/%y %H:%M')", "question_id": 4363072 }, { "intent": "How to properly determine current script directory in Python?", "rewritten_intent": "get current script directory", "snippet": "os.path.dirname(os.path.abspath(__file__))", "question_id": 3718657 }, { "intent": "How can I do multiple substitutions using regex in python?", "rewritten_intent": "double each character in string `text.read()`", "snippet": "re.sub('(.)', '\\\\1\\\\1', text.read(), 0, re.S)", "question_id": 15175142 }, { "intent": "Python convert tuple to string", "rewritten_intent": "concatenate strings in tuple `('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')` into a single string", "snippet": "\"\"\"\"\"\".join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))", "question_id": 19641579 }, { "intent": "How to get full path of current file's directory in Python?", "rewritten_intent": "get full path of current directory", "snippet": "os.path.dirname(os.path.abspath(__file__))", "question_id": 3430372 }, { "intent": "variable number of digit in format string", "rewritten_intent": "variable number of digits `digits` in variable `value` in format string \"{0:.{1}%}\"", "snippet": "\"\"\"{0:.{1}%}\"\"\".format(value, digits)", "question_id": 14932247 }, { "intent": "Get current URL in Python", "rewritten_intent": "get current requested url", "snippet": "self.request.url", "question_id": 2764586 }, { "intent": "Print a variable selected by a random number", "rewritten_intent": "get a random item from list `choices`", "snippet": "random_choice = random.choice(choices)", "question_id": 30651487 }, { "intent": "Python: Sum string lengths", "rewritten_intent": "sum the length of all strings in a list `strings`", "snippet": "length = sum(len(s) for s in strings)", "question_id": 3780403 }, { "intent": "Sort a list by multiple attributes?", "rewritten_intent": "sort a list `s` by first and second attributes", "snippet": "s = sorted(s, key=lambda x: (x[1], x[2]))", "question_id": 4233476 }, { "intent": "Sort a list by multiple attributes?", "rewritten_intent": "sort a list of lists `s` by second and third element in each list.", "snippet": "s.sort(key=operator.itemgetter(1, 2))", "question_id": 4233476 }, { "intent": "How to disable query cache with mysql.connector", "rewritten_intent": "Mysql commit current transaction", "snippet": "con.commit()", "question_id": 21974169 }, { "intent": "Filtering a list of strings based on contents", "rewritten_intent": "filtering out strings that contain 'ab' from a list of strings `lst`", "snippet": "[k for k in lst if 'ab' in k]", "question_id": 2152898 }, { "intent": "How do I find the first letter of each word?", "rewritten_intent": "find the first letter of each element in string `input`", "snippet": "output = ''.join(item[0].upper() for item in input.split())", "question_id": 5775719 }, { "intent": "Get name of primary field of Django model", "rewritten_intent": "get name of primary field `name` of django model `CustomPK`", "snippet": "CustomPK._meta.pk.name", "question_id": 13418405 }, { "intent": "How to count the number of words in a sentence?", "rewritten_intent": "count the number of words in a string `s`", "snippet": "len(s.split())", "question_id": 19410018 }, { "intent": "numpy matrix vector multiplication", "rewritten_intent": "multiply array `a` and array `b`respective elements then sum each row of the new array", "snippet": "np.einsum('ji,i->j', a, b)", "question_id": 21562986 }, { "intent": "check what version of Python is running", "rewritten_intent": "check python version", "snippet": "sys.version", "question_id": 1093322 }, { "intent": "check what version of Python is running", "rewritten_intent": "check python version", "snippet": "sys.version_info", "question_id": 1093322 }, { "intent": "Format number using LaTeX notation in Python", "rewritten_intent": "format number 1000000000.0 using latex notation", "snippet": "print('\\\\num{{{0:.2g}}}'.format(1000000000.0))", "question_id": 13490292 }, { "intent": "Python initializing a list of lists", "rewritten_intent": "Initialize a list of empty lists `x` of size 3", "snippet": "x = [[] for i in range(3)]", "question_id": 12791501 }, { "intent": "How to apply django/jinja2 template filters 'escape' and 'linebreaks' correctly?", "rewritten_intent": "apply jinja2 filters `forceescape` and `linebreaks` on variable `my_variable`", "snippet": "{{my_variable | forceescape | linebreaks}}", "question_id": 4901483 }, { "intent": "Split a list of tuples into sub-lists of the same tuple field", "rewritten_intent": "zip a list of tuples `[(1, 4), (2, 5), (3, 6)]` into a list of tuples according to original tuple index", "snippet": "zip(*[(1, 4), (2, 5), (3, 6)])", "question_id": 8092877 }, { "intent": "Split a list of tuples into sub-lists of the same tuple field", "rewritten_intent": "split a list of tuples `data` into sub-lists of the same tuple field using itertools", "snippet": "[list(group) for key, group in itertools.groupby(data, operator.itemgetter(1))]", "question_id": 8092877 }, { "intent": "How can I turn a string into a list in Python?", "rewritten_intent": "Convert a string into a list", "snippet": "list('hello')", "question_id": 7522533 }, { "intent": "pandas dataframe create new columns and fill with calculated values from same df", "rewritten_intent": "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`", "snippet": "df['A_perc'] = df['A'] / df['sum']", "question_id": 18504967 }, { "intent": "Getting a list of all subdirectories in the current directory", "rewritten_intent": "getting a list of all subdirectories in the directory `directory`", "snippet": "os.walk(directory)", "question_id": 973473 }, { "intent": "Getting a list of all subdirectories in the current directory", "rewritten_intent": "get a list of all subdirectories in the directory `directory`", "snippet": "[x[0] for x in os.walk(directory)]", "question_id": 973473 }, { "intent": "How to filter a dictionary in Python?", "rewritten_intent": "update all values associated with key `i` to string 'updated' if value `j` is not equal to 'None' in dictionary `d`", "snippet": "{i: 'updated' for i, j in list(d.items()) if j != 'None'}", "question_id": 4484690 }, { "intent": "How to filter a dictionary in Python?", "rewritten_intent": "Filter a dictionary `d` to remove keys with value None and replace other values with 'updated'", "snippet": "dict((k, 'updated') for k, v in d.items() if v is None)", "question_id": 4484690 }, { "intent": "How to filter a dictionary in Python?", "rewritten_intent": "Filter a dictionary `d` to remove keys with value 'None' and replace other values with 'updated'", "snippet": "dict((k, 'updated') for k, v in d.items() if v != 'None')", "question_id": 4484690 }, { "intent": "How to count number of rows in a group in pandas group by object?", "rewritten_intent": "count number of rows in a group `key_columns` in pandas groupby object `df`", "snippet": "df.groupby(key_columns).size()", "question_id": 19384532 }, { "intent": "python sum the values of lists of list", "rewritten_intent": "return list `result` of sum of elements of each list `b` in list of lists `a`", "snippet": "result = [sum(b) for b in a]", "question_id": 13283689 }, { "intent": "What's the best way to search for a Python dictionary value in a list of dictionaries?", "rewritten_intent": "What's the best way to search for a Python dictionary value in a list of dictionaries?", "snippet": "any(d['site'] == 'Superuser' for d in data)", "question_id": 1580270 }, { "intent": "2D array of objects in Python", "rewritten_intent": "create a 2D array of `Node` objects with dimensions `cols` columns and `rows` rows", "snippet": "nodes = [[Node() for j in range(cols)] for i in range(rows)]", "question_id": 6480441 }, { "intent": "How to replace (or strip) an extension from a filename in Python?", "rewritten_intent": "replace extension '.txt' in basename '/home/user/somefile.txt' with extension '.jpg'", "snippet": "print(os.path.splitext('/home/user/somefile.txt')[0] + '.jpg')", "question_id": 3548673 }, { "intent": "How to get the resolution of a monitor in Pygame?", "rewritten_intent": "Set the resolution of a monitor as `FULLSCREEN` in pygame", "snippet": "pygame.display.set_mode((0, 0), pygame.FULLSCREEN)", "question_id": 19954469 }, { "intent": "How can I format a float using matplotlib's LaTeX formatter?", "rewritten_intent": "format float `3.5e+20` to `$3.5 \\\\times 10^{20}$` and set as title of matplotlib plot `ax`", "snippet": "ax.set_title('$%s \\\\times 10^{%s}$' % ('3.5', '+20'))", "question_id": 17306755 }, { "intent": "Print file age in seconds using Python", "rewritten_intent": "Get the age of directory (or file) `/tmp` in seconds.", "snippet": "print(os.path.getmtime('/tmp'))", "question_id": 6879364 }, { "intent": "(Django) how to get month name?", "rewritten_intent": "how to get month name of datetime `today`", "snippet": "today.strftime('%B')", "question_id": 9621388 }, { "intent": "(Django) how to get month name?", "rewritten_intent": "get month name from a datetime object `today`", "snippet": "today.strftime('%B')", "question_id": 9621388 }, { "intent": "join list of lists in python", "rewritten_intent": "Convert nested list `x` into a flat list", "snippet": "[j for i in x for j in i]", "question_id": 716477 }, { "intent": "join list of lists in python", "rewritten_intent": "get each value from a list of lists `a` using itertools", "snippet": "print(list(itertools.chain.from_iterable(a)))", "question_id": 716477 }, { "intent": "Convert Date String to Day of Week", "rewritten_intent": "convert date string 'January 11, 2010' into day of week", "snippet": "datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')", "question_id": 16766643 }, { "intent": "Convert Date String to Day of Week", "rewritten_intent": null, "snippet": "datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%a')", "question_id": 16766643 }, { "intent": "delete a list element by value", "rewritten_intent": "remove item \"b\" in list `a`", "snippet": "a.remove('b')", "question_id": 2793324 }, { "intent": "delete a list element by value", "rewritten_intent": "remove item `c` in list `a`", "snippet": "a.remove(c)", "question_id": 2793324 }, { "intent": "delete a list element by value", "rewritten_intent": "delete the element 6 from list `a`", "snippet": "a.remove(6)", "question_id": 2793324 }, { "intent": "delete a list element by value", "rewritten_intent": "delete the element 6 from list `a`", "snippet": "a.remove(6)", "question_id": 2793324 }, { "intent": "delete a list element by value", "rewritten_intent": "delete the element `c` from list `a`", "snippet": "if (c in a):\n a.remove(c)", "question_id": 2793324 }, { "intent": "delete a list element by value", "rewritten_intent": "delete the element `c` from list `a`", "snippet": "try:\n a.remove(c)\nexcept ValueError:\n pass", "question_id": 2793324 }, { "intent": "Python re.findall print all patterns", "rewritten_intent": "Get all matching patterns 'a.*?a' from a string 'a 1 a 2 a 3 a 4 a'.", "snippet": "re.findall('(?=(a.*?a))', 'a 1 a 2 a 3 a 4 a')", "question_id": 17467504 }, { "intent": "Outer product of each column of a 2D array to form a 3D array - NumPy", "rewritten_intent": "outer product of each column of a 2d `X` array to form a 3d array `X`", "snippet": "np.einsum('ij,kj->jik', X, X)", "question_id": 41469647 }, { "intent": "Getting the last element of a list", "rewritten_intent": "Getting the last element of list `some_list`", "snippet": "some_list[(-1)]", "question_id": 930397 }, { "intent": "Getting the last element of a list", "rewritten_intent": "Getting the second to last element of list `some_list`", "snippet": "some_list[(-2)]", "question_id": 930397 }, { "intent": "gets the nth-to-last element", "rewritten_intent": "gets the `n` th-to-last element in list `some_list`", "snippet": "some_list[(- n)]", "question_id": 930397 }, { "intent": "Getting the last element of a list", "rewritten_intent": "get the last element in list `alist`", "snippet": "alist[(-1)]", "question_id": 930397 }, { "intent": "Getting the last element of a list", "rewritten_intent": "get the last element in list `astr`", "snippet": "astr[(-1)]", "question_id": 930397 }, { "intent": "Create a list of integers with duplicate values in Python", "rewritten_intent": "make a list of integers from 0 to `5` where each second element is a duplicate of the previous element", "snippet": "print([u for v in [[i, i] for i in range(5)] for u in v])", "question_id": 31743603 }, { "intent": "Create a list of integers with duplicate values in Python", "rewritten_intent": "create a list of integers with duplicate values `[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]`", "snippet": "[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]", "question_id": 31743603 }, { "intent": "Create a list of integers with duplicate values in Python", "rewritten_intent": "create a list of integers from 1 to 5 with each value duplicated", "snippet": "[(i // 2) for i in range(10)]", "question_id": 31743603 }, { "intent": "Fastest way to remove first and last lines from a Python string", "rewritten_intent": "remove first and last lines of string `s`", "snippet": "s[s.find('\\n') + 1:s.rfind('\\n')]", "question_id": 28134319 }, { "intent": "Is there a Python dict without values?", "rewritten_intent": "create dict of squared int values in range of 100", "snippet": "{(x ** 2) for x in range(100)}", "question_id": 19454970 }, { "intent": "How to zip lists in a list", "rewritten_intent": "zip lists `[1, 2], [3, 4], [5, 6]` in a list", "snippet": "zip(*[[1, 2], [3, 4], [5, 6]])", "question_id": 4112265 }, { "intent": "How to zip lists in a list", "rewritten_intent": "zip lists in a list [[1, 2], [3, 4], [5, 6]]", "snippet": "zip(*[[1, 2], [3, 4], [5, 6]])", "question_id": 4112265 }, { "intent": "python http request with token", "rewritten_intent": "request page 'https://www.mysite.com/' with credentials of username 'username' and password 'pwd'", "snippet": "requests.get('https://www.mysite.com/', auth=('username', 'pwd'))", "question_id": 3355822 }, { "intent": "get a new string from the 3rd character to the end of the string", "rewritten_intent": "get a new string from the 3rd character to the end of the string `x`", "snippet": "x[2:]", "question_id": 663171 }, { "intent": "substring a string", "rewritten_intent": "get a new string including the first two characters of string `x`", "snippet": "x[:2]", "question_id": 663171 }, { "intent": "substring a string", "rewritten_intent": "get a new string including all but the last character of string `x`", "snippet": "x[:(-2)]", "question_id": 663171 }, { "intent": "substring a string", "rewritten_intent": "get a new string including the last two characters of string `x`", "snippet": "x[(-2):]", "question_id": 663171 }, { "intent": "substring a string", "rewritten_intent": "get a new string with the 3rd to the second-to-last characters of string `x`", "snippet": "x[2:(-2)]", "question_id": 663171 }, { "intent": "reversing a string", "rewritten_intent": "reverse a string `some_string`", "snippet": "some_string[::(-1)]", "question_id": 663171 }, { "intent": "selecting alternate characters", "rewritten_intent": "select alternate characters of \"H-e-l-l-o- -W-o-r-l-d\"", "snippet": "'H-e-l-l-o- -W-o-r-l-d'[::2]", "question_id": 663171 }, { "intent": "substring a string", "rewritten_intent": "select a substring of `s` beginning at `beginning` of length `LENGTH`", "snippet": "s = s[beginning:(beginning + LENGTH)]", "question_id": 663171 }, { "intent": "Terminating a Python script", "rewritten_intent": "terminate the program", "snippet": "sys.exit()", "question_id": 73663 }, { "intent": "Terminating a Python script", "rewritten_intent": "terminate the program", "snippet": "quit()", "question_id": 73663 }, { "intent": "Terminating a Python script", "rewritten_intent": "Terminating a Python script with error message \"some error message\"", "snippet": "sys.exit('some error message')", "question_id": 73663 }, { "intent": "Transform unicode string in python", "rewritten_intent": "encode value of key `City` in dictionary `data` as `ascii`, ignoring non-ascii characters", "snippet": "data['City'].encode('ascii', 'ignore')", "question_id": 10264618 }, { "intent": "get current CPU and RAM usage", "rewritten_intent": "get current CPU and RAM usage", "snippet": "psutil.cpu_percent()\npsutil.virtual_memory()", "question_id": 276052 }, { "intent": "get current CPU and RAM usage", "rewritten_intent": "get current RAM usage of current program", "snippet": "pid = os.getpid()\npy = psutil.Process(pid)\nmemoryUse = (py.memory_info()[0] / (2.0 ** 30))", "question_id": 276052 }, { "intent": "get current CPU and RAM usage", "rewritten_intent": "print cpu and memory usage", "snippet": "print((psutil.cpu_percent()))\nprint((psutil.virtual_memory()))", "question_id": 276052 }, { "intent": "Pandas read_csv expects wrong number of columns, with ragged csv file", "rewritten_intent": "read a ragged csv file `D:/Temp/tt.csv` using `names` parameter in pandas", "snippet": "pd.read_csv('D:/Temp/tt.csv', names=list('abcdef'))", "question_id": 20154303 }, { "intent": "First non-null value per row from a list of Pandas columns", "rewritten_intent": "get first non-null value per each row from dataframe `df`", "snippet": "df.stack().groupby(level=0).first()", "question_id": 31828240 }, { "intent": "format strings and named arguments in Python", "rewritten_intent": "print two numbers `10` and `20` using string formatting", "snippet": "\"\"\"{0} {1}\"\"\".format(10, 20)", "question_id": 17895835 }, { "intent": "format strings and named arguments in Python", "rewritten_intent": "replace placeholders in string '{1} {ham} {0} {foo} {1}' with arguments `(10, 20, foo='bar', ham='spam')`", "snippet": "\"\"\"{1} {ham} {0} {foo} {1}\"\"\".format(10, 20, foo='bar', ham='spam')", "question_id": 17895835 }, { "intent": "How to convert strings numbers to integers in a list?", "rewritten_intent": "create list `changed_list ` containing elements of list `original_list` whilst converting strings containing digits to integers", "snippet": "changed_list = [(int(f) if f.isdigit() else f) for f in original_list]", "question_id": 818949 }, { "intent": "Add items to a dictionary of lists", "rewritten_intent": "get a dictionary with keys from one list `keys` and values from other list `data`", "snippet": "dict(zip(keys, zip(*data)))", "question_id": 11613284 }, { "intent": "Python: Converting from ISO-8859-1/latin1 to UTF-8", "rewritten_intent": "convert string `apple` from iso-8859-1/latin1 to utf-8", "snippet": "apple.decode('iso-8859-1').encode('utf8')", "question_id": 6539881 }, { "intent": "How do you remove the column name row from a pandas DataFrame?", "rewritten_intent": "Exclude column names when writing dataframe `df` to a csv file `filename.csv`", "snippet": "df.to_csv('filename.csv', header=False)", "question_id": 19781609 }, { "intent": "how to get around \"Single '}' encountered in format string\" when using .format and formatting in printing", "rewritten_intent": "Escape character '}' in string '{0}:<15}}{1}:<15}}{2}:<8}}' while using function `format` with arguments `('1', '2', '3')`", "snippet": "print('{0}:<15}}{1}:<15}}{2}:<8}}'.format('1', '2', '3'))", "question_id": 9079540 }, { "intent": "Python list of dicts, get max value index", "rewritten_intent": "get dictionary with max value of key 'size' in list of dicts `ld`", "snippet": "max(ld, key=lambda d: d['size'])", "question_id": 30546889 }, { "intent": "Format() in Python Regex", "rewritten_intent": "format parameters 'b' and 'a' into plcaeholders in string \"{0}\\\\w{{2}}b{1}\\\\w{{2}}quarter\"", "snippet": "\"\"\"{0}\\\\w{{2}}b{1}\\\\w{{2}}quarter\"\"\".format('b', 'a')", "question_id": 18609153 }, { "intent": "How to use 'User' as foreign key in Django 1.5", "rewritten_intent": "django create a foreign key column `user` and link it to table 'User'", "snippet": "user = models.ForeignKey('User', unique=True)", "question_id": 19433630 }, { "intent": "Regex match even number of letters", "rewritten_intent": "write a regex pattern to match even number of letter `A`", "snippet": "re.compile('^([^A]*)AA([^A]|AA)*$')", "question_id": 2045175 }, { "intent": "Combining NumPy arrays", "rewritten_intent": "join Numpy array `b` with Numpy array 'a' along axis 0", "snippet": "b = np.concatenate((a, a), axis=0)", "question_id": 6740311 }, { "intent": "How to custom sort an alphanumeric list?", "rewritten_intent": "custom sort an alphanumeric list `l`", "snippet": "sorted(l, key=lambda x: x.replace('0', 'Z'))", "question_id": 41894454 }, { "intent": "Plot logarithmic axes with matplotlib in python", "rewritten_intent": "plot logarithmic axes with matplotlib", "snippet": "ax.set_yscale('log')", "question_id": 773814 }, { "intent": "Access environment variables", "rewritten_intent": "Access environment variable \"HOME\"", "snippet": "os.environ['HOME']", "question_id": 4906977 }, { "intent": "Access environment variables", "rewritten_intent": "get value of environment variable \"HOME\"", "snippet": "os.environ['HOME']", "question_id": 4906977 }, { "intent": "Access environment variables", "rewritten_intent": "print all environment variables", "snippet": "print(os.environ)", "question_id": 4906977 }, { "intent": "Access environment variables", "rewritten_intent": "get all environment variables", "snippet": "os.environ", "question_id": 4906977 }, { "intent": "Access environment variables", "rewritten_intent": "get value of the environment variable 'KEY_THAT_MIGHT_EXIST'", "snippet": "print(os.environ.get('KEY_THAT_MIGHT_EXIST'))", "question_id": 4906977 }, { "intent": "Access environment variables", "rewritten_intent": "get value of the environment variable 'KEY_THAT_MIGHT_EXIST' with default value `default_value`", "snippet": "print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))", "question_id": 4906977 }, { "intent": "Access environment variables", "rewritten_intent": "get value of the environment variable 'HOME' with default value '/home/username/'", "snippet": "print(os.environ.get('HOME', '/home/username/'))", "question_id": 4906977 }, { "intent": "How to split a string within a list to create key-value pairs in Python", "rewritten_intent": "create a dictionary containing each string in list `my_list` split by '=' as a key/value pairs", "snippet": "print(dict([s.split('=') for s in my_list]))", "question_id": 12739911 }, { "intent": "finding index of an item closest to the value in a list that's not entirely sorted", "rewritten_intent": "find the index of element closest to number 11.5 in list `a`", "snippet": "min(enumerate(a), key=lambda x: abs(x[1] - 11.5))", "question_id": 9706041 }, { "intent": "How to use lxml to find an element by text?", "rewritten_intent": "find element `a` that contains string \"TEXT A\" in file `root`", "snippet": "e = root.xpath('.//a[contains(text(),\"TEXT A\")]')", "question_id": 14299978 }, { "intent": "How to use lxml to find an element by text?", "rewritten_intent": "Find the`a` tag in html `root` which starts with the text `TEXT A` and assign it to `e`", "snippet": "e = root.xpath('.//a[starts-with(text(),\"TEXT A\")]')", "question_id": 14299978 }, { "intent": "How to use lxml to find an element by text?", "rewritten_intent": "find the element that holds string 'TEXT A' in file `root`", "snippet": "e = root.xpath('.//a[text()=\"TEXT A\"]')", "question_id": 14299978 }, { "intent": "Python: an efficient way to slice a list with a index list", "rewritten_intent": "create list `c` containing items from list `b` whose index is in list `index`", "snippet": "c = [b[i] for i in index]", "question_id": 12768504 }, { "intent": "Multiplication of 1d arrays in numpy", "rewritten_intent": "get the dot product of two one dimensional numpy arrays", "snippet": "np.dot(a[:, (None)], b[(None), :])", "question_id": 23566515 }, { "intent": "Multiplication of 1d arrays in numpy", "rewritten_intent": "multiplication of two 1-dimensional arrays in numpy", "snippet": "np.outer(a, b)", "question_id": 23566515 }, { "intent": "Execute a file with arguments in Python shell", "rewritten_intent": "execute a file './abc.py' with arguments `arg1` and `arg2` in python shell", "snippet": "subprocess.call(['./abc.py', arg1, arg2])", "question_id": 5788891 }, { "intent": "Pandas: Fill missing values by mean in each group faster than transfrom", "rewritten_intent": "Replace NaN values in column 'value' with the mean of data in column 'group' of dataframe `df`", "snippet": "df[['value']].fillna(df.groupby('group').transform('mean'))", "question_id": 40682209 }, { "intent": "Python regex alternative for join", "rewritten_intent": "separate each character in string `s` by '-'", "snippet": "re.sub('(.)(?=.)', '\\\\1-', s)", "question_id": 27457970 }, { "intent": "Python regex alternative for join", "rewritten_intent": "concatenate '-' in between characters of string `str`", "snippet": "re.sub('(?<=.)(?=.)', '-', str)", "question_id": 27457970 }, { "intent": "Index of element in Numpy array", "rewritten_intent": "get the indexes of the x and y axes in Numpy array `np` where variable `a` is equal to variable `value`", "snippet": "i, j = np.where(a == value)", "question_id": 18079029 }, { "intent": "Finding the most frequent character in a string", "rewritten_intent": "print letter that appears most frequently in string `s`", "snippet": "print(collections.Counter(s).most_common(1)[0])", "question_id": 4131123 }, { "intent": "How to match beginning of string or character in Python", "rewritten_intent": "find float number proceeding sub-string `par` in string `dir`", "snippet": "float(re.findall('(?:^|_)' + par + '(\\\\d+\\\\.\\\\d*)', dir)[0])", "question_id": 12211944 }, { "intent": "How to match beginning of string or character in Python", "rewritten_intent": "Get all the matches from a string `abcd` if it begins with a character `a`", "snippet": "re.findall('[^a]', 'abcd')", "question_id": 12211944 }, { "intent": "How to get a list of variables in specific Python module?", "rewritten_intent": "get a list of variables from module 'adfix.py' in current module.", "snippet": "print([item for item in dir(adfix) if not item.startswith('__')])", "question_id": 9759820 }, { "intent": "Get the first element of each tuple in a list in Python", "rewritten_intent": "get the first element of each tuple in a list `rows`", "snippet": "[x[0] for x in rows]", "question_id": 22412258 }, { "intent": "Get the first element of each tuple in a list in Python", "rewritten_intent": "get a list `res_list` of the first elements of each tuple in a list of tuples `rows`", "snippet": "res_list = [x[0] for x in rows]", "question_id": 22412258 }, { "intent": "How to repeat Pandas data frame?", "rewritten_intent": "duplicate data in pandas dataframe `x` for 5 times", "snippet": "pd.concat([x] * 5, ignore_index=True)", "question_id": 23887881 }, { "intent": "How to repeat Pandas data frame?", "rewritten_intent": "Get a repeated pandas data frame object `x` by `5` times", "snippet": "pd.concat([x] * 5)", "question_id": 23887881 }, { "intent": "Sorting JSON in python by a specific value", "rewritten_intent": "sort json `ips_data` by a key 'data_two'", "snippet": "sorted_list_of_keyvalues = sorted(list(ips_data.items()), key=item[1]['data_two'])", "question_id": 34148637 }, { "intent": "JSON to pandas DataFrame", "rewritten_intent": "read json `elevations` to pandas dataframe `df`", "snippet": "pd.read_json(elevations)", "question_id": 21104592 }, { "intent": "Generate random numbers with a given (numerical) distribution", "rewritten_intent": "generate a random number in 1 to 7 with a given distribution [0.1, 0.05, 0.05, 0.2, 0.4, 0.2]", "snippet": "numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])", "question_id": 4265988 }, { "intent": "Find maximum value of a column and return the corresponding row values using Pandas", "rewritten_intent": "Return rows of data associated with the maximum value of column 'Value' in dataframe `df`", "snippet": "df.loc[df['Value'].idxmax()]", "question_id": 15741759 }, { "intent": "Finding recurring patterns in a string", "rewritten_intent": "find recurring patterns in a string '42344343434'", "snippet": "re.findall('^(.+?)((.+)\\\\3+)$', '42344343434')[0][:-1]", "question_id": 11303238 }, { "intent": "convert binary string to numpy array", "rewritten_intent": "convert binary string '\\x00\\x00\\x80?\\x00\\x00\\x00@\\x00\\x00@@\\x00\\x00\\x80@' to numpy array", "snippet": "np.fromstring('\\x00\\x00\\x80?\\x00\\x00\\x00@\\x00\\x00@@\\x00\\x00\\x80@', dtype='...', vf, vf)", "question_id": 19863964 }, { "intent": "Simple URL GET/POST function", "rewritten_intent": "request http url `url`", "snippet": "r = requests.get(url)", "question_id": 4476373 }, { "intent": "Simple URL GET/POST function", "rewritten_intent": "request http url `url` with parameters `payload`", "snippet": "r = requests.get(url, params=payload)", "question_id": 4476373 }, { "intent": "Simple URL GET/POST function", "rewritten_intent": "post request url `url` with parameters `payload`", "snippet": "r = requests.post(url, data=payload)", "question_id": 4476373 }, { "intent": "Simple URL GET/POST", "rewritten_intent": "make an HTTP post request with data `post_data`", "snippet": "post_response = requests.post(url='http://httpbin.org/post', json=post_data)", "question_id": 4476373 }, { "intent": "Slicing a list in Django template", "rewritten_intent": "django jinja slice list `mylist` by '3:8'", "snippet": "{{(mylist | slice): '3:8'}}", "question_id": 23422542 }, { "intent": "pandas HDFStore - how to reopen?", "rewritten_intent": "create dataframe `df` with content of hdf store file '/home/.../data.h5' with key of 'firstSet'", "snippet": "df1 = pd.read_hdf('/home/.../data.h5', 'firstSet')", "question_id": 14591855 }, { "intent": "find last occurence of multiple characters in a string in Python", "rewritten_intent": "get the largest index of the last occurrence of characters '([{' in string `test_string`", "snippet": "max(test_string.rfind(i) for i in '([{')", "question_id": 31950612 }, { "intent": "How to print Unicode character in Python?", "rewritten_intent": "print 'here is your checkmark: ' plus unicode character u'\\u2713'", "snippet": "print('here is your checkmark: ' + '\\u2713')", "question_id": 10569438 }, { "intent": "How to print Unicode character in Python?", "rewritten_intent": "print unicode characters in a string `\\u0420\\u043e\\u0441\\u0441\\u0438\\u044f`", "snippet": "print('\\u0420\\u043e\\u0441\\u0441\\u0438\\u044f')", "question_id": 10569438 }, { "intent": "in python how do I convert a single digit number into a double digits string?", "rewritten_intent": "pads string '5' on the left with 1 zero", "snippet": "print('{0}'.format('5'.zfill(2)))", "question_id": 3505831 }, { "intent": "Best / most pythonic way to get an ordered list of unique items", "rewritten_intent": "Remove duplicates elements from list `sequences` and sort it in ascending order", "snippet": "sorted(set(itertools.chain.from_iterable(sequences)))", "question_id": 7458689 }, { "intent": "Pandas DataFrame to list", "rewritten_intent": "pandas dataframe `df` column 'a' to list", "snippet": "df['a'].values.tolist()", "question_id": 23748995 }, { "intent": "Pandas DataFrame to list", "rewritten_intent": "Get a list of all values in column `a` in pandas data frame `df`", "snippet": "df['a'].tolist()", "question_id": 23748995 }, { "intent": "Escaping quotes in string", "rewritten_intent": "escaping quotes in string", "snippet": "replace('\"', '\\\\\"')", "question_id": 6275762 }, { "intent": "How to check if a character is upper-case in Python?", "rewritten_intent": "check if all string elements in list `words` are upper-cased", "snippet": "print(all(word[0].isupper() for word in words))", "question_id": 3668964 }, { "intent": "What is the best way to remove a dictionary item by value in python?", "rewritten_intent": "remove items from dictionary `myDict` if the item's value `val` is equal to 42", "snippet": "myDict = {key: val for key, val in list(myDict.items()) if val != 42}", "question_id": 29218750 }, { "intent": "What is the best way to remove a dictionary item by value in python?", "rewritten_intent": "Remove all items from a dictionary `myDict` whose values are `42`", "snippet": "{key: val for key, val in list(myDict.items()) if val != 42}", "question_id": 29218750 }, { "intent": "How can I determine the byte length of a utf-8 encoded string in Python?", "rewritten_intent": "Determine the byte length of a utf-8 encoded string `s`", "snippet": "return len(s.encode('utf-8'))", "question_id": 6714826 }, { "intent": "In Python 2.5, how do I kill a subprocess?", "rewritten_intent": "kill a process with id `process.pid`", "snippet": "os.kill(process.pid, signal.SIGKILL)", "question_id": 1064335 }, { "intent": "Python Pandas How to select rows with one or more nulls from a DataFrame without listing columns explicitly?", "rewritten_intent": "get data of columns with Null values in dataframe `df`", "snippet": "df[pd.isnull(df).any(axis=1)]", "question_id": 14247586 }, { "intent": "Strip random characters from url", "rewritten_intent": "strip everything up to and including the character `&` from url `url`, strip the character `=` from the remaining string and concatenate `.html` to the end", "snippet": "url.split('&')[-1].replace('=', '') + '.html'", "question_id": 41133414 }, { "intent": "Expat parsing in python 3", "rewritten_intent": "Parse a file `sample.xml` using expat parsing in python 3", "snippet": "parser.ParseFile(open('sample.xml', 'rb'))", "question_id": 1179305 }, { "intent": "how do I halt execution in a python script?", "rewritten_intent": "Exit script", "snippet": "sys.exit()", "question_id": 3376534 }, { "intent": "How to dynamically assign values to class properties in Python?", "rewritten_intent": "assign value in `group` dynamically to class property `attr`", "snippet": "setattr(self, attr, group)", "question_id": 19153328 }, { "intent": "How to decode a 'url-encoded' string in python", "rewritten_intent": "decode url-encoded string `some_string` to its character equivalents", "snippet": "urllib.parse.unquote(urllib.parse.unquote(some_string))", "question_id": 28431359 }, { "intent": "How to decode a 'url-encoded' string in python", "rewritten_intent": "decode a double URL encoded string \r\n'FireShot3%2B%25282%2529.png' to\r\n'FireShot3+(2).png'", "snippet": "urllib.parse.unquote(urllib.parse.unquote('FireShot3%2B%25282%2529.png'))", "question_id": 28431359 }, { "intent": "How to use Flask-Security register view?", "rewritten_intent": "change flask security register url to `/create_account`", "snippet": "app.config['SECURITY_REGISTER_URL'] = '/create_account'", "question_id": 14793098 }, { "intent": "IO Error while storing data in pickle", "rewritten_intent": "open a file `/home/user/test/wsservice/data.pkl` in binary write mode", "snippet": "output = open('/home/user/test/wsservice/data.pkl', 'wb')", "question_id": 5285181 }, { "intent": "remove an element from a list by index", "rewritten_intent": "remove the last element in list `a`", "snippet": "del a[(-1)]", "question_id": 627435 }, { "intent": "remove an element from a list by index", "rewritten_intent": "remove the element in list `a` with index 1", "snippet": "a.pop(1)", "question_id": 627435 }, { "intent": "remove an element from a list by index", "rewritten_intent": "remove the last element in list `a`", "snippet": "a.pop()", "question_id": 627435 }, { "intent": "remove an element from a list by index", "rewritten_intent": "remove the element in list `a` at index `index`", "snippet": "a.pop(index)", "question_id": 627435 }, { "intent": "remove an element from a list by index", "rewritten_intent": "remove the element in list `a` at index `index`", "snippet": "del a[index]", "question_id": 627435 }, { "intent": "How do I print a Celsius symbol with matplotlib?", "rewritten_intent": "print a celsius symbol on x axis of a plot `ax`", "snippet": "ax.set_xlabel('Temperature (\\u2103)')", "question_id": 8440117 }, { "intent": "How do I print a Celsius symbol with matplotlib?", "rewritten_intent": "Print a celsius symbol with matplotlib", "snippet": "ax.set_xlabel('Temperature ($^\\\\circ$C)')", "question_id": 8440117 }, { "intent": "'List of lists' to 'list' without losing empty lists from the original list of lists", "rewritten_intent": "convert a list of lists `list_of_lists` into a list of strings keeping empty sub-lists as empty string ''", "snippet": "[''.join(l) for l in list_of_lists]", "question_id": 18022241 }, { "intent": "How do I get a list of all the duplicate items using pandas in python?", "rewritten_intent": "get a list of all the duplicate items in dataframe `df` using pandas", "snippet": "pd.concat(g for _, g in df.groupby('ID') if len(g) > 1)", "question_id": 14657241 }, { "intent": "deleting rows in numpy array", "rewritten_intent": "Delete third row in a numpy array `x`", "snippet": "x = numpy.delete(x, 2, axis=1)", "question_id": 3877491 }, { "intent": "deleting rows in numpy array", "rewritten_intent": "delete first row of array `x`", "snippet": "x = numpy.delete(x, 0, axis=0)", "question_id": 3877491 }, { "intent": "Merge DataFrames in Pandas using the mean", "rewritten_intent": "merge rows from dataframe `df1` with rows from dataframe `df2` and calculate the mean for rows that have the same value of axis 1", "snippet": "pd.concat((df1, df2), axis=1).mean(axis=1)", "question_id": 19490064 }, { "intent": "Average values in two Numpy arrays", "rewritten_intent": "Get the average values from two numpy arrays `old_set` and `new_set`", "snippet": "np.mean(np.array([old_set, new_set]), axis=0)", "question_id": 18461623 }, { "intent": "Changing marker's size in matplotlib", "rewritten_intent": "Matplotlib change marker size to 500", "snippet": "scatter(x, y, s=500, color='green', marker='h')", "question_id": 19948732 }, { "intent": "split items in list", "rewritten_intent": "Create new list `result` by splitting each item in list `words`", "snippet": "result = [item for word in words for item in word.split(',')]", "question_id": 12808420 }, { "intent": "Converting JSON date string to python datetime", "rewritten_intent": "convert JSON string '2012-05-29T19:30:03.283Z' into a DateTime object using format '%Y-%m-%dT%H:%M:%S.%fZ'", "snippet": "datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')", "question_id": 10805589 }, { "intent": "python comprehension loop for dictionary", "rewritten_intent": "count `True` values associated with key 'one' in dictionary `tadas`", "snippet": "sum(item['one'] for item in list(tadas.values()))", "question_id": 35561743 }, { "intent": "How to base64 encode a PDF file in Python", "rewritten_intent": "encode a pdf file `pdf_reference.pdf` with `base64` encoding", "snippet": "a = open('pdf_reference.pdf', 'rb').read().encode('base64')", "question_id": 208894 }, { "intent": "split a string in python", "rewritten_intent": "split string `a` using new-line character '\\n' as separator", "snippet": "a.rstrip().split('\\n')", "question_id": 2094176 }, { "intent": "split a string in python", "rewritten_intent": "split a string `a` with new line character", "snippet": "a.split('\\n')[:-1]", "question_id": 2094176 }, { "intent": "How can I return HTTP status code 204 from a Django view?", "rewritten_intent": "return http status code 204 from a django view", "snippet": "return HttpResponse(status=204)", "question_id": 12476452 }, { "intent": "check if a value exist in a list", "rewritten_intent": "check if 7 is in `a`", "snippet": "(7 in a)", "question_id": 7571635 }, { "intent": "check if a value exist in a list", "rewritten_intent": "check if 'a' is in list `a`", "snippet": "('a' in a)", "question_id": 7571635 }, { "intent": "Sorting JSON data by keys value", "rewritten_intent": "sort list `results` by keys value 'year'", "snippet": "sorted(results, key=itemgetter('year'))", "question_id": 13438574 }, { "intent": "How do I get current URL in Selenium Webdriver 2 Python?", "rewritten_intent": "get current url in selenium webdriver `browser`", "snippet": "print(browser.current_url)", "question_id": 15985339 }, { "intent": "Python: Split string with multiple delimiters", "rewritten_intent": "split string `str` with delimiter '; ' or delimiter ', '", "snippet": "re.split('; |, ', str)", "question_id": 4998629 }, { "intent": "Unescaping Characters in a String with Python", "rewritten_intent": "un-escaping characters in a string with python", "snippet": "\"\"\"\\\\u003Cp\\\\u003E\"\"\".decode('unicode-escape')", "question_id": 5555063 }, { "intent": "Convert string date to timestamp in Python", "rewritten_intent": "convert date string `s` in format pattern '%d/%m/%Y' into a timestamp", "snippet": "time.mktime(datetime.datetime.strptime(s, '%d/%m/%Y').timetuple())", "question_id": 9637838 }, { "intent": "Convert string date to timestamp in Python", "rewritten_intent": "convert string '01/12/2011' to an integer timestamp", "snippet": "int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime('%s'))", "question_id": 9637838 }, { "intent": "How to get http headers in flask?", "rewritten_intent": "get http header of the key 'your-header-name' in flask", "snippet": "request.headers['your-header-name']", "question_id": 29386995 }, { "intent": "How to subset a data frame using Pandas based on a group criteria?", "rewritten_intent": "select records of dataframe `df` where the sum of column 'X' for each value in column 'User' is 0", "snippet": "df.groupby('User')['X'].filter(lambda x: x.sum() == 0)", "question_id": 27868020 }, { "intent": "How to subset a data frame using Pandas based on a group criteria?", "rewritten_intent": "Get data of dataframe `df` where the sum of column 'X' grouped by column 'User' is equal to 0", "snippet": "df.loc[df.groupby('User')['X'].transform(sum) == 0]", "question_id": 27868020 }, { "intent": "How to subset a data frame using Pandas based on a group criteria?", "rewritten_intent": "Get data from dataframe `df` where column 'X' is equal to 0", "snippet": "df.groupby('User')['X'].transform(sum) == 0", "question_id": 27868020 }, { "intent": "How do I find an element that contains specific text in Selenium Webdriver (Python)?", "rewritten_intent": null, "snippet": "driver.find_elements_by_xpath(\"//*[contains(text(), 'My Button')]\")", "question_id": 12323403 }, { "intent": "Convert pandas group by object to multi-indexed Dataframe", "rewritten_intent": "convert pandas group by object to multi-indexed dataframe with indices 'Name' and 'Destination'", "snippet": "df.set_index(['Name', 'Destination'])", "question_id": 14301913 }, { "intent": "How do I coalesce a sequence of identical characters into just one?", "rewritten_intent": "coalesce non-word-characters in string `a`", "snippet": "print(re.sub('(\\\\W)\\\\1+', '\\\\1', a))", "question_id": 2813829 }, { "intent": "How to open a file with the standard application?", "rewritten_intent": "open a file \"$file\" under Unix", "snippet": "os.system('start \"$file\"')", "question_id": 1679798 }, { "intent": "Convert a Unicode string to a string", "rewritten_intent": "Convert a Unicode string `title` to a 'ascii' string", "snippet": "unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')", "question_id": 1207457 }, { "intent": "Convert a Unicode string to a string", "rewritten_intent": "Convert a Unicode string `a` to a 'ascii' string", "snippet": "a.encode('ascii', 'ignore')", "question_id": 1207457 }, { "intent": "Get a filtered list of files in a directory", "rewritten_intent": "create a list `files` containing all files in directory '.' that starts with numbers between 0 and 9 and ends with the extension '.jpg'", "snippet": "files = [f for f in os.listdir('.') if re.match('[0-9]+.*\\\\.jpg', f)]", "question_id": 2225564 }, { "intent": "Adding a 1-D Array to a 3-D array in Numpy", "rewritten_intent": "adding a 1-d array `[1, 2, 3, 4, 5, 6, 7, 8, 9]` to a 3-d array `np.zeros((6, 9, 20))`", "snippet": "np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])[(None), :, (None)]", "question_id": 32283692 }, { "intent": "Adding a 1-D Array to a 3-D array in Numpy", "rewritten_intent": "add array of shape `(6, 9, 20)` to array `[1, 2, 3, 4, 5, 6, 7, 8, 9]`", "snippet": "np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]).reshape((1, 9, 1))", "question_id": 32283692 }, { "intent": "How can I launch an instance of an application using Python?", "rewritten_intent": null, "snippet": "os.system('start excel.exe ')", "question_id": 247724 }, { "intent": "What is the proper way to print a nested list with the highest value in Python", "rewritten_intent": "get the list with the highest sum value in list `x`", "snippet": "print(max(x, key=sum))", "question_id": 29760130 }, { "intent": "Functional statement in Python to return the sum of certain lists in a list of lists", "rewritten_intent": "sum the length of lists in list `x` that are more than 1 item in length", "snippet": "sum(len(y) for y in x if len(y) > 1)", "question_id": 35707224 }, { "intent": "Python - Insert numbers in string between quotes", "rewritten_intent": "Enclose numbers in quotes in a string `This is number 1 and this is number 22`", "snippet": "re.sub('(\\\\d+)', '\"\\\\1\"', 'This is number 1 and this is number 22')", "question_id": 42364992 }, { "intent": "Multiplying Rows and Columns of Python Sparse Matrix by elements in an Array", "rewritten_intent": "multiply the columns of sparse matrix `m` by array `a` then multiply the rows of the resulting matrix by array `a`", "snippet": "numpy.dot(numpy.dot(a, m), a)", "question_id": 13163145 }, { "intent": "How to check if something exists in a postgresql database using django?", "rewritten_intent": "Django check if an object with criteria `name` equal to 'name' and criteria `title` equal to 'title' exists in model `Entry`", "snippet": "Entry.objects.filter(name='name', title='title').exists()", "question_id": 9561243 }, { "intent": "Sort a nested list by two elements", "rewritten_intent": "sort a nested list by the inverse of element 2, then by element 1", "snippet": "sorted(l, key=lambda x: (-int(x[1]), x[0]))", "question_id": 34705205 }, { "intent": "Django - How to simply get domain name?", "rewritten_intent": "get domain/host name from request object in Django", "snippet": "request.META['HTTP_HOST']", "question_id": 29945684 }, { "intent": "Python Regex Get String Between Two Substrings", "rewritten_intent": "get a string `randomkey123xyz987` between two substrings in a string `api('randomkey123xyz987', 'key', 'text')` using regex", "snippet": "re.findall(\"api\\\\('(.*?)'\", \"api('randomkey123xyz987', 'key', 'text')\")", "question_id": 29703793 }, { "intent": "Call Perl script from Python", "rewritten_intent": "invoke perl script './uireplace.pl' using perl interpeter '/usr/bin/perl' and send argument `var` to it", "snippet": "subprocess.call(['/usr/bin/perl', './uireplace.pl', var])", "question_id": 4682088 }, { "intent": "Pythonic way to print list items", "rewritten_intent": "print list of items `myList`", "snippet": "print('\\n'.join(str(p) for p in myList))", "question_id": 15769246 }, { "intent": "update dictionary with dynamic keys and values in python", "rewritten_intent": "update the dictionary `mydic` with dynamic keys `i` and values with key 'name' from dictionary `o`", "snippet": "mydic.update({i: o['name']})", "question_id": 13860026 }, { "intent": "how to split a unicode string into list", "rewritten_intent": "split a `utf-8` encoded string `stru` into a list of characters", "snippet": "list(stru.decode('utf-8'))", "question_id": 18711384 }, { "intent": "Convert UTF-8 with BOM to UTF-8 with no BOM in Python", "rewritten_intent": "convert utf-8 with bom string `s` to utf-8 with no bom `u`", "snippet": "u = s.decode('utf-8-sig')", "question_id": 8898294 }, { "intent": "How do I do a not equal in Django queryset filtering?", "rewritten_intent": "Filter model 'Entry' where 'id' is not equal to 3 in Django", "snippet": "Entry.objects.filter(~Q(id=3))", "question_id": 687295 }, { "intent": "How can I lookup an attribute in any scope by name?", "rewritten_intent": "lookup an attribute in any scope by name 'range'", "snippet": "getattr(__builtins__, 'range')", "question_id": 2850966 }, { "intent": "How to make a python script which can logoff, shutdown, and restart a computer?", "rewritten_intent": "restart a computer after `900` seconds using subprocess", "snippet": "subprocess.call(['shutdown', '/r', '/t', '900'])", "question_id": 14764126 }, { "intent": "How to make a python script which can logoff, shutdown, and restart a computer?", "rewritten_intent": "shutdown a computer using subprocess", "snippet": "subprocess.call(['shutdown', '/s'])", "question_id": 14764126 }, { "intent": "How to make a python script which can logoff, shutdown, and restart a computer?", "rewritten_intent": "abort a computer shutdown using subprocess", "snippet": "subprocess.call(['shutdown', '/a '])", "question_id": 14764126 }, { "intent": "How to make a python script which can logoff, shutdown, and restart a computer?", "rewritten_intent": "logoff computer having windows operating system using python", "snippet": "subprocess.call(['shutdown', '/l '])", "question_id": 14764126 }, { "intent": "How to make a python script which can logoff, shutdown, and restart a computer?", "rewritten_intent": "shutdown and restart a computer running windows from script", "snippet": "subprocess.call(['shutdown', '/r'])", "question_id": 14764126 }, { "intent": "How to erase the file contents of text file in Python?", "rewritten_intent": "erase the contents of a file `filename`", "snippet": "open('filename', 'w').close()", "question_id": 2769061 }, { "intent": "How to erase the file contents of text file in Python?", "rewritten_intent": null, "snippet": "open('file.txt', 'w').close()", "question_id": 2769061 }, { "intent": "Pandas DataFrame to List of Dictionaries", "rewritten_intent": "convert dataframe `df` to list of dictionaries including the index values", "snippet": "df.to_dict('index')", "question_id": 29815129 }, { "intent": "Pandas DataFrame to List of Dictionaries", "rewritten_intent": "Create list of dictionaries from pandas dataframe `df`", "snippet": "df.to_dict('records')", "question_id": 29815129 }, { "intent": "pandas dataframe groupby datetime month", "rewritten_intent": "Group a pandas data frame by monthly frequenct `M` using groupby", "snippet": "df.groupby(pd.TimeGrouper(freq='M'))", "question_id": 24082784 }, { "intent": "How do I divide the members of a list by the corresponding members of another list in Python?", "rewritten_intent": "divide the members of a list `conversions` by the corresponding members of another list `trials`", "snippet": "[(c / t) for c, t in zip(conversions, trials)]", "question_id": 3731426 }, { "intent": "sort dict by value python", "rewritten_intent": "sort dict `data` by value", "snippet": "sorted(data, key=data.get)", "question_id": 16772071 }, { "intent": "sort dict by value python", "rewritten_intent": "Sort a dictionary `data` by its values", "snippet": "sorted(data.values())", "question_id": 16772071 }, { "intent": "sort dict by value python", "rewritten_intent": "Get a list of pairs of key-value sorted by values in dictionary `data`", "snippet": "sorted(list(data.items()), key=lambda x: x[1])", "question_id": 16772071 }, { "intent": "sort dict by value python", "rewritten_intent": null, "snippet": "sorted(list(data.items()), key=lambda x: x[1])", "question_id": 16772071 }, { "intent": "How do I display current time using Python + Django?", "rewritten_intent": "display current time", "snippet": "now = datetime.datetime.now().strftime('%H:%M:%S')", "question_id": 5110352 }, { "intent": "Find the nth occurrence of substring in a string", "rewritten_intent": "find the index of the second occurrence of the substring `bar` in string `foo bar bar bar`", "snippet": "\"\"\"foo bar bar bar\"\"\".replace('bar', 'XXX', 1).find('bar')", "question_id": 1883980 }, { "intent": "How do you check the presence of many keys in a Python dictinary?", "rewritten_intent": "check if key 'stackoverflow' and key 'google' are presented in dictionary `sites`", "snippet": "set(['stackoverflow', 'google']).issubset(sites)", "question_id": 2813806 }, { "intent": "Replace part of a string in Python?", "rewritten_intent": "replace string ' and ' in string `stuff` with character '/'", "snippet": "stuff.replace(' and ', '/')", "question_id": 10037742 }, { "intent": "How to use `numpy.savez` in a loop for save more than one array?", "rewritten_intent": "Save array at index 0, index 1 and index 8 of array `np` to tmp file `tmp`", "snippet": "np.savez(tmp, *[getarray[0], getarray[1], getarray[8]])", "question_id": 22712292 }, { "intent": "time offset", "rewritten_intent": "substract 1 hour and 10 minutes from current time", "snippet": "t = datetime.datetime.now()\n(t - datetime.timedelta(hours=1, minutes=10))", "question_id": 14043934 }, { "intent": "time offset", "rewritten_intent": "subtract 1 hour and 10 minutes from time object `t`", "snippet": "(t - datetime.timedelta(hours=1, minutes=10))", "question_id": 14043934 }, { "intent": "time offset", "rewritten_intent": "add 1 hour and 2 minutes to time object `t`", "snippet": "dt = datetime.datetime.combine(datetime.date.today(), t)", "question_id": 14043934 }, { "intent": "time offset", "rewritten_intent": "subtract 5 hours from the time object `dt`", "snippet": "dt -= datetime.timedelta(hours=5)", "question_id": 14043934 }, { "intent": "Manipulating binary data in Python", "rewritten_intent": "encode string `data` using hex 'hex' encoding", "snippet": "print(data.encode('hex'))", "question_id": 3059301 }, { "intent": "Manipulating binary data in Python", "rewritten_intent": "Return the decimal value for each hex character in data `data`", "snippet": "print(' '.join([str(ord(a)) for a in data]))", "question_id": 3059301 }, { "intent": "python - iterating over a subset of a list of tuples", "rewritten_intent": "Get all the items from a list of tuple 'l' where second item in tuple is '1'.", "snippet": "[x for x in l if x[1] == 1]", "question_id": 18131367 }, { "intent": "How to read stdin to a 2d python array of integers?", "rewritten_intent": "Create array `a` containing integers from stdin", "snippet": "a.fromlist([int(val) for val in stdin.read().split()])", "question_id": 8192379 }, { "intent": "Is there a way to refer to the entire matched expression in re.sub without the use of a group?", "rewritten_intent": "place '\\' infront of each non-letter char in string `line`", "snippet": "print(re.sub('[_%^$]', '\\\\\\\\\\\\g<0>', line))", "question_id": 26155985 }, { "intent": "How to use regular expression in lxml xpath?", "rewritten_intent": "Get all `a` tags where the text starts with value `some text` using regex", "snippet": "doc.xpath(\"//a[starts-with(text(),'some text')]\")", "question_id": 2755950 }, { "intent": "Compare elements of a list of lists and return a list", "rewritten_intent": "convert a list of lists `a` into list of tuples of appropriate elements form nested lists", "snippet": "zip(*a)", "question_id": 35017035 }, { "intent": "Convert list of strings to int", "rewritten_intent": "convert a list of strings `lst` to list of integers", "snippet": "[map(int, sublist) for sublist in lst]", "question_id": 34696853 }, { "intent": "Convert list of strings to int", "rewritten_intent": "convert strings in list-of-lists `lst` to ints", "snippet": "[[int(x) for x in sublist] for sublist in lst]", "question_id": 34696853 }, { "intent": "Numpy: find index of elements in one array that occur in another array", "rewritten_intent": "get index of elements in array `A` that occur in another array `B`", "snippet": "np.where(np.in1d(A, B))[0]", "question_id": 28901311 }, { "intent": "Split dictionary of lists into list of dictionaries", "rewritten_intent": "create a list where each element is a dictionary with keys 'key1' and 'key2' and values corresponding to each value in the lists referenced by keys 'key1' and 'key2' in dictionary `d`", "snippet": "[{'key1': a, 'key2': b} for a, b in zip(d['key1'], d['key2'])]", "question_id": 1780174 }, { "intent": "Split dictionary of lists into list of dictionaries", "rewritten_intent": null, "snippet": "map(dict, zip(*[[(k, v) for v in value] for k, value in list(d.items())]))", "question_id": 1780174 }, { "intent": "Get Last Day of the Month", "rewritten_intent": "Get Last Day of the first month in 2002", "snippet": "calendar.monthrange(2002, 1)", "question_id": 42950 }, { "intent": "Get Last Day of the Month", "rewritten_intent": "Get Last Day of the second month in 2002", "snippet": "calendar.monthrange(2008, 2)", "question_id": 42950 }, { "intent": "Get Last Day of the Month", "rewritten_intent": "Get Last Day of the second month in 2100", "snippet": "calendar.monthrange(2100, 2)", "question_id": 42950 }, { "intent": "Get Last Day of the Month", "rewritten_intent": "Get Last Day of the month `month` in year `year`", "snippet": "calendar.monthrange(year, month)[1]", "question_id": 42950 }, { "intent": "Get Last Day of the Month", "rewritten_intent": "Get Last Day of the second month in year 2012", "snippet": "monthrange(2012, 2)", "question_id": 42950 }, { "intent": "Get Last Day of the Month", "rewritten_intent": "Get Last Day of the first month in year 2000", "snippet": "(datetime.date(2000, 2, 1) - datetime.timedelta(days=1))", "question_id": 42950 }, { "intent": "Calling an external command", "rewritten_intent": "Calling an external command \"ls -l\"", "snippet": "from subprocess import call", "question_id": 89228 }, { "intent": "Calling an external command", "rewritten_intent": "Calling an external command \"some_command with args\"", "snippet": "os.system('some_command with args')", "question_id": 89228 }, { "intent": "Calling an external command", "rewritten_intent": "Calling an external command \"some_command < input_file | another_command > output_file\"", "snippet": "os.system('some_command < input_file | another_command > output_file')", "question_id": 89228 }, { "intent": "Calling an external command", "rewritten_intent": "Calling an external command \"some_command with args\"", "snippet": "stream = os.popen('some_command with args')", "question_id": 89228 }, { "intent": "Calling an external command", "rewritten_intent": "Calling an external command \"echo Hello World\"", "snippet": "print(subprocess.Popen('echo Hello World', shell=True, stdout=subprocess.PIPE).stdout.read())", "question_id": 89228 }, { "intent": "Calling an external command", "rewritten_intent": "Calling an external command \"echo Hello World\"", "snippet": "print(os.popen('echo Hello World').read())", "question_id": 89228 }, { "intent": "Calling an external command", "rewritten_intent": "Calling an external command \"echo Hello World\"", "snippet": "return_code = subprocess.call('echo Hello World', shell=True)", "question_id": 89228 }, { "intent": "Calling an external command", "rewritten_intent": "Calling an external command \"ls\"", "snippet": "p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\nfor line in p.stdout.readlines():\n print(line, end=' ')\nretval = p.wait()", "question_id": 89228 }, { "intent": "Calling an external command", "rewritten_intent": "Calling an external command \"ls -l\"", "snippet": "call(['ls', '-l'])", "question_id": 89228 }, { "intent": "Url decode UTF-8 in Python", "rewritten_intent": "decode url `url` with utf8 and print it", "snippet": "print(urllib.parse.unquote(url).decode('utf8'))", "question_id": 16566069 }, { "intent": "Url decode UTF-8 in Python", "rewritten_intent": "decode a urllib escaped url string `url` with `utf8`", "snippet": "url = urllib.parse.unquote(url).decode('utf8')", "question_id": 16566069 }, { "intent": "Delete letters from string", "rewritten_intent": "delete letters from string '12454v'", "snippet": "\"\"\"\"\"\".join(filter(str.isdigit, '12454v'))", "question_id": 14750675 }, { "intent": "applying regex to a pandas dataframe", "rewritten_intent": "Update row values for a column `Season` using vectorized string operation in pandas", "snippet": "df['Season'].str.split('-').str[0].astype(int)", "question_id": 25292838 }, { "intent": "Sort tuples based on second parameter", "rewritten_intent": "sort a list of tuples `my_list` by second parameter in the tuple", "snippet": "my_list.sort(key=lambda x: x[1])", "question_id": 8459231 }, { "intent": "Find all occurrences of a substring in Python", "rewritten_intent": "find indexes of all occurrences of a substring `tt` in a string `ttt`", "snippet": "[m.start() for m in re.finditer('(?=tt)', 'ttt')]", "question_id": 4664850 }, { "intent": "Find all occurrences of a substring in Python", "rewritten_intent": "find all occurrences of a substring in a string", "snippet": "[m.start() for m in re.finditer('test', 'test test test test')]", "question_id": 4664850 }, { "intent": "re.split with spaces in python", "rewritten_intent": "split string `s` based on white spaces", "snippet": "re.findall('\\\\s+|\\\\S+', s)", "question_id": 35005907 }, { "intent": "Working with set_index in Pandas DataFrame", "rewritten_intent": "set columns `['race_date', 'track_code', 'race_number']` as indexes in dataframe `rdata`", "snippet": "rdata.set_index(['race_date', 'track_code', 'race_number'])", "question_id": 18071222 }, { "intent": "recursively go through all subdirectories and read files", "rewritten_intent": "recursively go through all subdirectories and files in `rootdir`", "snippet": "for (root, subFolders, files) in os.walk(rootdir):\n pass", "question_id": 13571134 }, { "intent": "sorting a list of dictionary values by date in python", "rewritten_intent": "sort a list of dictionary values by 'date' in reverse order", "snippet": "list.sort(key=lambda item: item['date'], reverse=True)", "question_id": 652291 }, { "intent": "How to truncate a string using str.format in Python?", "rewritten_intent": "display first 5 characters of string 'aaabbbccc'", "snippet": "\"\"\"{:.5}\"\"\".format('aaabbbccc')", "question_id": 24076297 }, { "intent": "How do I convert a string of hexadecimal values to a list of integers?", "rewritten_intent": "unpack hexadecimal string `s` to a list of integer values", "snippet": "struct.unpack('11B', s)", "question_id": 14961562 }, { "intent": "Finding the index of an item given a list containing it in Python", "rewritten_intent": "finding the index of an item 'foo' given a list `['foo', 'bar', 'baz']` containing it", "snippet": "[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'foo']", "question_id": 176918 }, { "intent": "How to generate all permutations of a list in Python", "rewritten_intent": "generate all permutations of list `[1, 2, 3]` and list `[4, 5, 6]`", "snippet": "print(list(itertools.product([1, 2, 3], [4, 5, 6])))", "question_id": 104420 }, { "intent": "How to generate all permutations of a list in Python", "rewritten_intent": "generate all permutations of a list `[1, 2, 3]`", "snippet": "itertools.permutations([1, 2, 3])", "question_id": 104420 }, { "intent": "Remove punctuation from Unicode formatted strings", "rewritten_intent": "substitute occurrences of unicode regex pattern u'\\\\p{P}+' with empty string '' in string `text`", "snippet": "return re.sub('\\\\p{P}+', '', text)", "question_id": 11066400 }, { "intent": "manually throw/raise an exception", "rewritten_intent": "manually throw/raise a `ValueError` exception with the message 'A very specific bad thing happened'", "snippet": "raise ValueError('A very specific bad thing happened')", "question_id": 2052390 }, { "intent": "Manually raising (throwing) an exception", "rewritten_intent": "throw an exception \"I know Python!\"", "snippet": "raise Exception('I know Python!')", "question_id": 2052390 }, { "intent": "Manually raising (throwing) an exception", "rewritten_intent": "Manually throw an exception \"I know python!\"", "snippet": "raise Exception('I know python!')", "question_id": 2052390 }, { "intent": "Manually raising (throwing) an exception", "rewritten_intent": "throw a ValueError with message 'represents a hidden bug, do not catch this'", "snippet": "raise ValueError('represents a hidden bug, do not catch this')", "question_id": 2052390 }, { "intent": "Manually raising (throwing) an exception", "rewritten_intent": "throw an Exception with message 'This is the exception you expect to handle'", "snippet": "raise Exception('This is the exception you expect to handle')", "question_id": 2052390 }, { "intent": "Manually raising (throwing) an exception", "rewritten_intent": "throw a value error with message 'A very specific bad thing happened', 'foo', 'bar', 'baz'", "snippet": "raise ValueError('A very specific bad thing happened')", "question_id": 2052390 }, { "intent": "Manually raising (throwing) an exception", "rewritten_intent": "throw a runtime error with message 'specific message'", "snippet": "raise RuntimeError('specific message')", "question_id": 2052390 }, { "intent": "Manually raising (throwing) an exception", "rewritten_intent": "throw an assertion error with message \"Unexpected value of 'distance'!\", distance", "snippet": "raise AssertionError(\"Unexpected value of 'distance'!\", distance)", "question_id": 2052390 }, { "intent": "Clear text from textarea with selenium", "rewritten_intent": "if Selenium textarea element `foo` is not empty, clear the field", "snippet": "driver.find_element_by_id('foo').clear()", "question_id": 7732125 }, { "intent": "Clear text from textarea with selenium", "rewritten_intent": "clear text from textarea 'foo' with selenium", "snippet": "driver.find_element_by_id('foo').clear()", "question_id": 7732125 }, { "intent": "Convert an IP string to a number and vice versa", "rewritten_intent": "convert a number 2130706433 to ip string", "snippet": "socket.inet_ntoa(struct.pack('!L', 2130706433))", "question_id": 9590965 }, { "intent": "How to rearrange Pandas column sequence?", "rewritten_intent": "Rearrange the columns 'a','b','x','y' of pandas DataFrame `df` in mentioned sequence 'x' ,'y','a' ,'b'", "snippet": "df = df[['x', 'y', 'a', 'b']]", "question_id": 12329853 }, { "intent": "How to call Base Class's __init__ method from the child class?", "rewritten_intent": "call base class's __init__ method from the child class `ChildClass`", "snippet": "super(ChildClass, self).__init__(*args, **kwargs)", "question_id": 19205916 }, { "intent": "Sum of all values in a Python dict", "rewritten_intent": "sum of all values in a python dict `d`", "snippet": "sum(d.values())", "question_id": 4880960 }, { "intent": "Sum of all values in a Python dict", "rewritten_intent": null, "snippet": "sum(d.values())", "question_id": 4880960 }, { "intent": "Convert Python dictionary to JSON array", "rewritten_intent": "convert python dictionary `your_data` to json array", "snippet": "json.dumps(your_data, ensure_ascii=False)", "question_id": 14661051 }, { "intent": "numpy array assignment using slicing", "rewritten_intent": "assign an array of floats in range from 0 to 100 to a variable `values`", "snippet": "values = np.array([i for i in range(100)], dtype=np.float64)", "question_id": 23638638 }, { "intent": "Sort a list of dictionary provided an order", "rewritten_intent": "sort a list of dictionaries `list_of_dct` by values in an order `order`", "snippet": "sorted(list_of_dct, key=lambda x: order.index(list(x.values())[0]))", "question_id": 35078261 }, { "intent": "how to change the case of first letter of a string?", "rewritten_intent": "change the case of the first letter in string `s`", "snippet": "return s[0].upper() + s[1:]", "question_id": 4223923 }, { "intent": "how to change [1,2,3,4] to '1234' using python", "rewritten_intent": "join list of numbers `[1,2,3,4] ` to string of numbers.", "snippet": "\"\"\"\"\"\".join([1, 2, 3, 4])", "question_id": 2597932 }, { "intent": "Delete every non utf-8 symbols froms string", "rewritten_intent": "delete every non `utf-8` characters from a string `line`", "snippet": "line = line.decode('utf-8', 'ignore').encode('utf-8')", "question_id": 26541968 }, { "intent": "How to execute a command in the terminal from a Python script?", "rewritten_intent": "execute a command `command ` in the terminal from a python script", "snippet": "os.system(command)", "question_id": 33065588 }, { "intent": "Python MySQL Parameterized Queries", "rewritten_intent": "MySQL execute query 'SELECT * FROM foo WHERE bar = %s AND baz = %s' with parameters `param1` and `param2`", "snippet": "c.execute('SELECT * FROM foo WHERE bar = %s AND baz = %s', (param1, param2))", "question_id": 775296 }, { "intent": "Convert a string to datetime object in python", "rewritten_intent": "Parse string `datestr` into a datetime object using format pattern '%Y-%m-%d'", "snippet": "dateobj = datetime.datetime.strptime(datestr, '%Y-%m-%d').date()", "question_id": 5868374 } ]