text
stringlengths
4
1.08k
How can I remove text within parentheses with a regex?,"re.sub('\\([^)]*\\)', '', filename)"
How can I tell if a string only contains letter AND spaces,"""""""a b"""""".replace(' ', '').isalpha()"
Add SUM of values of two LISTS into new LIST,"[(x + y) for x, y in zip(first, second)]"
How to sort a Python dictionary by value?,"sorted(list(a_dict.items()), key=lambda item: item[1][1])"
How to exclude a character from a regex group?,re.compile('[^a-zA-Z0-9-]+')
Get index of the top n values of a list in python,"sorted(list(range(len(a))), key=lambda i: a[i])[-2:]"
Get index of the top n values of a list in python,"zip(*sorted(enumerate(a), key=operator.itemgetter(1)))[0][-2:]"
Get index of the top n values of a list in python,"sorted(list(range(len(a))), key=lambda i: a[i], reverse=True)[:2]"
How to get the index with the key in Python dictionary?,list(x.keys()).index('c')
"How to print +1 in Python, as +1 (with plus sign) instead of 1?",print('{0:+d}'.format(score))
Remove adjacent duplicate elements from a list,"[k for k, g in itertools.groupby([1, 2, 2, 3, 2, 2, 4])]"
Converting a String to List in Python,"""""""0,1,2"""""".split(',')"
Converting a String to List in Python,"[int(x) for x in '0,1,2'.split(',')]"
Python: Convert list of key-value tuples into dictionary?,"dict([('A', 1), ('B', 2), ('C', 3)])"
How to write a multidimensional array to a text file?,"np.savetxt('test.txt', x)"
How to store os.system() output in a variable or a list in python,"direct_output = subprocess.check_output('ls', shell=True)"
Select everything but a list of columns from pandas dataframe,df[df.columns - ['T1_V6']]
How to count values in a certain range in a Numpy array?,((25 < a) & (a < 100)).sum()
how to get day name in datetime in python,date.today().strftime('%A')
Python regular expression match whole word,"re.search('\\bis\\b', your_string)"
Python: How do I format a date in Jinja2?,{{car.date_of_manufacture | datetime}}
Python: How do I format a date in Jinja2?,{{car.date_of_manufacture.strftime('%Y-%m-%d')}}
Making a flat list out of list of lists,[item for sublist in l for item in sublist]
Making a flat list out of list of lists,list(itertools.chain(*list2d))
Making a flat list out of list of lists,list(itertools.chain.from_iterable(list2d))
Convert int to ASCII and back in Python,ord('a')
Python: use regular expression to remove the white space from all lines,"re.sub('(?m)^[^\\S\\n]+', '', ' a\n b\n c\nd e')"
Python: use regular expression to remove the white space from all lines,"re.sub('(?m)^\\s+', '', 'a\n b\n c')"
Python: Assign each element of a List to a separate Variable,"a, b, c = [1, 2, 3]"
Python split a list into subsets based on pattern,"[list(v) for k, v in itertools.groupby(mylist, key=lambda x: x[:5])]"
Regular expression substitution in Python,"line = re.sub('\\(+as .*?\\) ', '', line)"
How to skip the extra newline while printing lines read from a file?,print(line.rstrip('\n'))
Get index values of Pandas DataFrame as list?,df.index.values.tolist()
check if a list is empty,"if (not a):
pass"
check if a list is empty,"if (not seq):
pass"
check if a list is empty,"if (len(li) == 0):
pass"
Find the indices of elements greater than x,"[i for i, v in enumerate(a) if v > 4]"
sorting list of nested dictionaries in python,"sorted(yourdata, reverse=True)"
sorting list of nested dictionaries in python,"sorted(yourdata, key=lambda d: d.get('key', {}).get('subkey'), reverse=True)"
sorting list of nested dictionaries in python,"yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)"
How to remove decimal points in pandas,df.round()
How to extract data from matplotlib plot,gca().get_lines()[n].get_xydata()
How to get the N maximum values per row in a numpy ndarray?,"A[:, -2:]"
MultiValueDictKeyError in Django,"request.GET.get('username', '')"
Any way to properly pretty-print ordered dictionaries in Python?,pprint(dict(list(o.items())))
Django can't find URL pattern,"url('^$', include('sms.urls')),"
Django can't find URL pattern,"url('^', include('sms.urls')),"
Pythonic way to get the largest item in a list,"max_item = max(a_list, key=operator.itemgetter(1))"
Pythonic way to get the largest item in a list,"max(a_list, key=operator.itemgetter(1))"
How to iterate over time periods in pandas,"s.resample('3M', how='sum')"
how to extract elements from a list in python?,"[a[i] for i in (1, 2, 5)]"
Python: Filter lines from a text file which contain a particular word,[line for line in open('textfile') if 'apple' in line]
How to convert a Date string to a DateTime object?,"datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')"
"Reading tab-delimited file with Pandas - works on Windows, but not on Mac","pandas.read_csv(filename, sep='\t', lineterminator='\r')"
Replace first occurence of string,"'longlongTESTstringTEST'.replace('TEST', '?', 1)"
How can I zip file with a flattened directory structure using Zipfile in Python?,"archive.write(pdffile, os.path.basename(pdffile))"
"Elegant way to create a dictionary of pairs, from a list of tuples?",dict(x[1:] for x in reversed(myListOfTuples))
How to subtract two lists in python,"[(x1 - x2) for x1, x2 in zip(List1, List2)]"
How to tell if string starts with a number?,string[0].isdigit()
How to tell if string starts with a number?,"strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))"
How can I find script's directory with Python?,print(os.path.dirname(os.path.realpath(__file__)))
Finding the surrounding sentence of a char/word in a string,"re.split('(?<=\\?|!|\\.)\\s{0,2}(?=[A-Z]|$)', text)"
"Plotting a list of (x, y) coordinates in python matplotlib",plt.scatter(*zip(*li))
Rearrange tuple of tuples in Python,tuple(zip(*t))
Find Average of Every Three Columns in Pandas dataframe,"df.groupby(np.arange(len(df.columns)) // 3, axis=1).mean()"
How do I convert a list of ascii values to a string in python?,""""""""""""".join(chr(i) for i in L)"
Python 2.7 Counting number of dictionary items with given value,sum(x == chosen_value for x in list(d.values()))
Python 2.7 Counting number of dictionary items with given value,sum(1 for x in list(d.values()) if some_condition(x))
convert double to float in Python,"struct.unpack('f', struct.pack('f', 0.00582811585976))"
Converting datetime.date to UTC timestamp in Python,"timestamp = (dt - datetime(1970, 1, 1)).total_seconds()"
Custom sorting in pandas dataframe,df.sort('m')
How to sort with lambda in Python,"a = sorted(a, key=lambda x: x.modified, reverse=True)"
How can I print the Truth value of a variable?,print(bool(a))
How can I change a specific row label in a Pandas dataframe?,df = df.rename(index={last: 'a'})
Scikit-learn: How to run KMeans on a one-dimensional array?,"km.fit(x.reshape(-1, 1))"
sorting a list in python,"sorted(words, key=lambda x: 'a' + x if x.startswith('s') else 'b' + x)"
login to a site using python and opening the login site in the browser,webbrowser.open('http://somesite.com/adminpanel/index.php')
"Pythonic way to fetch all elements in a dictionary, falling between two keys?","dict((k, v) for k, v in parent_dict.items() if 2 < k < 4)"
"Pythonic way to fetch all elements in a dictionary, falling between two keys?","dict((k, v) for k, v in parent_dict.items() if k > 2 and k < 4)"
python sorting two lists,"[list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0]))]"
number of values in a list greater than a certain number,sum(((i > 5) for i in j))
number of values in a list greater than a certain number,len([1 for i in j if (i > 5)])
number of values in a list greater than a certain number,"j = np.array(j)
sum((j > i))"
Python: elegant way of creating a list of tuples?,"[(x + tuple(y)) for x, y in zip(zip(a, b), c)]"
Changing file permission in python,"os.chmod(path, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)"
Multiple files for one argument in argparse Python 2.7,"parser.add_argument('file', nargs='*')"
Comparing values in two lists in Python,"z = [(i == j) for i, j in zip(x, y)]"
Comparing values in two lists in Python,[(x[i] == y[i]) for i in range(len(x))]
Python: Extract numbers from a string,"[int(s) for s in re.findall('\\b\\d+\\b', ""he33llo 42 I'm a 32 string 30"")]"
Create an empty data frame with index from another data frame,df2 = pd.DataFrame(index=df1.index)
How do I convert a string 2 bytes long to an integer in python,"struct.unpack('h', pS[0:2])"
Printing lists onto tables in python,"print('\n'.join(' '.join(map(str, row)) for row in t))"
Sort Pandas Dataframe by Date,df.sort_values(by='Date')
How can I check if a checkbox is checked in Selenium Python Webdriver?,driver.find_element_by_name('<check_box_name>').is_selected()
How can I check if a checkbox is checked in Selenium Python Webdriver?,driver.find_element_by_id('<check_box_id>').is_selected()
Is it possible to use 'else' in a python list comprehension?,"[(a if a else 2) for a in [0, 1, 0, 3]]"