intent
stringlengths
4
183
snippet
stringlengths
2
1k
Converting lists of tuples to strings Python
""" """.join([('%d@%d' % t) for t in l])
Converting lists of tuples to strings Python
""" """.join([('%d@%d' % (t[0], t[1])) for t in l])
Splinter or Selenium: Can we get current html page after clicking a button?
driver.execute_script('return document.documentElement.outerHTML;')
Find a specific pattern (regular expression) in a list of strings (Python)
[i for i in teststr if re.search('\\d+[xX]', i)]
Selecting with complex criteria from pandas.DataFrame
df['A'][(df['B'] > 50) & (df['C'] == 900)]
How to sort dictionaries by keys in Python
sorted(o.items())
How to sort dictionaries by keys in Python
sorted(d)
How to sort dictionaries by keys in Python
sorted(d.items())
convert strings into integers
int('1')
convert strings into integers
int()
convert strings into integers
T2 = [map(int, x) for x in T1]
How to call a shell script from python code?
subprocess.call(['./test.sh'])
How to call a shell script from python code?
subprocess.call(['notepad'])
Interleaving two lists in Python
[val for pair in zip(l1, l2) for val in pair]
Base64 encoding in Python 3
encoded = base64.b64encode('data to be encoded')
Base64 encoding in Python 3
encoded = 'data to be encoded'.encode('ascii')
Parsing CSV / tab-delimited txt file with Python
lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))
Python - Access object attributes as in a dictionary
getattr(my_object, my_str)
list of dicts to/from dict of lists
print(dict(zip(LD[0], zip(*[list(d.values()) for d in LD]))))
How do I sum the first value in each tuple in a list of tuples in Python?
sum([pair[0] for pair in list_of_pairs])
Convert unicode string dictionary into dictionary in python
d = ast.literal_eval("{'code1':1,'code2':1}")
Find all words in a string that start with the $ sign in Python
[word for word in mystring.split() if word.startswith('$')]
How to remove any URL within a string in Python
text = re.sub('^https?:\\/\\/.*[\\r\\n]*', '', text, flags=re.MULTILINE)
How to find all elements in a numpy 2-dimensional array that match a certain list?
np.where(np.in1d(A, [1, 3, 4]).reshape(A.shape), A, 0)
Calculate mean across dimension in a 2D array
np.mean(a, axis=1)
Running R script from python
subprocess.call(['/usr/bin/Rscript', '--vanilla', '/pathto/MyrScript.r'])
Running R script from python
subprocess.call('/usr/bin/Rscript --vanilla /pathto/MyrScript.r', shell=True)
How to add a header to a csv file in Python?
writer.writeheader()
Pandas Dataframe: Replacing NaN with row average
df.fillna(df.mean(axis=1), axis=1)
Python: Converting Epoch time into the datetime
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))
Calling a base class's classmethod in Python
super(Derived, cls).do(a)
selecting rows in numpy ndarray based on the value of two columns
a[np.where((a[:, (0)] == 0) * (a[:, (1)] == 1))]
Python regex separate space-delimited words into a list
re.split(' +', 'hello world sample text')
Length of longest word in a list
len(max(words, key=len))
accessing python dictionary
result[0]['from_user']
Save line in file to list
[line.split() for line in open('File.txt')]
Python: Best Way to Exchange Keys with Values in a Dictionary?
res = dict((v, k) for k, v in a.items())
creating a tmp file in python
new_file = open('path/to/FILE_NAME.ext', 'w')
How to count distinct values in a column of a pandas group by object?
df.groupby(['col1', 'col2'])['col3'].nunique().reset_index()
Check for a key pattern in a dictionary in python
any(key.startswith('EMP$$') for key in dict1)
Check for a key pattern in a dictionary in python
[value for key, value in list(dict1.items()) if key.startswith('EMP$$')]
python, best way to convert a pandas series into a pandas dataframe
pd.DataFrame({'email': sf.index, 'list': sf.values})
printing tab-separated values of a list
print('\t'.join(map(str, list)))
Python unicode string with UTF-8?
print('\xd0\xbf\xd1\x80\xd0\xb8'.encode('raw_unicode_escape'))
Python unicode string with UTF-8?
'Sopet\xc3\xb3n'.encode('latin-1').decode('utf-8')
How to adjust the quality of a resized image in Python Imaging Library?
image = image.resize((x, y), Image.ANTIALIAS)
Regex, find pattern only in middle of string
re.findall('n(?<=[^n]n)n+(?=[^n])(?i)', s)
how to show Percentage in python
print('{0:.0f}%'.format(1.0 / 3 * 100))
Sort a list of dicts by dict values
mylist.sort(key=lambda x: x['title'])
Sort a list of dicts by dict values
l.sort(key=lambda x: x['title'])
Sort a list of dicts by dict values
l.sort(key=lambda x: (x['title'], x['title_url'], x['id']))
finding n largest differences between two lists
heapq.nlargest(10, range(len(l1)), key=lambda i: abs(l1[i] - l2[i]))
Finding multiple attributes within the span tag in Python
soup.find_all('span', {'class': 'starGryB sp'})
Pandas writing dataframe to other postgresql schema
df.to_sql('test', engine, schema='a_schema')
Regular Expression to find brackets in a string
brackets = re.sub('[^(){}[\\]]', '', s)
Removing duplicates from list of lists in Python
list(dict((x[0], x) for x in L).values())
Reading a file without newlines
[line.rstrip('\n') for line in file]
get item's position in a list
[i for (i, x) in enumerate(testlist) if (x == 1)]
get item's position in a list
[i for (i, x) in enumerate(testlist) if (x == 1)]
get item's position in a list
for i in [i for (i, x) in enumerate(testlist) if (x == 1)]: pass
get item's position in a list
for i in (i for (i, x) in enumerate(testlist) if (x == 1)): pass
get item's position in a list
gen = (i for (i, x) in enumerate(testlist) if (x == 1))
get item's position in a list
print(testlist.index(element))
get item's position in a list
gen = (i for (i, x) in enumerate(testlist) if (x == 1))
Find the maximum value in a list of tuples in Python
max(lis, key=lambda item: item[1])[0]
Find the maximum value in a list of tuples in Python
max(lis, key=itemgetter(1))[0]
How do I simulate a progress counter in a command line application in Python?
time.sleep(1)
Tuple conversion to a string
""", """.join('(' + ', '.join(i) + ')' for i in L)
Default value for field in Django model
b = models.CharField(max_length=7, default='0000000', editable=False)
How do I perform secondary sorting in python?
sorted(list5, lambda x: (degree(x), x))
How do I perform secondary sorting in python?
sorted(list5, key=lambda vertex: (degree(vertex), vertex))
Python: convert list to generator
(n for n in [1, 2, 3, 5])
Remove multiple items from list in Python
newlist = [v for i, v in enumerate(oldlist) if i not in removelist]
Deleting a specific line in a file (python)
f = open('yourfile.txt', 'w')
Attribute getters in python
getattr(obj, 'attr')
How do I convert tuple of tuples to list in one line (pythonic)?
from functools import reduce reduce(lambda a, b: a + b, (('aa',), ('bb',), ('cc',)))
How do I convert tuple of tuples to list in one line (pythonic)?
map(lambda a: a[0], (('aa',), ('bb',), ('cc',)))
Python Pandas: How to replace a characters in a column of a dataframe?
df['range'].replace(',', '-', inplace=True)
inverse of zip
zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
inverse of zip
zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
inverse of zip
result = ([a for (a, b) in original], [b for (a, b) in original])
inverse of zip
result = ((a for (a, b) in original), (b for (a, b) in original))
inverse of zip
zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)])
inverse of zip
map(None, *[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)])
Python JSON serialize a Decimal object
json.dumps(Decimal('3.9'))
Add key to a dictionary
d['mynewkey'] = 'mynewvalue'
Add key to a dictionary
data.update({'a': 1, })
Add key to a dictionary
data.update(dict(a=1))
Add key to a dictionary
data.update(a=1)
Is there a one line code to find maximal value in a matrix?
max([max(i) for i in matrix])
Python - how to round down to 2 decimals
answer = str(round(answer, 2))
Extract IP address from an html string (python)
ip = re.findall('[0-9]+(?:\\.[0-9]+){3}', s)
How do I filter a pandas DataFrame based on value counts?
df.groupby('A').filter(lambda x: len(x) > 1)
Converting a string into a list in Python
[x for x in myfile.splitlines() if x != '']
Converting a string into a list in Python
lst = map(int, open('filename.txt').readlines())
Adding Colorbar to a Spectrogram
plt.colorbar(mappable=mappable, cax=ax3)
Count most frequent 100 words from sentences in Dataframe Pandas
Counter(' '.join(df['text']).split()).most_common(100)
Python split a string using regex
re.findall('(.+?):(.+?)\\b ?', text)
Generate all subsets of size k (containing k elements) in Python
list(itertools.combinations((1, 2, 3), 2))
Python: How to get a value of datetime.today() that is "timezone aware"?
datetime.now(pytz.utc)