text stringlengths 4 1.08k |
|---|
vectorize over the rows of an array,"numpy.apply_along_axis(sum, 1, X)" |
replace carriage return in string `somestring` with empty string '',"somestring.replace('\\r', '')" |
commit all the changes after executing a query.,dbb.commit() |
how to json serialize __dict__ of a django model?,"return HttpResponse(json.dumps(data), content_type='application/json')" |
remove string from list if from substring list,[l.split('\\')[-1] for l in list_dirs] |
pandas split string into columns,"df['stats'].str[1:-1].str.split(',').apply(pd.Series).astype(float)" |
get the indexes of truthy elements of a boolean list as a list/tuple,"[i for i, elem in enumerate(bool_list, 1) if elem]" |
creating a list of dictionaries in python,"[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]" |
remove leading and trailing zeros in the string 'your_strip',your_string.strip('0') |
how to put appropriate line breaks in a string representing a mathematical expression that is 9000+ characters?,wordsep_re = re.compile('(\\s+|(?:-|\\+|\\*\\*|\\*))') |
replace nan values in column 'value' with the mean of data in column 'group' of dataframe `df`,df[['value']].fillna(df.groupby('group').transform('mean')) |
tricky string matching,"""""""a_foobar_FooBar baz golf_CART Foo""""""" |
relative imports in python 3,myothermodule.py |
create 4 numbers in range between 1 and 3,"print(np.linspace(1, 3, num=4, endpoint=False))" |
how to append an element of a sublist in python,"[1, 2, 3]" |
"plotting a list of (x, y) coordinates in python matplotlib",plt.show() |
floating point in python,print('%.3f' % 4.53) |
numpy: get random set of rows from 2d array,"A[(np.random.choice(A.shape[0], 2, replace=False)), :]" |
how to get output from subprocess.popen(),sys.stdout.flush() |
pixelate image with pillow,"palette.append((0, 0, 0))" |
double iteration in list comprehension,[x for b in a for x in b] |
how do i select a random element from an array in python?,"random.choice([1, 2, 3])" |
python regex substitute from some position of pattern,"find.sub('\\1', text)" |
numpy replace negative values in array,"numpy.where(a <= 2, a, 2)" |
find all substrings in string `mystring` composed only of letters `a` and `b` where each `a` is directly preceded and succeeded by `b`,"re.findall('\\b(?:b+a)+b+\\b', mystring)" |
stack two dataframes next to each other in pandas,"pd.concat([GOOG, AAPL], keys=['GOOG', 'AAPL'], axis=1)" |
"in python, how to change text after it's printed?",sys.stdout.write('\x1b[D \x1b[D') |
python : how to create a dynamic list of class values,"MyList = [inst1, inst2]" |
sort list `lst` in descending order based on the second item of each tuple in it,"lst.sort(key=lambda x: x[2], reverse=True)" |
pandas dataframe performance,df.loc['2000-1-1':'2000-3-31'] |
how to get non-blocking/real-time behavior from python logging module? (output to pyqt qtextbrowser),sys.exit(app.exec_()) |
finding out absolute path to a file from python,os.path.abspath(__file__) |
how to gracefully fallback to `nan` value while reading integers from a csv with pandas?,"df = pd.read_csv('my.csv', dtype={'my_column': np.float64}, na_values=['n/a'])" |
how to use flask-script and gunicorn,"manager.add_command('gunicorn', GunicornServer())" |
plot data from csv file with matplotlib,"ax1.plot(data['x'], data['y'], color='r', label='the data')" |
xml parsing in python using elementtree,tree.find('//BODY').text |
google app engine (python) - uploading a file (image),imagedata.image = self.request.get('image') |
how do i get the number of lists with a particular element?,"Counter({'a': 3, 'c': 3, 'b': 2, 'd': 1})" |
generate a list of all unique pairs of integers in `range(9)`,"list(permutations(list(range(9)), 2))" |
run 'test2.py' file with python location 'path/to/python' and arguments 'neededargumetgohere' as a subprocess,"call(['path/to/python', 'test2.py', 'neededArgumetGoHere'])" |
how do i get rid of python tkinter root window?,root.deiconify() |
fastest way to sort each row in a pandas dataframe,"df.sort(df.columns, axis=1, ascending=False)" |
mysql commit current transaction,con.commit() |
how can i generate a list of consecutive numbers?,list(range(9)) |
how to delete a character from a string using python?,"newstr = oldstr.replace('M', '')" |
how to dynamically access class properties in python?,"setattr(my_class_instance, 'attr_name', attr_value)" |
get first element of each tuple in list `a`,[tup[0] for tup in A] |
how to call python function from nodejs,sys.stdout.flush() |
designing a recursive function that uses digit_sum to calculate sum of digits,"return sum(map(int, str(n)))" |
how to convert a list by mapping an element into multiple elements in python?,"print([y for x in l for y in (x, x + 1)])" |
move a tkinter canvas with mouse,root.mainloop() |
passing a list to python from command line,main(sys.argv[1:]) |
python regex findall alternation behavior,"re.findall('\\d|\\d,\\d\\)', '6,7)')" |
get file '~/foo.ini',config_file = os.path.expanduser('~/foo.ini') |
how to count the occurrence of certain item in an ndarray in python?,"a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4]) |
collections.Counter(a)" |
is there a way to make seaborn or vincent interactive?,"plt.plot(x, y)" |
how do i open an image from the internet in pil?,im = Image.open(image_file) |
sum values from dataframe into parent index - python/pandas,df_sum = df.groupby('parent').sum() |
convert hex triplet string `rgbstr` to rgb tuple,"struct.unpack('BBB', rgbstr.decode('hex'))" |
substitute occurrences of unicode regex pattern u'\\p{p}+' with empty string '' in string `text`,"return re.sub('\\p{P}+', '', text)" |
list of lists into numpy array,"numpy.array([[1, 2], [3, 4]])" |
python string interning and substrings,""""""""""""".join(g)" |
how to convert list of numpy arrays into single numpy array?,"numpy.concatenate(LIST, axis=0)" |
remove the element in list `a` at index `index`,a.pop(index) |
remove duplicate chars using regex?,"re.sub('a*', 'a', 'aaabbbccc')" |
"splitting a semicolon-separated string to a dictionary, in python",dict(item.split('=') for item in s.split(';')) |
pandas dataframe groupby two columns and get counts,"df.groupby(['col5', 'col2']).size().groupby(level=1).max()" |
"format all floating variables `var1`, `var2`, `var3`, `var1` to print to two decimal places.","print('%.2f kg = %.2f lb = %.2f gal = %.2f l' % (var1, var2, var3, var4))" |
how to define a mathematical function in sympy?,"f.subs(x, 1)" |
convert dataframe column type from string to datetime,"pd.to_datetime(pd.Series(['05/23/2005']), format='%m/%d/%Y')" |
fastest way to remove all multiple occurrence items from a list?,list_of_lists = [list(k) for k in list_of_tuples] |
how to apply numpy.linalg.norm to each row of a matrix?,"numpy.apply_along_axis(numpy.linalg.norm, 1, a)" |
java equivalent of python's string partition,"['foo', 'bar hello world']" |
python comprehension loop for dictionary,"sum(item.get('one', 0) for item in list(tadas.values()))" |
selecting across multiple columns with python pandas?,df[(df['A'] > 1) | (df['B'] < -1)] |
manually throw/raise a `valueerror` exception with the message 'a very specific bad thing happened',raise ValueError('A very specific bad thing happened') |
python: how to delete rows ending in certain characters?,"df = df[~df['User Name'].str.endswith(('DA', 'PL'))]" |
"convert the zip of range `(1, 5)` and range `(7, 11)` into a dictionary","dict(zip(list(range(1, 5)), list(range(7, 11))))" |
"resample dataframe `frame` to resolution of 1 hour `1h` for timeseries index, summing values in the column `radiation` averaging those in column `tamb`","frame.resample('1H').agg({'radiation': np.sum, 'tamb': np.mean})" |
"find the index of a dict within a list, by matching the dict's value","tom_index = next(index for index, d in enumerate(lst) if d['name'] == 'Tom')" |
how do i model a many-to-many relationship over 3 tables in sqlalchemy (orm)?,session.query(Shots).filter_by(event_id=event_id).order_by(asc(Shots.user_id)) |
how to add multiple values to a dictionary key in python?,a[key].append(2) |
get a dictionary from a dictionary `hand` where the values are present,"dict((k, v) for k, v in hand.items() if v)" |
finding tuple in the list of tuples (sorting by multiple keys),"sorted(t, key=lambda i: (i[1], -i[2]))" |
how to transform a tuple to a string of values without comma and parentheses,""""""" """""".join([str(x) for x in t])" |
using beautifulsoup to search html for string,soup.body.findAll(text=re.compile('^Python$')) |
split string by capital letter but ignore aaa python regex,""""""" """""".join(re.findall('[A-Z]?[^A-Z\\s]+|[A-Z]+', vendor))" |
remove the element in list `a` with index 1,a.pop(1) |
iterate items in lists `listone` and `listtwo`,"for item in itertools.chain(listone, listtwo): |
pass" |
hexadecimal string to byte array in python,"map(ord, hex_data)" |
how can i check if a checkbox is checked in selenium python webdriver?,driver.find_element_by_id('<check_box_id>').is_selected() |
get the dimensions of numpy array `a`,N.shape(a) |
numpy: get 1d array as 2d array without reshape,"np.array([1, 2, 3], ndmin=2).T" |
access an arbitrary element in a dictionary in python,next(iter(dict.values())) |
custom sort python,my_list.sort(key=my_key) |
delete all values in a list `mylist`,del mylist[:] |
how to read lines from mmap file in python?,print(line.rstrip()) |
convert float 24322.34 to comma-separated string,"""""""{0:,.2f}"""""".format(24322.34)" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.