text
stringlengths 4
1.08k
|
|---|
removing duplicate strings from a list in python,a = list(set(a))
|
append string to the start of each value in a said column of a pandas dataframe (elegantly),df['col'] = 'str' + df['col'].astype(str)
|
get the sum of values to the power of their indices in a list `l`,"sum(j ** i for i, j in enumerate(l, 1))"
|
return a list of weekdays,weekdays('Wednesday')
|
importing a python package from a script with the same name,"sys.path.insert(0, '..')"
|
"difference between using commas, concatenation, and string formatters in python","print('I am printing {} and {}'.format(x, y))"
|
adding url to mysql row in python,"cursor.execute('INSERT INTO `index`(url) VALUES(%s)', (url,))"
|
getting a list with new line characters,"pattern = re.compile('(.)\\1?', re.IGNORECASE | re.DOTALL)"
|
how to install python packages in virtual environment only with virtualenv bootstrap script?,"subprocess.call(['pip', 'install', '-E', home_dir, 'django'])"
|
properly quit a program,sys.exit(0)
|
"extract file name from path, no matter what the os/path format",print(os.path.basename(your_path))
|
python equivalent for hashmap,my_dict = {'cheese': 'cake'}
|
how do you convert a python time.struct_time object into a iso string?,"time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup)"
|
constructing a python set from a numpy matrix,y = set(x.flatten())
|
open image 'picture.jpg',"img = Image.open('picture.jpg')
|
img.show()"
|
how to add group labels for bar charts in matplotlib?,ax.set_xticklabels(x)
|
sorting dictionary by numeric value,"sorted(list(tag_weight.items()), key=lambda x: int(x[1]), reverse=True)"
|
how can i find a process by name and kill using ctypes?,subprocess.call('taskkill /IM exename.exe')
|
return common element indices between two numpy arrays,"numpy.nonzero(numpy.in1d(a2, a1))[0]"
|
finding index of maximum value in array with numpy,x[np.where(x == 5)]
|
how can i format a float using matplotlib's latex formatter?,"ax.set_title('${0} \\times 10^{{{1}}}$'.format('3.5', '+20'))"
|
how to subset a data frame using pandas based on a group criteria?,df.loc[df.groupby('User')['X'].filter(lambda x: x.sum() == 0).index]
|
"finding minimum, maximum and average values for nested lists?","max(PlayerList, key=lambda p: max(p[1:]))[0]"
|
how to design code in python?,duck.quack()
|
dot notation string manipulation,"re.sub('\\.[^.]+$', '', s)"
|
multi-column factorize in pandas,df.drop_duplicates()
|
how to calculate the axis of orientation?,plt.show()
|
communicate multiple times with a process without breaking the pipe?,proc.stdin.write('message2')
|
fill missing value in one column 'cat1' with the value of another column 'cat2',df['Cat1'].fillna(df['Cat2'])
|
how to write a lambda function that is conditional on two variables (columns) in python,"df['dummyVar '] = df['x'].where((df['x'] > 100) & (df['y'] < 50), df['y'])"
|
get all the texts without tags from beautiful soup object `soup`,""""""""""""".join(soup.findAll(text=True))"
|
how to find shortest path in a weighted graph using networkx?,"nx.dijkstra_path(g, 'b', 'b', 'distance')"
|
delete column from pandas dataframe,"df.drop('column_name', axis=1, inplace=True)"
|
testing whether a numpy array contains a given row,"equal([1, 2], a).all(axis=1)"
|
"how can i get the values that are common to two dictionaries, even if the keys are different?",list(set(dict_a.values()) & set(dict_b.values()))
|
changing the application and taskbar icon - python/tkinter,root.iconbitmap(default='ardulan.ico')
|
split a string `s` on last delimiter,"s.rsplit(',', 1)"
|
get last day of the second month in year 2012,"monthrange(2012, 2)"
|
is it possible to stream output from a python subprocess to a webpage in real time?,time.sleep(1)
|
convert python dictionary to json array,"json.dumps(your_data, ensure_ascii=False)"
|
utf-8 compatible compression in python,json.dumps({'compressedData': base64.b64encode(zString)})
|
print a list of integers `list_of_ints` using string formatting,"print(', '.join(str(x) for x in list_of_ints))"
|
how to replace repeated instances of a character with a single instance of that character in python,"re.sub('\\*+', '*', text)"
|
sort a list of tuples alphabetically and by value,"sorted(list_of_medals, key=lambda x: (-x[1], x[0]))"
|
how to modify a variable inside a lambda function?,"return myFunc(lambda a, b: iadd(a, b))"
|
python argparse with dependencies,"parser.add_argument('host', nargs=1, help='ip address to lookup')"
|
average values in two numpy arrays,"np.mean(np.array([old_set, new_set]), axis=0)"
|
combining two series in pandas along their index,"pd.concat([s1, s2], axis=1)"
|
what is a good size (in bytes) for a log file?,"RotatingFileHandler(filename, maxBytes=10 * 1024 * 1024, backupCount=5)"
|
force bash interpreter '/bin/bash' to be used instead of shell,"os.system('GREPDB=""echo 123""; /bin/bash -c ""$GREPDB""')"
|
how do i convert lf to crlf?,"txt.replace('\n', '\r\n')"
|
python tkinter: displays only a portion of an image,"self.canvas.create_image(0, 0, image=image1, anchor=NW)"
|
convert integer to binary,"map(int, bin(6)[2:])"
|
how to change legend size with matplotlib.pyplot,"pyplot.legend(loc=2, fontsize='x-small')"
|
how to convert a datetime string back to datetime object?,"datetime.strptime('2010-11-13 10:33:54.227806', '%Y-%m-%d %H:%M:%S.%f')"
|
how to convert integer value to array of four bytes in python,"tuple(struct.pack('!I', number))"
|
remove elements from list `centroids` the indexes of which are in array `index`,"[element for i, element in enumerate(centroids) if i not in index]"
|
make function `writefunction` output nothing in curl `p`,"p.setopt(pycurl.WRITEFUNCTION, lambda x: None)"
|
add string in a certain position in python,s[:4] + '-' + s[4:]
|
python remove anything that is not a letter or number,"re.sub('[\\W_]+', '', s, flags=re.UNICODE)"
|
verify if a string is json in python?,"print(is_json('{""age"":100 }'))"
|
get a list of items in the list `container` with attribute equal to `value`,items = [item for item in container if item.attribute == value]
|
regular expression matching all but a string,"res = re.findall('-(?!(?:aa|bb)-)(\\w+)(?=-)', s)"
|
django - correct way to load a large default value in a model,schema = models.TextField(default=get_default_json)
|
how to perform element-wise multiplication of two lists in python?,ab = [(a[i] * b[i]) for i in range(len(a))]
|
python sorting - a list of objects,s.sort(key=operator.attrgetter('resultType'))
|
compare if an element exists in two lists,set(a).intersection(b)
|
how to convert numpy datetime64 into datetime,x.astype('M8[ms]').astype('O')
|
pandas - grouping intra day timeseries by date,"df.groupby(pd.TimeGrouper('D')).transform(np.cumsum).resample('D', how='ohlc')"
|
how do i abort the execution of a python script?,sys.exit()
|
python: how do i randomly select a value from a dictionary key?,"['Protein', 'Green', 'Squishy']"
|
how do i order fields of my row objects in spark (python),"rdd = sc.parallelize([(1, 2)])"
|
how can i fill a matplotlib grid?,"plt.plot(x, y, 'o')"
|
add scrolling to a platformer in pygame,pygame.display.update()
|
sorting the lists in list of lists `data`,[sorted(item) for item in data]
|
sorting a dictionary by highest value of nested list,"OrderedDict([('b', 7), ('a', 5), ('c', 3)])"
|
python: converting from tuple to string?,"s += '(' + ', '.join(map(str, tup)) + ')'"
|
"how do i launch a file in its default program, and then close it when the script finishes?","subprocess.Popen('start /WAIT ' + self.file, shell=True)"
|
how do i get the id of an object after persisting it in pymongo?,collection.remove({'_id': ObjectId('4c2fea1d289c7d837e000000')})
|
sorting a list of tuples such that grouping by key is not desired,"[(1, 2), (3, 4), (1, 3), (2, 4), (1, 4), (2, 3)]"
|
how to switch between python 2.7 to python 3 from command line?,print('hello')
|
convert datetime object to date object in python,datetime.datetime.now().date()
|
how to generate a list from a pandas dataframe with the column name and column values?,df.values.tolist()
|
how do i pass a variable by reference?,"print(('after, outer_list =', outer_list))"
|
reading data from text file with missing values,"genfromtxt('missing1.dat', delimiter=',')"
|
how to split a string at line breaks in python?,[row.split('\t') for row in s.splitlines()]
|
creating a dictionary from a csv file,"{'Date': ['Foo', 'Bar'], '123': ['456', '789'], 'abc': ['def', 'ghi']}"
|
how do i compare values in a dictionary?,"print(max(d, key=lambda x: (d[x]['salary'], d[x]['bonus'])))"
|
evaluate the expression '20<30',eval('20<30')
|
how to disable the minor ticks of log-plot in matplotlib?,plt.show()
|
copy list `old_list` and name it `new_list`,new_list = [x[:] for x in old_list]
|
how to make two markers share the same label in the legend using matplotlib?,ax.set_ylabel('Temperature ($^\\circ$C)')
|
how to store numerical lookup table in python (with labels),"{'_id': 'run_unique_identifier', 'param1': 'val1', 'param2': 'val2'}"
|
simple way to append a pandas series with same index,"pd.Series(np.concatenate([a, b]))"
|
converting a list of tuples into a dict in python,"{'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}"
|
get digits in string `my_string`,""""""""""""".join(c for c in my_string if c.isdigit())"
|
python accessing values in a list of dictionaries,[d['Name'] for d in thisismylist]
|
"how to replace custom tabs with spaces in a string, depend on the size of the tab?","line = line.replace('\t', ' ')"
|
get modified time of file `file`,print(('last modified: %s' % time.ctime(os.path.getmtime(file))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.