text
stringlengths 4
1.08k
|
|---|
convert a list of strings `lst` to list of integers,"[map(int, sublist) for sublist in lst]"
|
breaking a string in python depending on character pattern,"re.findall('\\d:::.+?(?=\\d:::|$)', a)"
|
"how to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/l '])"
|
how to convert 2d list to 2d numpy array?,a = np.array(a)
|
how to change the order of dataframe columns?,cols = list(df.columns.values)
|
regular expression to match a dot,"re.split('\\b\\w+\\.\\w+@', s)"
|
create an empty data frame with index from another data frame,df2 = pd.DataFrame(index=df1.index)
|
pop/remove items out of a python tuple,tupleX = [x for x in tupleX if x > 5]
|
using beautifulsoup to search html for string,soup.body.findAll(text='Python Jobs')
|
remove 20 symbols in front of '.' in string 'unique12345678901234567890.mkv',"re.sub('.{20}(.mkv)', '\\1', 'unique12345678901234567890.mkv')"
|
print the key of the max value in a dictionary the pythonic way,"print(max(d, key=d.get))"
|
concatenate elements of a list 'x' of multiple integers to a single integer,"sum(d * 10 ** i for i, d in enumerate(x[::-1]))"
|
how to change the color of certain words in the tkinter text widget?,"self.text.pack(fill='both', expand=True)"
|
python: regular expression search pattern for binary files (half a byte),my_pattern = re.compile('\xde\xad[@-O].')
|
"how can i compare two lists in python, and return that the second need to have the same values regardless of order?",sorted(a) == sorted(b)
|
find the indices of elements greater than x,"[(i, j) for i, j in zip(a, x) if i >= 4]"
|
call a function through a variable in python,_w()
|
python mysql parameterized queries,"c.execute('SELECT * FROM foo WHERE bar = %s AND baz = %s' % (param1, param2))"
|
"in python, how do i convert all of the items in a list to floats?",[float(i) for i in lst]
|
how to cell values as new columns in pandas dataframe,"df2 = df['Labels'].str.get_dummies(sep=',')"
|
get file creation time with python on mac,return os.stat(path).st_birthtime
|
sorting list of nested dictionaries in python,"sorted(yourdata, reverse=True)"
|
pandas - conditionally select column based on row value,"pd.concat([foo['Country'], z], keys=['Country', 'z'], axis=1)"
|
consequences of abusing nltk's word_tokenize(sent),"nltk.tokenize.word_tokenize('Hello, world.')"
|
extract all keys from a list of dictionaries,all_keys = set().union(*(list(d.keys()) for d in mylist))
|
how to show decimal point only when it's not a whole number?,[(int(i) if int(i) == i else i) for i in li]
|
python: converting a list of dictionaries to json,json.dumps(list)
|
parse date string '2009/05/13 19:19:30 -0400' using format '%y/%m/%d %h:%m:%s %z',"datetime.strptime('2009/05/13 19:19:30 -0400', '%Y/%m/%d %H:%M:%S %z')"
|
find non-common elements in lists,"set([1, 2, 3]) ^ set([3, 4, 5])"
|
sorting numpy array according to the sum,"np.take(a, idx, axis=1)"
|
how do i change the axis tick font in a matplotlib plot when rendering using latex?,"rc('text.latex', preamble='\\usepackage{cmbright}')"
|
how to implement simple sessions for google app engine?,session = Session.get_by_id(sid)
|
update row values for a column `season` using vectorized string operation in pandas,df['Season'].str.split('-').str[0].astype(int)
|
pairwise crossproduct in python,"[(x, y) for x in a for y in b]"
|
hashing a python dictionary,hash(frozenset(list(my_dict.items())))
|
pandas : assign result of groupby to dataframe to a new column,df['size'].loc[df.groupby('adult')['weight'].transform('idxmax')]
|
sort a list of tuples by 2nd item (integer value),"sorted(data, key=itemgetter(1))"
|
how to get a random value in python dictionary,"country, capital = random.choice(list(d.items()))"
|
pandas: transforming the dataframegroupby object to desired format,df.index = ['/'.join(i) for i in df.index]
|
multi-line logging in python,logging.debug('Nothing special here... Keep walking')
|
"how to print +1 in python, as +1 (with plus sign) instead of 1?",print('%+d' % score)
|
create list `changed_list ` containing elements of list `original_list` whilst converting strings containing digits to integers,changed_list = [(int(f) if f.isdigit() else f) for f in original_list]
|
how to write unicode strings into a file?,f.write(s.encode('UTF-8'))
|
get utc datetime in iso format,datetime.datetime.utcnow().isoformat()
|
can a value in a python dictionary have two values?,"afc = {'Baltimore Ravens': (10, 3), 'Pb Steelers': (3, 4)}"
|
sorting lines of file python,"re.split('\\s+', line)"
|
playing video in gtk in a window with a menubar,Gtk.main()
|
how to document python function parameter types?,"return 'Hello World! %s, %s' % (x, y)"
|
"python-matplotlib boxplot. how to show percentiles 0,10,25,50,75,90 and 100?",plt.show()
|
how do i fix a dimension error in tensorflow?,"x_image = tf.reshape(tf_in, [-1, 2, 4, 1])"
|
comparing previous row values in pandas dataframe,df['match'] = df['col1'].diff().eq(0)
|
atomic writing to file with python,f.write('huzza')
|
how do i get a empty array of any size i want in python?,a = [0] * 10
|
how to start a background process in python?,os.system('some_command &')
|
extracting all rows from pandas dataframe that have certain value in a specific column,data['Value'] == 'TRUE'
|
how do i efficiently combine similar dataframes in pandas into one giant dataframe,"df1.set_index('Date', inplace=True)"
|
are there any way to scramble strings in python?,return ''.join(word)
|
how can i check if a letter in a string is capitalized using python?,print(''.join(uppers))
|
how to split a word into letters in python,""""""","""""".join('Hello')"
|
how to print a list of tuples,"print(x[0], x[1])"
|
how to rearrange pandas column sequence?,"df = df[['x', 'y', 'a', 'b']]"
|
how to split a string using an empty separator in python,list('1111')
|
get a list of tuples with multiple iterators using list comprehension,"[(i, j) for i in range(1, 3) for j in range(1, 5)]"
|
python: for loop - print on the same line,print(' '.join([function(word) for word in split]))
|
python: logging module - globally,logger.setLevel(logging.DEBUG)
|
how to write a unicode csv in python 2.7,self.writer.writerow([str(s).encode('utf-8') for s in row])
|
isolation level with flask-sqlalchemy,db.session.query(Printer).all()
|
"parse a yaml file ""example.yaml""","with open('example.yaml') as stream:
|
try:
|
print((yaml.load(stream)))
|
except yaml.YAMLError as exc:
|
print(exc)"
|
matplotlib bar chart with dates,plt.show()
|
how do i format a number with a variable number of digits in python?,"""""""12344"""""".zfill(10)"
|
determine whether a key is present in a dictionary,"d.setdefault(x, []).append(foo)"
|
check if a global variable 'myvar' exists,"if ('myVar' in globals()):
|
pass"
|
map two lists into one single list of dictionaries,"[dict(zip(keys, a)) for a in zip(values[::2], values[1::2])]"
|
can i get a reference to a python property?,print(Foo.__dict__['bar'])
|
apply `numpy.linalg.norm` to each row of a matrix `a`,"numpy.apply_along_axis(numpy.linalg.norm, 1, a)"
|
right align string `mystring` with a width of 7,"""""""{:>7s}"""""".format(mystring)"
|
get element at index 0 of first row and element at index 1 of second row in array `a`,"A[[0, 1], [0, 1]]"
|
how to give a pandas/matplotlib bar graph custom colors,"df.plot(kind='bar', stacked=True, colormap='Paired')"
|
how to pass callable in django 1.9,"url('^$', 'recipes.views.index'),"
|
how to call base class's __init__ method from the child class?,"super(ChildClass, self).__init__(*args, **kwargs)"
|
export a pandas data frame `df` to a file `mydf.tsv` and retain the indices,"df.to_csv('mydf.tsv', sep='\t')"
|
how to check whether screen is off in mac/python?,main()
|
how do i make bar plots automatically cycle across different colors?,plt.show()
|
python: get the position of the biggest item in a numpy array,numpy.argwhere(a.max() == a)
|
organizing list of tuples,"l = [(1, 4), (8, 10), (19, 25), (10, 13), (14, 16), (25, 30)]"
|
including a django app's url.py is resulting in a 404,"urlpatterns = patterns('', ('^gallery/', include('mysite.gallery.urls')))"
|
list all files in directory `path`,os.listdir(path)
|
how can i determine the byte length of a utf-8 encoded string in python?,return len(s.encode('utf-8'))
|
how do i check if all elements in a list are the same?,len(set(mylist)) == 1
|
how to generate 2d gaussian with python?,"np.random.multivariate_normal(mean, cov, 10000)"
|
loop through 0 to 10 with step 2,"for i in range(0, 10, 2):
|
pass"
|
how can a pandas merge preserve order?,"x.reset_index().merge(y, how='left', on='state', sort=False).sort('index')"
|
"for each index `x` from 0 to 3, append the element at index `x` of list `b` to the list at index `x` of list a.",[a[x].append(b[x]) for x in range(3)]
|
what is the easiest way to convert list with str into list with int?,"map(int, ['1', '2', '3'])"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.