text
stringlengths 4
1.08k
|
|---|
communication between two computers using python socket,time.sleep(0.5)
|
pandas dataframe add column to index without resetting,"df.set_index(['d'], append=True)"
|
missing data in a column of pandas dataframe,"salesdata.loc[~salesdata.Outlet_Size.isnull(), 'Outlet_Size'].unique()"
|
how to add a colorbar for a hist2d plot,"plt.colorbar(im, ax=ax)"
|
converting a time string to seconds in python,"time.strptime('00:00:00,000'.split(',')[0], '%H:%M:%S')"
|
how to display image in pygame?,pygame.display.flip()
|
is there a way to leave an argument out of the help using python argparse,"parser.add_argument('--secret', help=argparse.SUPPRESS)"
|
how to find the indexes of matches in two lists,"[i for i, (a, b) in enumerate(zip(vec1, vec2)) if a == b]"
|
edit the values in a list of dictionaries?,"d.update((k, 'value3') for k, v in d.items() if v == 'value2')"
|
how to decrement a variable while printing in python?,print(decrement())
|
"find element `a` that contains string ""text a"" in file `root`","e = root.xpath('.//a[contains(text(),""TEXT A"")]')"
|
more elegant way to create a 2d matrix in python,a = [[(0) for y in range(8)] for x in range(8)]
|
"how do i modify a single character in a string, in python?",a = list('hello')
|
group the values from django model `article` with group by value `pub_date` and annotate by `title`,Article.objects.values('pub_date').annotate(article_count=Count('title'))
|
howto uncompress gzipped data in a byte array?,zlib.decompress(data)
|
create a list with the characters of a string `5+6`,list('5+6')
|
how to filter from csv file using python script,"csv.writer(open('abx.csv', 'w'), delimiter=' ').writerows(filtered)"
|
"python zlib output, how to recover out of mysql utf-8 table?",zlib.decompress(u.encode('latin1'))
|
copy list `old_list` as `new_list`,new_list = old_list[:]
|
find phone numbers in python script,"reg = re.compile('.*?(\\(?\\d{3}\\D{0,3}\\d{3}\\D{0,3}\\d{4}).*?', re.S)"
|
don't understand this python for loop,"[('pos1', 'target1'), ('pos2', 'target2')]"
|
write to utf-8 file in python,file.write('\ufeff')
|
how to pass a list of lists through a for loop in python?,"[[0.5, 0.625], [0.625, 0.375]]"
|
network pinging with python,os.system('ping -c 5 www.examplesite.com')
|
grouping pandas dataframe by n days starting in the begining of the day,df['dateonly'] = pd.to_datetime(df['dateonly'])
|
map two lists into a dictionary in python,"dict((k, v) for k, v in zip(keys, values))"
|
converting html to text with python,soup = BeautifulSoup(html)
|
best way to print list output in python,print('---'.join(vals))
|
how to compare two json objects with the same elements in a different order equal?,sorted(a.items()) == sorted(b.items())
|
round number 1.0005 up to 3 decimal places,"round(1.0005, 3)"
|
how do i coalesce a sequence of identical characters into just one?,"print(re.sub('-+', '-', astr))"
|
pandas dataframe `df` column 'a' to list,df['a'].values.tolist()
|
easier way to add multiple list items?,sum(sum(x) for x in lists)
|
how to check for a key in a defaultdict without updating the dictionary (python)?,"dct.get(key, 'ham')"
|
pretty-print ordered dictionary `o`,pprint(dict(list(o.items())))
|
how do i plot hatched bars using pandas?,"ax.legend(loc='center right', bbox_to_anchor=(1, 1), ncol=4)"
|
find all indices of maximum in pandas dataframe,"np.where(df.values == rowmax[:, (None)])"
|
pandas: combine two columns in a dataframe,"pandas.concat([df['foo'].dropna(), df['bar'].dropna()]).reindex_like(df)"
|
filter a dictionary `d` to remove keys with value 'none' and replace other values with 'updated',"dict((k, 'updated') for k, v in d.items() if v != 'None')"
|
how can i get an array of alternating values in python?,a[1::2] = -1
|
"check whether file ""/path/to/file"" exists","my_file = Path('/path/to/file')
|
if my_file.is_file():
|
pass"
|
get a new string with the 3rd to the second-to-last characters of string `x`,x[2:(-2)]
|
how can i speed up transition matrix creation in numpy?,"m3 = np.zeros((50, 50))"
|
flask : how to architect the project with multiple apps?,settings.py
|
get the immediate minimum among a list of numbers in python,a = list(a)
|
output first 100 characters in a string,print(my_string[0:100])
|
split string using a newline delimeter with python,print(data.split('\n'))
|
write the content of file `xxx.mp4` to file `f`,"f.write(open('xxx.mp4', 'rb').read())"
|
how to get only div with id ending with a certain value in beautiful soup?,soup.select('div[id$=_answer]')
|
max value within a list of lists of tuple,"max(flatlist, key=lambda x: x[1])"
|
summarizing a dictionary of arrays in python,"OrderedDict(heapq.nlargest(3, iter(mydict.items()), key=lambda tup: sum(tup[1])))"
|
convert hex string '0xdeadbeef' to decimal,ast.literal_eval('0xdeadbeef')
|
reading data blocks from a file in python,f = open('file_name_here')
|
"using scikit-learn classifier inside nltk, multiclass case","clf.fit(X_train, y_train)"
|
dirty fields in django,"super(Klass, self).save(*args, **kwargs)"
|
how to convert an integer timestamp back to utc datetime?,datetime.utcfromtimestamp(float(self.timestamp))
|
get dict key by max value,"max(d, key=d.get)"
|
how to get two random records with django,MyModel.objects.order_by('?')[:2]
|
how to reverse tuples in python?,reversed(x)
|
how can i plot hysteresis in matplotlib?,fig = plt.figure()
|
none,"datetime.datetime.strptime('2007-03-04T21:08:12', '%Y-%m-%dT%H:%M:%S')"
|
regex in python - using groups,"re.findall('\\bpresent\\b', tale)"
|
pythonic way to calculate streaks in pandas dataframe,"streaks(df, 'E')"
|
how do i halt execution in a python script?,sys.exit()
|
add items to a dictionary of lists,"dict(zip(keys, zip(*data)))"
|
insert row into excel spreadsheet using openpyxl in python,"wb.create_sheet(0, 'Sheet1')"
|
sympy : creating a numpy function from diagonal matrix that takes a numpy array,"Matrix([[32.4, 32.4, 32.4], [32.8, 32.8, 32.8], [33.2, 33.2, 33.2]])"
|
get a list of values for key 'key' from a list of dictionaries `l`,[d['key'] for d in l]
|
search for the last occurence in multiple columns in a dataframe,df.stack(level=0).groupby('team').tail(1)
|
"python code simplification? one line, add all in list",sum(int(n) for n in str(2 ** 1000))
|
python sockets: enabling promiscuous mode in linux,"s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)"
|
get sql headers from numpy array in python,"[('a', '<i4'), ('b', '<i4'), ('c', '<i4')]"
|
sum the second value of each tuple in a list,sum(zip(*structure)[1])
|
flask application traceback doesn't show up in server log,app.run(debug=True)
|
multiprocessing.pool with a global variable,"pool = Pool(4, initializer, ())"
|
iterating through directories with python,"print(os.path.join(subdir, file))"
|
multiplication of 1d arrays in numpy,"np.dot(a[:, (None)], b[(None), :])"
|
multiply high order matrices with numpy,"np.tensordot(ind, dist, axes=[1, 1])[0].T"
|
how does python variable scoping works?,example2()
|
find all files with extension '.c' in directory `folder`,results += [each for each in os.listdir(folder) if each.endswith('.c')]
|
how to get all sub-elements of an element tree with python elementtree?,[elem.tag for elem in a.iter() if elem is not a]
|
python/matplotlib - is there a way to make a discontinuous axis?,plt.show()
|
python check if all elements of a list are the same type,"all(isinstance(x, int) for x in lst)"
|
how do i exclude an inherited field in a form in django?,self.fields.pop('is_staff')
|
find and replace 2nd occurrence of word 'cat' by 'bull' in a sentence 's',"re.sub('^((.*?cat.*?){1})cat', '\\1Bull', s)"
|
how to sort a pandas dataframe according to multiple criteria?,"df.sort_values(['Peak', 'Weeks'], ascending=[True, False], inplace=True)"
|
how to select only specific columns from a dataframe with multiindex columns?,"data.loc[:, ([('one', 'a'), ('one', 'c'), ('two', 'a'), ('two', 'c')])]"
|
how to flatten a tuple in python,"[(a, b, c) for a, (b, c) in l]"
|
set default directory of pydev interactive console?,sys.path.append('F:\\projects\\python')
|
how can i sum the product of two list items using for loop in python?,"sum(x * y for x, y in zip(a, b))"
|
rename file `dir` to `dir` + '!',"os.rename(dir, dir + '!')"
|
can i sort text by its numeric value in python?,"sorted(list(mydict.items()), key=lambda a: map(int, a[0].split('.')))"
|
get index of elements in array `a` that occur in another array `b`,"np.where(np.in1d(A, B))[0]"
|
python dataframe pandas drop column using int,"df.drop(df.columns[i], axis=1)"
|
delete digits in python (regex),"re.sub('$\\d+\\W+|\\b\\d+\\b|\\W+\\d+$', '', s)"
|
remove all instances of parenthesesis containing text beginning with `as ` from string `line`,"line = re.sub('\\(+as .*?\\) ', '', line)"
|
check if key 'key1' in `dict`,('key1' in dict)
|
"join multiple dataframes `d1`, `d2`, and `d3` on column 'name'","df1.merge(df2, on='name').merge(df3, on='name')"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.