text
stringlengths
4
1.08k
String Formatting in Python 3,"""""""({0.goals} goals, ${0.penalties})"""""".format(self)"
Convert list of lists to list of integers,[int(''.join(str(d) for d in x)) for x in L]
Convert list of lists to list of integers,[''.join(str(d) for d in x) for x in L]
Convert list of lists to list of integers,L = [int(''.join([str(y) for y in x])) for x in L]
How to write a list to a file with newlines in Python3,myfile.write('\n'.join(lines))
Removing an element from a list based on a predicate,"[x for x in ['AAT', 'XAC', 'ANT', 'TTA'] if 'X' not in x and 'N' not in x]"
python regular expression to remove repeated words,"text = re.sub('\\b(\\w+)( \\1\\b)+', '\\1', text)"
Counting non zero values in each column of a dataframe in python,df.astype(bool).sum(axis=1)
Python match string if it does not start with X,"re.search('(?<!Distillr)\\\\AcroTray\\.exe', 'C:\\SomeDir\\AcroTray.exe')"
String to list in Python,"""""""QH QD JC KD JS"""""".split()"
Parsing XML in Python with regex,"print(re.search('>.*<', line).group(0))"
How to empty a file using Python,"open(filename, 'w').close()"
how to convert a string date into datetime format in python?,"datetime.datetime.strptime(string_date, '%Y-%m-%d %H:%M:%S.%f')"
What's the fastest way to locate a list element within a list in python?,"[index for index, item in enumerate(thelist) if item[0] == '332']"
Python: trying to lower a string and remove non-alphanumeric characters aside from space,"re.sub('[^\\sa-zA-Z0-9]', '', text).lower().strip()"
Python: trying to lower a string and remove non-alphanumeric characters aside from space,"re.sub('(?!\\s)[\\W_]', '', text).lower().strip()"
Subscripting text in matplotlib labels,"plt.plot(x, y, label='H\u2082O')"
Subscripting text in matplotlib labels,"plt.plot(x, y, label='$H_2O$')"
Looping over a list in Python,[x for x in mylist if len(x) == 3]
Initialize a list of objects in Python,lst = [Object() for _ in range(100)]
Initialize a list of objects in Python,lst = [Object() for i in range(100)]
selenium how to get the content of href within some targeted class,self.driver.find_element_by_css_selector('.someclass a').get_attribute('href')
Joining Table/DataFrames with common Column in Python,"df1.merge(df2, on='Date_Time')"
insert variable values into a string in python,"'first string is: %s, second one is: %s' % (str1, 'geo.tif')"
Split a string by a delimiter in python,[x.strip() for x in '2.MATCHES $$TEXT$$ STRING'.split('$$TEXT$$')]
check if a directory exists and create it if necessary,"if (not os.path.exists(directory)):
os.makedirs(directory)"
check if a directory exists and create it if necessary,os.makedirs(path)
check if a directory exists and create it if necessary,distutils.dir_util.mkpath(path)
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]