text
stringlengths 4
1.08k
|
|---|
how to remove adjacent duplicate elements in a list using list comprehensions?,"[n for i, n in enumerate(xs) if i == 0 or n != xs[i - 1]]"
|
how to open a url in python,webbrowser.open_new(url)
|
find all words containing letters between a and z in string `formula`,"re.findall('\\b[A-Z]', formula)"
|
how to remove accents from values in columns?,"df['City'] = df['City'].str.replace('\xeb', 'e')"
|
removing unicode \u2026 like characters in a string in python2.7,"print(s.decode('unicode_escape').encode('ascii', 'ignore'))"
|
select rows from a dataframe based on values in a column in pandas,df.query('foo == 222 | bar == 444')
|
how to obtain the day of the week in a 3 letter format from a datetime object in python?,datetime.datetime.now().strftime('%a')
|
"in python, how do i check to see if keys in a dictionary all have the same value x?",len(set(d.values())) == 1
|
find 3 letter words,words = [word for word in string.split() if len(word) == 3]
|
delete a column `column_name` without having to reassign from pandas data frame `df`,"df.drop('column_name', axis=1, inplace=True)"
|
"""pythonic"" method to parse a string of comma-separated integers into a list of integers?","mylist = [int(x) for x in '3 ,2 ,6 '.split(',')]"
|
make subprocess find git executable on windows,"proc = subprocess.Popen('git status', stdout=subprocess.PIPE, shell=True)"
|
adding url `url` to mysql row,"cursor.execute('INSERT INTO index(url) VALUES(%s)', (url,))"
|
how to update/modify a xml file in python?,et.write('file_new.xml')
|
trying to plot temperature,plt.show()
|
is there a portable way to get the current username in python?,getpass.getuser()
|
"find the greatest number in set `(1, 2, 3)`","print(max(1, 2, 3))"
|
concatenate rows of pandas dataframe with same id,df.groupby('id').agg(lambda x: x.tolist())
|
how do you calculate the greatest number of repetitions in a list?,"print(max(group, key=lambda k: len(list(k[1]))))"
|
get the first and last 3 elements of list `l`,l[:3] + l[-3:]
|
calculation between groups in a pandas multiindex dataframe,df['ratio'] = df.groupby(level=0)[3].transform(lambda x: x[0] / x[1])
|
removing duplicates from nested list based on first 2 elements,"list({(x[0], x[1]): x for x in L}.values())"
|
"how to remove specific characters in a string *within specific delimiters*, e.g. within parentheses","re.sub('\\s+(?=[^[\\(]*\\))|((?<=\\()\\s+)', '', my_string)"
|
pandas write table to mysql,"df.to_sql('demand_forecast_t', engine, if_exists='replace', index=False)"
|
matching id's in beautifulsoup,"print(soupHandler.findAll('div', id=re.compile('^post-')))"
|
python inverse of a matrix,"A = matrix([[1, 2, 3], [11, 12, 13], [21, 22, 23]])"
|
how to print integers as hex strings using json.dumps() in python,"{'a': '0x1', 'c': '0x3', 'b': 2.0}"
|
is there a simple way to change a column of yes/no to 1/0 in a pandas dataframe?,"pd.Series(np.where(sample.housing.values == 'yes', 1, 0), sample.index)"
|
check if a local variable 'myvar' exists,"if ('myVar' in locals()):
|
pass"
|
detecting non-ascii characters in unicode string,"print(set(re.sub('[\x00-\x7f]', '', '\xa3\u20ac\xa3\u20ac')))"
|
how to maximize a plt.show() window using python,plt.show()
|
how do i pass template context information when using httpresponseredirect in django?,{{request.session.foo}}
|
how can i fill out a python string with spaces?,"""""""{0: <16}"""""".format('Hi')"
|
read csv file 'my.csv' into a dataframe `df` with datatype of float for column 'my_column' considering character 'n/a' as nan value,"df = pd.read_csv('my.csv', dtype={'my_column': np.float64}, na_values=['n/a'])"
|
one hour difference in python,var < datetime.datetime.today() - datetime.timedelta(hours=1)
|
python serial: how to use the read or readline function to read more than 1 character at a time,ser.readline()
|
how do i insert a space after a certain amount of characters in a string using python?,"""""""this isar ando msen tenc e"""""""
|
group a list `list_of_tuples` of tuples by values,zip(*list_of_tuples)
|
"python - using argparse, pass an arbitrary string as an argument to be used in the script","parser.add_argument('-a', action='store_true')"
|
using multiple cursors in a nested loop in sqlite3 from python-2.7,curOuter.execute('SELECT id FROM myConnections')
|
get count of values associated with key in dict python,"len([x for x in s if x.get('success', False)])"
|
convert enum to int in python,print(nat.index(nat.Germany))
|
how do i split an ndarray based on array of indexes?,"array([[0, 1], [2, 3], [6, 7], [8, 9], [10, 11]])"
|
how to sort in decreasing value first then increasing in second value,"print(sorted(student_tuples, key=lambda t: (-t[2], t[0])))"
|
json->string in python,print(result[0]['status'])
|
converting byte string `c` in unicode string,c.decode('unicode_escape')
|
how to make pylab.savefig() save image for 'maximized' window instead of default size,"matplotlib.rc('font', size=6)"
|
search for string 'blabla' in txt file 'example.txt',"f = open('example.txt')
|
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
|
if (s.find('blabla') != (-1)):
|
pass"
|
get unique values from a list in python,mylist = list(set(mylist))
|
get current time in pretty format,"strftime('%Y-%m-%d %H:%M:%S', gmtime())"
|
what is the simplest way to create a shaped window in wxpython?,"self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)"
|
pandas dataframe group year index by decade,df.groupby(df.index.year // 10 * 10).sum()
|
find the indices of elements greater than x,"[(i, j) for i, j in zip(a, x)]"
|
removing non numeric characters from a string,new_string = ''.join(ch for ch in your_string if ch.isdigit())
|
how to replace all occurrences of regex as if applying replace repeatedly,"""""""\\1 xby """""""
|
"pandas, multiply all the numeric values in the data frame by a constant","df.ix[:, (~np.in1d(df.dtypes, ['object', 'datetime']))] *= 3"
|
jinja2 formate date `item.date` accorto pattern 'y m d',{{(item.date | date): 'Y M d'}}
|
plotting categorical data with pandas and matplotlib,df.groupby('colour').size().plot(kind='bar')
|
elegant way to modify a list of variables by reference in python?,"setattr(i, x, f(getattr(i, x)))"
|
python: logging typeerror: not all arguments converted during string formatting,logging.info('date={}'.format(date))
|
python matplotlib decrease size of colorbar labels,cbar.ax.tick_params(labelsize=10)
|
how to drop a list of rows from pandas dataframe?,"df.drop(df.index[[1, 3]], inplace=True)"
|
execute external commands/script `your_own_script` with csh instead of bash,os.system('tcsh your_own_script')
|
django model field default based on another model field,"super(ModelB, self).save(*args, **kwargs)"
|
passing a function with two arguments to filter() in python,basetwo('10010')
|
check if key 'a' in `d`,('a' in d)
|
is it possible to plot timelines with matplotlib?,fig.autofmt_xdate()
|
how to zip lists in a list,"zip(*[[1, 2], [3, 4], [5, 6]])"
|
make all keys lowercase in dictionary `d`,"d = {(a.lower(), b): v for (a, b), v in list(d.items())}"
|
plotting a 2d array with matplotlib,ax.set_zlabel('$V(\\phi)$')
|
how do i add a new column to a spark dataframe (using pyspark)?,"df.select('*', (df.age + 10).alias('agePlusTen'))"
|
how to convert decimal to binary list in python,[int(x) for x in list('{0:0b}'.format(8))]
|
atomic increment of a counter in django,Counter.objects.filter(name=name).update(count=F('count') + 1)
|
how to change attributes of a networkx / matplotlib graph drawing?,plt.show()
|
how to check if a value exists in a dictionary (python),'one' in list(d.values())
|
creating a numpy array of 3d coordinates from three 1d arrays,"np.vstack(np.meshgrid(x_p, y_p, z_p)).reshape(3, -1).T"
|
"left trimming ""\n\r"" from string `mystring`",myString.lstrip('\n\r')
|
"zip two lists `[1, 2]` and `[3, 4]` into a list of two tuples containing elements at the same index in each list","zip([1, 2], [3, 4])"
|
"pandas, dataframe: splitting one column into multiple columns","pd.concat([df, df.dictionary.apply(str2dict).apply(pd.Series)], axis=1)"
|
getting a list of all subdirectories in the current directory,next(os.walk('.'))[1]
|
get current time,datetime.datetime.now().time()
|
django logging to console,logger = logging.getLogger(__name__)
|
python - how to convert int to string represent a 32bit hex number,"""""""0x{0:08X}"""""".format(3652458)"
|
inserting characters at the start and end of a string,"yourstring = ''.join(('L', 'yourstring', 'LL'))"
|
python map list of strings to integer list,"k = [1, 1, 2, 3]"
|
get 'popular categories' in django,Category.objects.annotate(num_books=Count('book')).order_by('num_books')
|
python regular expression for beautiful soup,"['comment form new', 'comment comment-xxxx...']"
|
understanding list comprehension for flattening list of lists in python,[item for sublist in (list_of_lists for item in sublist)]
|
python lambda returning none instead of empty string,lambda x: x if x is not None else ''
|
how to discontinue a line graph in the plot pandas or matplotlib python,plt.show()
|
replace values in an array,"b = np.where(np.isnan(a), 0, a)"
|
how to transform a time series pandas dataframe using the index attributes?,"pd.pivot_table(df, index=df.index.date, columns=df.index.time, values='Close')"
|
how can i use the fields_to_export attribute in baseitemexporter to order my scrapy csv data?,ITEM_PIPELINES = {'myproject.pipelines.CSVPipeline': 300}
|
"in django, how does one filter a queryset with dynamic field lookups?",Person.objects.filter(**kwargs)
|
grouping pandas dataframe by n days starting in the begining of the day,df['date'] = pd.to_datetime(df['date'])
|
finding words after keyword in python,"re.search('name (.*)', s)"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.