intent
stringlengths
4
183
snippet
stringlengths
2
1k
check if a directory exists and create it if necessary
os.makedirs(path)
Replace a substring when it is a separate word
re.sub('\\bH3\\b', 'H1', text)
Python: removing characters except digits from string
re.sub('\\D', '', 'aas30dsa20')
Python: removing characters except digits from string
"""""".join([x for x in 'aas30dsa20' if x.isdigit()])
How to access a tag called "name" in BeautifulSoup
print(soup.find('name').string)
Iterate through PyMongo Cursor as key-value pair
records = dict((record['_id'], record) for record in cursor)
Python how to combine two matrices in numpy
np.concatenate((A, B))
Python how to combine two matrices in numpy
np.vstack((A, B))
how to check the character count of a file in python
os.stat(filepath).st_size
count the occurrences of a list item
l.count('a')
count the occurrences of a list item
Counter(l)
count the occurrences of a list item
[[x, l.count(x)] for x in set(l)]
count the occurrences of a list item
dict(((x, l.count(x)) for x in set(l)))
count the occurrences of a list item
l.count('b')
How to copy a file using python?
shutil.copy(srcfile, dstdir)
Efficient way to find the largest key in a dictionary with non-zero value
max(k for k, v in x.items() if v != 0)
Efficient way to find the largest key in a dictionary with non-zero value
(k for k, v in x.items() if v != 0)
Efficient way to find the largest key in a dictionary with non-zero value
max(k for k, v in x.items() if v != 0)
Re-read an open file Python
file.seek(0)
Coalesce values from 2 columns into a single column in a pandas dataframe
df['c'] = np.where(df['a'].isnull, df['b'], df['a'])
python: Is this a wrong way to remove an element from a dict?
del d['ele']
How can I subtract or add 100 years to a datetime field in the database in Django?
MyModel.objects.update(timestamp=F('timestamp') + timedelta(days=36524.25))
How to merge multiple lists into one list in python?
['it'] + ['was'] + ['annoying']
How to increment a value with leading zeroes?
str(int(x) + 1).zfill(len(x))
How can I check if a Pandas dataframe's index is sorted
all(df.index[:-1] <= df.index[1:])
Convert tuple to list
list(t)
Convert tuple to list
tuple(l)
Convert tuple to list and back
level1 = map(list, level1)
how to send the output of pprint module to a log file
pprint.pprint(dataobject, logFile)
Python Pandas: Get index of rows which column matches certain value
df.loc[df['BoolCol']]
Python Pandas: Get index of rows which column matches certain value
df.iloc[np.flatnonzero(df['BoolCol'])]
Python Pandas: Get index of rows which column matches certain value
df[df['BoolCol'] == True].index.tolist()
Python Pandas: Get index of rows which column matches certain value
df[df['BoolCol']].index.tolist()
How do I change directory back to my original working directory with Python?
os.chdir(owd)
How to insert strings with quotes and newlines into sqlite db with Python?
c.execute("INSERT INTO test VALUES (?, 'bar')", (testfield,))
Python - how to convert a "raw" string into a normal string
"""\\x89\\n""".decode('string_escape')
Python - how to convert a "raw" string into a normal string
raw_string.decode('string_escape')
Python - how to convert a "raw" string into a normal string
raw_byte_string.decode('unicode_escape')
Splitting a string with repeated characters into a list using regex
[m.group(0) for m in re.finditer('(\\d)\\1*', s)]
How to do a scatter plot with empty circles in Python?
plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')
How to do a scatter plot with empty circles in Python?
plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')
Deleting a div with a particlular class using BeautifulSoup
soup.find('div', id='main-content').decompose()
How to filter rows containing a string pattern from a Pandas dataframe
df[df['ids'].str.contains('ball')]
How to convert pandas index in a dataframe to a column?
df.reset_index(level=0, inplace=True)
How to convert pandas index in a dataframe to a column?
df['index1'] = df.index
How to convert pandas index in a dataframe to a column?
df.reset_index(level=['tick', 'obs'])
Generic reverse of list items in Python
[x[::-1] for x in b]
in Numpy, how to zip two 2-D arrays?
np.array([zip(x, y) for x, y in zip(a, b)])
in Numpy, how to zip two 2-D arrays?
np.array(zip(a.ravel(), b.ravel()), dtype='i4,i4').reshape(a.shape)
How to convert a list of longs into a comma separated string in python
""",""".join([str(i) for i in list_of_ints])
Posting raw data with Python
requests.post(url, data=DATA, headers=HEADERS_DICT, auth=(username, password))
Find last occurrence of character
'abcd}def}'.rfind('}')
Ending with a for loop in python
print([item for item in [1, 2, 3]])
transpose dictionary (extract all the values for one key from a list of dictionaries)
[(x['x'], x['y']) for x in d]
How to get the filename without the extension from a path in Python?
print(os.path.splitext(os.path.basename('hemanth.txt'))[0])
Make dictionary from list with python
dict(x[i:i + 2] for i in range(0, len(x), 2))
Merging a list of lists
values = sum([['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']], [])
How to select rows in a DataFrame between two values, in Python Pandas?
df = df[(df['closing_price'] >= 99) & (df['closing_price'] <= 101)]
Replace all occurrences of a string in a pandas dataframe (Python)
df.replace({'\n': '<br>'}, regex=True)
Replace all occurrences of a string in a pandas dataframe (Python)
df.replace({'\n': '<br>'}, regex=True)
Mapping a string into a list of pairs
[(x + y) for x, y in zip(word, word[1:])]
Mapping a string into a list of pairs
list(map(lambda x, y: x + y, word[:-1], word[1:]))
How do you extract a url from a string using python?
print(re.findall('(https?://[^\\s]+)', myString))
How do you extract a url from a string using python?
print(re.search('(?P<url>https?://[^\\s]+)', myString).group('url'))
Remove all special characters, punctuation and spaces from string
re.sub('[^A-Za-z0-9]+', '', mystring)
How to get a daterange of the 2nd Fridays of each month?
pd.date_range('2016-01-01', freq='WOM-2FRI', periods=13)
Multidimensional array in Python
matrix = [[a, b], [c, d], [e, f]]
How do I replace whitespaces with underscore and vice versa?
mystring.replace(' ', '_')
How to get an absolute file path in Python
os.path.abspath('mydir/myfile.txt')
Is there a string-collapse library function in python?
""" """.join(my_string.split())
Get Filename Without Extension in Python
os.path.splitext(filename)[0]
How to sum elements in functional way
[sum(l[:i]) for i, _ in enumerate(l)]
Python Regex Split Keeps Split Pattern Characters
"""Docs/src/Scripts/temp""".replace('/', '/\x00/').split('\x00')
Shuffle columns of an array with Numpy
np.random.shuffle(np.transpose(r))
Copy all values in a column to a new column in a pandas dataframe
df['D'] = df['B']
Find a value within nested json dictionary in python
list(data['A']['B'].values())[0]['maindata'][0]['Info']
True for all characters of a string
all(predicate(x) for x in string)
How to determine number of files on a drive with Python?
os.statvfs('/').f_files - os.statvfs('/').f_ffree
how to get a single result from a SQLite query in python?
cursor.fetchone()[0]
How to convert a string list into an integer in python
user_list = [int(number) for number in user_input.split(',')]
How to convert a string list into an integer in python
[int(s) for s in user.split(',')]
Sorting a Python list by two criteria
sorted(list, key=lambda x: (x[0], -x[1]))
How to sort a list of objects , based on an attribute of the objects?
ut.sort(key=cmpfun, reverse=True)
How to sort a list of objects , based on an attribute of the objects?
ut.sort(key=lambda x: x.count, reverse=True)
How to sort a list of objects , based on an attribute of the objects?
ut.sort(key=lambda x: x.count, reverse=True)
Click a href button with selenium and python?
driver.find_element_by_partial_link_text('Send').click()
Click a href button with selenium and python?
driver.findElement(By.linkText('Send InMail')).click()
Click a href button with selenium and python?
driver.find_element_by_link_text('Send InMail').click()
Casting an int to a string in Python
'ME' + str(i)
Sorting data in DataFrame Pandas
df.sort_values(['System_num', 'Dis'])
Prepend a line to an existing file in Python
open('outfile', 'w').write('#test firstline\n' + open('infile').read())
Python sort a List by length of value in tuple
l.sort(key=lambda t: len(t[1]), reverse=True)
Split by suffix with Python regular expression
re.findall('\\b(\\w+)d\\b', s)
python's re: return True if regex contains in the string
bool(re.search('ba[rzd]', 'foobarrrr'))
Removing duplicates in lists
list(set(t))
Removing duplicates in lists
list(set(source_list))
Removing duplicates in lists
list(OrderedDict.fromkeys('abracadabra'))
How to make List from Numpy Matrix in Python
numpy.array(a).reshape(-1).tolist()
How to make List from Numpy Matrix in Python
numpy.array(a)[0].tolist()
Beautifulsoup - nextSibling
print(soup.find(text='Address:').findNext('td').contents[0])