question_id int64 1.48k 42.2M | intent stringlengths 11 91 | rewritten_intent stringlengths 11 135 ⌀ | snippet stringlengths 8 164 |
|---|---|---|---|
977,491 | Comparing two .txt files using difflib in Python | compare contents at filehandles `file1` and `file2` using difflib | difflib.SequenceMatcher(None, file1.read(), file2.read()) |
33,065,588 | How to execute a command in the terminal from a Python script? | execute a command `command ` in the terminal from a python script | os.system(command) |
4,484,690 | How to filter a dictionary in Python? | Filter a dictionary `d` to remove keys with value None and replace other values with 'updated' | dict((k, 'updated') for k, v in d.items() if v is None) |
9,573,244 | check if the string is empty | check if string `my_string` is empty | if some_string:
pass |
663,171 | substring a string | select a substring of `s` beginning at `beginning` of length `LENGTH` | s = s[beginning:(beginning + LENGTH)] |
25,040,875 | Get a list of values from a list of dictionaries in python | get a list of values with key 'key' from a list of dictionaries `l` | [d['key'] for d in l if 'key' in d] |
7,270,321 | Finding the index of elements based on a condition using python list comprehension | Get all indexes of a list `a` where each value is greater than `2` | [i for i in range(len(a)) if a[i] > 2] |
974,678 | How to create single Python dict from a list of dicts by summing values with common keys? | create a flat dictionary by summing values associated with similar keys in each dictionary of list `dictlist` | dict((key, sum(d[key] for d in dictList)) for key in dictList[0]) |
14,961,014 | Removing items from unnamed lists in Python | Remove the string value `item` from a list of strings `my_sequence` | [item for item in my_sequence if item != 'item'] |
38,379,453 | How to read only part of a list of strings in python | get a list of substrings consisting of the first 5 characters of every string in list `buckets` | [s[:5] for s in buckets] |
42,098,487 | How to split 1D array into 2D array in NumPy by splitting the array at the last element? | split 1d array `a` into 2d array at the last element | np.split(a, [-1]) |
940,822 | Regular expression syntax for "match nothing"? | regular expression match nothing | re.compile('$^') |
20,025,882 | Append string to the start of each value in a said column of a pandas dataframe (elegantly) | append string 'str' at the beginning of each value in column 'col' of dataframe `df` | df['col'] = 'str' + df['col'].astype(str) |
14,295,673 | Convert string into datetime.time object | Convert string '03:55' into datetime.time object | datetime.datetime.strptime('03:55', '%H:%M').time() |
20,375,561 | Joining pandas dataframes by column names | Join pandas data frame `frame_1` and `frame_2` with left join by `county_ID` and right join by `countyid` | pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid') |
10,543,303 | number of values in a list greater than a certain number | get the number of values in list `j` that is greater than 5 | sum(((i > 5) for i in j)) |
17,071,871 | Select rows from a DataFrame based on values in a column in pandas | Select rows whose value of the "B" column is "one" or "three" in the DataFrame `df` | print(df.loc[df['B'].isin(['one', 'three'])]) |
319,426 | case insensitive string comparison | case insensitive comparison of strings `string1` and `string2` | if (string1.lower() == string2.lower()):
print('The strings are the same (case insensitive)')
else:
print('The strings are not the same (case insensitive)') |
2,231,663 | Slicing a list into a list of sub-lists | null | [input[i:i + n] for i in range(0, len(input), n)] |
18,071,222 | Working with set_index in Pandas DataFrame | set columns `['race_date', 'track_code', 'race_number']` as indexes in dataframe `rdata` | rdata.set_index(['race_date', 'track_code', 'race_number']) |
5,826,427 | Can a python script execute a function inside a bash script? | null | subprocess.Popen(['bash', '-c', '. foo.sh; go']) |
14,661,701 | How to drop a list of rows from Pandas dataframe? | drop rows whose index value in list `[1, 3]` in dataframe `df` | df.drop(df.index[[1, 3]], inplace=True) |
8,936,030 | Using BeautifulSoup to search html for string | BeautifulSoup find string 'Python Jobs' in HTML body `body` | soup.body.findAll(text='Python Jobs') |
21,684,346 | How to display a pdf that has been downloaded in python | display a pdf file that has been downloaded as `my_pdf.pdf` | webbrowser.open('file:///my_pdf.pdf') |
17,952,279 | Logarithmic y-axis bins in python | plot a data logarithmically in y axis | plt.yscale('log', nonposy='clip') |
10,973,614 | Convert JSON array to Python list | Convert JSON array `array` to Python object | data = json.loads(array) |
761,804 | Trimming a string | Trimming a string " Hello " | ' Hello '.strip() |
27,175,400 | How to find the index of a value in 2d array in Python? | find all the indexes in a Numpy 2D array where the value is 1 | zip(*np.where(a == 1)) |
24,082,784 | pandas dataframe groupby datetime month | Group a pandas data frame by monthly frequenct `M` using groupby | df.groupby(pd.TimeGrouper(freq='M')) |
42,211,584 | How do I compare values in a dictionary? | get the maximum of 'salary' and 'bonus' values in a dictionary | print(max(d, key=lambda x: (d[x]['salary'], d[x]['bonus']))) |
3,804,727 | python, subprocess: reading output from subprocess | flush output of python print | sys.stdout.flush() |
18,397,805 | How do I delete a row in a numpy array which contains a zero? | delete all rows in a numpy array `a` where any value in a row is zero `0` | a[np.all(a != 0, axis=1)] |
1,854 | What OS am I running on | get os name | import platform
platform.system() |
19,961,490 | Construct pandas DataFrame from list of tuples | construct pandas dataframe from a list of tuples | df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std']) |
42,142,756 | How can I change a specific row label in a Pandas dataframe? | rename `last` row index label in dataframe `df` to `a` | df = df.rename(index={last: 'a'}) |
3,899,980 | How to change the font size on a matplotlib plot | change the font size on plot `matplotlib` to 22 | matplotlib.rcParams.update({'font.size': 22}) |
40,498,088 | List comprehension - converting strings in one list, to integers in another | get list of sums of neighboring integers in string `example` | [sum(map(int, s)) for s in example.split()] |
2,231,663 | Slicing a list into a list of sub-lists | get a list of tuples of every three consecutive items in list `[1, 2, 3, 4, 5, 6, 7, 8, 9]` | list(zip(*((iter([1, 2, 3, 4, 5, 6, 7, 8, 9]),) * 3))) |
8,344,905 | Pythons fastest way of randomising case of a string | randomly switch letters' cases in string `s` | """""".join(x.upper() if random.randint(0, 1) else x for x in s) |
237,079 | get file creation & modification date/times in | get modified time of file `file` | time.ctime(os.path.getmtime(file)) |
2,514,961 | Remove all values within one list from another list in python | remove all values within one list `[2, 3, 7]` from another list `a` | [x for x in a if x not in [2, 3, 7]] |
2,424,412 | What is the easiest way to convert list with str into list with int? | convert list with str into list with int | list(map(int, ['1', '2', '3'])) |
663,171 | substring a string | get a new string including all but the last character of string `x` | x[:(-2)] |
13,295,735 | How can I replace all the NaN values with Zero's in a column of a pandas dataframe | replace all the nan values with 0 in a pandas dataframe `df` | df.fillna(0) |
2,052,390 | manually throw/raise an exception | manually throw/raise a `ValueError` exception with the message 'A very specific bad thing happened' | raise ValueError('A very specific bad thing happened') |
31,029,560 | Plotting categorical data with pandas and matplotlib | plot a bar graph from the column 'color' in the DataFrame 'df' | df.colour.value_counts().plot(kind='bar') |
4,906,977 | Access environment variables | get value of the environment variable 'KEY_THAT_MIGHT_EXIST' with default value `default_value` | print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value)) |
16,568,056 | Python Nested List Comprehension with two Lists | create a list of aggregation of each element from list `l2` to all elements of list `l1` | [(x + y) for x in l2 for y in l1] |
29,471,884 | Get the immediate minimum among a list of numbers in python | get the next value greatest to `2` from a list of numbers `num_list` | min([x for x in num_list if x > 2]) |
21,164,910 | Delete Column in Pandas based on Condition | delete all columns in DataFrame `df` that do not hold a non-zero value in its records | df.loc[:, ((df != 0).any(axis=0))] |
3,847,472 | get index of character in python list | get index of character 'b' in list '['a', 'b']' | ['a', 'b'].index('b') |
3,277,503 | read a file line by line into a list | read file `fname` line by line into a list `content` | with open(fname) as f:
content = f.readlines() |
1,299,855 | upload file with Python Mechanize | null | br.form.add_file(open(filename), 'text/plain', filename) |
19,205,916 | How to call Base Class's __init__ method from the child class? | call base class's __init__ method from the child class `ChildClass` | super(ChildClass, self).__init__(*args, **kwargs) |
22,904,654 | How to save Xlsxwriter file in certain path? | save xlsxwriter file to 'C:/Users/Steven/Documents/demo.xlsx' path | workbook = xlsxwriter.Workbook('C:/Users/Steven/Documents/demo.xlsx') |
18,116,235 | Removing letters from a list of both numbers and letters | Get only digits from a string `strs` | """""".join([c for c in strs if c.isdigit()]) |
22,741,068 | How do I remove identical items from a list and sort it in Python? | remove identical items from list `my_list` and sort it alphabetically | sorted(set(my_list)) |
14,931,769 | get all combination of n binary value | get all combination of n binary values | lst = list(itertools.product([0, 1], repeat=n)) |
13,223,737 | how to read a file in other directory in python | open file '5_1.txt' in directory `direct` | x_file = open(os.path.join(direct, '5_1.txt'), 'r') |
6,480,441 | 2D array of objects in Python | create a 2D array of `Node` objects with dimensions `cols` columns and `rows` rows | nodes = [[Node() for j in range(cols)] for i in range(rows)] |
15,096,021 | Python list of tuples to list of int | Flatten list `x` | x = [i[0] for i in x] |
1,476 | express binary literals | convert binary string '010101' to integer | int('010101', 2) |
9,652,832 | How to I load a tsv file into a Pandas DataFrame? | load a tsv file `c:/~/trainSetRel3.txt` into a pandas data frame | DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t') |
20,477,190 | Get top biggest values from each column of the pandas.DataFrame | get biggest 3 values from each column of the pandas dataframe `data` | data.apply(lambda x: sorted(x, 3)) |
2,045,175 | Regex match even number of letters | write a regex pattern to match even number of letter `A` | re.compile('^([^A]*)AA([^A]|AA)*$') |
17,141,558 | How to sort a dataFrame in python pandas by two or more columns? | sort dataframe `df` based on column 'a' in ascending and column 'b' in descending | df.sort_values(['a', 'b'], ascending=[True, False]) |
931,092 | Reverse a string | Reverse list `s` | s[::(-1)] |
5,826,427 | Can a python script execute a function inside a bash script? | call a function `otherfunc` inside a bash script `test.sh` using subprocess | subprocess.call('test.sh otherfunc') |
34,015,615 | Python reversing an UTF-8 string | reverse a UTF-8 string 'a' | b = a.decode('utf8')[::-1].encode('utf8') |
14,041,791 | print variable and a string in python | Print a string `card` with string formatting | print('I have: {0.price}'.format(card)) |
10,565,598 | Numpy: How to check if array contains certain numbers? | check if array `b` contains all elements of array `a` | numpy.in1d(b, a).all() |
9,505,526 | Split string into strings of repeating elements | split string `s` into strings of repeating elements | print([a for a, b in re.findall('((\\w)\\2*)', s)]) |
510,348 | make a time delay | delay for "5" seconds | time.sleep(5) |
17,109,608 | change figure size and figure format in matplotlib | change figure size to 3 by 4 in matplotlib | plt.figure(figsize=(3, 4)) |
2,225,564 | Get a filtered list of files in a directory | create a list `files` containing all files in directory '.' that starts with numbers between 0 and 9 and ends with the extension '.jpg' | files = [f for f in os.listdir('.') if re.match('[0-9]+.*\\.jpg', f)] |
3,328,012 | How can I tell if a file is a descendant of a given directory? | check if file `filename` is descendant of directory '/the/dir/' | os.path.commonprefix(['/the/dir/', os.path.realpath(filename)]) == '/the/dir/' |
674,519 | How can I convert a Python dictionary to a list of tuples? | convert a python dictionary `d` to a list of tuples | [(v, k) for k, v in list(d.items())] |
15,183,084 | how to create a dictionary using two lists in python? | create a dictionary using two lists`x` and `y` | dict(zip(x, y)) |
16,374,540 | Efficient way to convert a list to dictionary | Convert a list `['A:1', 'B:2', 'C:3', 'D:4']` to dictionary | dict(map(lambda s: s.split(':'), ['A:1', 'B:2', 'C:3', 'D:4'])) |
36,139 | How do I sort a list of strings in Python? | sort list `mylist` in alphabetical order | mylist.sort(key=str.lower) |
13,252,333 | Python check if all elements of a list are the same type | Check if all elements in list `lst` are tupples of long and int | all(isinstance(x, int) for x in lst) |
16,739,319 | Selenium Webdriver - NoSuchElementExceptions | selenium wait for driver `driver` 60 seconds before throwing a NoSuchElementExceptions exception | driver.implicitly_wait(60) |
23,748,995 | Pandas DataFrame to list | pandas dataframe `df` column 'a' to list | df['a'].values.tolist() |
2,168,123 | Converting a String to List in Python | split string "0,1,2" based on delimiter ',' | """0,1,2""".split(',') |
817,122 | Delete digits in Python (Regex) | delete digits at the end of string `s` | re.sub('\\b\\d+\\b', '', s) |
4,241,757 | Python/Django: How to remove extra white spaces & tabs from a string? | remove extra white spaces & tabs from a string `s` | """ """.join(s.split()) |
14,764,126 | How to make a python script which can logoff, shutdown, and restart a computer? | shutdown and restart a computer running windows from script | subprocess.call(['shutdown', '/r']) |
16,099,694 | How to remove empty string in a list? | get a list `cleaned` that contains all non-empty elements in list `your_list` | cleaned = [x for x in your_list if x] |
7,996,940 | What is the best way to sort list with custom sorting parameters in Python? | null | li1.sort(key=lambda x: not x.startswith('b.')) |
4,476,373 | Simple URL GET/POST | make an HTTP post request with data `post_data` | post_response = requests.post(url='http://httpbin.org/post', json=post_data) |
19,490,064 | Merge DataFrames in Pandas using the mean | merge rows from dataframe `df1` with rows from dataframe `df2` and calculate the mean for rows that have the same value of axis 1 | pd.concat((df1, df2), axis=1).mean(axis=1) |
38,147,447 | How to remove square bracket from pandas dataframe | get element at index 0 of each list in column 'value' of dataframe `df` | df['value'] = df['value'].str.get(0) |
186,857 | Splitting a semicolon-separated string to a dictionary, in Python | split a string `s` by ';' and convert to a dictionary | dict(item.split('=') for item in s.split(';')) |
3,437,059 | string contains substring | check if string "substring" is in string | string.find('substring') |
123,198 | copy a file | copy a file from `src` to `dst` | copyfile(src, dst) |
41,894,454 | How to custom sort an alphanumeric list? | custom sort an alphanumeric list `l` | sorted(l, key=lambda x: x.replace('0', 'Z')) |
8,249,836 | how to get all possible combination of items from 2-dimensional list in python? | get all possible combination of items from 2-dimensional list `a` | list(itertools.product(*a)) |
187,455 | Counting array elements in Python | count the number of elements in array `myArray` | len(myArray) |
40,384,599 | Sorting a list of tuples by the addition of second and third element of the tuple | sorting a list of tuples `lst` by the sum of the second elements onwards, and third element of the tuple | sorted(lst, key=lambda x: (sum(x[1:]), x[0])) |
11,573,817 | How to download a file via FTP with Python ftplib | null | ftp.retrbinary('RETR %s' % filename, file.write) |
README.md exists but content is empty.
- Downloads last month
- 10