text
stringlengths
4
1.08k
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])
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)"