text
stringlengths 4
1.08k
|
|---|
how to assign unique identifier to dataframe row,df.head(10)
|
appending to list in python dictionary,"dates_dict.setdefault(key, []).append(date)"
|
random byte string in python,"buf = '\x00' + ''.join(chr(random.randint(0, 255)) for _ in range(4)) + '\x00'"
|
how to write integers to a file,"file.write('%s %s %s' % (ranks[a], ranks[b], count))"
|
iterate over a dictionary `dict` in sorted order,return sorted(dict.items())
|
tuple digits to number conversion,float(str(a[0]) + '.' + str(a[1]))
|
convert list to a list of tuples python,zip(*it)
|
how to map 2 lists with comparison in python,"[{'y': 2, 'location': 2}, {'z': 3, 'location': 2}]"
|
how do i get the name from a named tuple in python?,type(ham).__name__
|
is there a fast way to return sin and cos of the same value in python?,"a, b = np.sin(x), np.cos(x)"
|
sorting a set of values,"sorted(s, key=float)"
|
re.split with spaces in python,"re.findall('\\s+|\\S+', s)"
|
get a environment variable `debussy`,print(os.environ['DEBUSSY'])
|
what is the best way to create a string array in python?,strs = ['' for x in range(size)]
|
pandas. group by field and merge the values in a single row,df.set_index('id').stack().unstack()
|
finding consecutive segments in a pandas data frame,"df.reset_index().groupby(['A', 'block'])['index'].apply(np.array)"
|
fastest way to populate a 1d numpy array,"np.fromiter(a, dtype=np.float)"
|
python beautifulsoup give multiple tags to findall,"tags = soup.find_all(['hr', 'strong'])"
|
how to delete tkinter widgets from a window?,root.mainloop()
|
"regex in python to find words that follow pattern: vowel, consonant, vowel, consonant","""""""([aeiou]+[bcdfghjklmnpqrstvwxz]+)+"""""""
|
using a comparator function to sort,"sorted(subjects, operator.itemgetter(0), reverse=True)"
|
convert int to ascii and back in python,ord('a')
|
cartesian product of `x` and `y` array points into single array of 2d points,"numpy.dstack(numpy.meshgrid(x, y)).reshape(-1, 2)"
|
python pandas : group by in group by and average?,df.groupby(['cluster']).mean()
|
python - bulk select then insert from one db to another,cursor.execute('INSERT OR REPLACE INTO master.table1 SELECT * FROM table1')
|
how to: django template pass array and use it in javascript?,"['Afghanistan', 'Japan', 'United Arab Emirates']"
|
how to convert an h:mm:ss time string to seconds in python?,print(get_sec('0:00:25'))
|
how to split string into words that do not contain whitespaces in python?,"""""""This is a string"""""".split()"
|
unable to remove unicode char from column names in pandas,df.columns = [strip_non_ascii(x) for x in df.columns]
|
how to get a padded slice of a multidimensional array?,arr[-2:2]
|
what's a good approach to managing the db connection in a google cloud sql (gae) python app?,"cursor.execute('SELECT guestName, content, entryID FROM entries')"
|
getting seconds from numpy timedelta64,"np.diff(index) / np.timedelta64(1, 'm')"
|
printing a variable in an embedded python interpreter,Py_Finalize()
|
change unicode string into list?,"[float(i) for i in a.strip('{}').split(',')]"
|
how to remove whitespace from end of string in python?,"print('{}, you won!'.format(name))"
|
"missing data, insert rows in pandas and fill with nan",df.set_index('A')
|
string formatting in python,"print([1, 2, 3])"
|
how to get the size of tar.gz in (mb) file in python,os.path.getsize('flickrapi-1.2.tar.gz')
|
kill process with python,os.system('path/to/my_script.sh')
|
remove index 2 element from a list `my_list`,my_list.pop(2)
|
how to make a window jump to the front?,"root.attributes('-topmost', True)"
|
how to create range of numbers in python like in matlab,"print(np.linspace(1, 3, num=5))"
|
change figure size and figure format in matplotlib,"plt.figure(figsize=(3, 4))"
|
how do i disable log messages from the requests library?,logging.getLogger('urllib3').setLevel(logging.WARNING)
|
change one character in a string in python?,""""""""""""".join(s)"
|
python save to file,file.close()
|
draw a grid line on every tick of plot `plt`,plt.grid(True)
|
how to execute a command in the terminal from a python script?,subprocess.call('./driver.exe bondville.dat')
|
generate a sequence of numbers in python,""""""","""""".join(map(str, sorted(list(range(1, 100, 4))) + list(range(2, 100, 4))))"
|
"access environment variable ""home""",os.environ['HOME']
|
applying uppercase to a column in pandas dataframe,"df['1/2 ID'] = map(lambda x: x.upper(), df['1/2 ID'])"
|
delete none values from python dict,"D.update((k, v) for k, v in user.items() if v is not None)"
|
python/matplotlib - is there a way to make a discontinuous axis?,"ax2.plot(x, y, 'bo')"
|
how to write individual bits to a text file in python?,"open('file.bla', 'wb')"
|
how to add a string to every even row in a pandas dataframe column series?,print(df['New_Col'])
|
python requests getting sslerror,"requests.get('https://www.reporo.com/', verify='chain.pem')"
|
"get a sorted list of the characters of string `s` in lexicographic order, with lowercase letters first","sorted(s, key=str.lower)"
|
extend dictionary `a` with key/value pairs of dictionary `b`,a.update(b)
|
sum of all values in a python dict,sum(d.values())
|
"in pandas, why does tz_convert change the timezone used from est to lmt?",pytz.timezone('US/Eastern')
|
display a float with two decimal places in python,"""""""{0:.2f}"""""".format(5)"
|
getting a json request in a view (using django),return HttpResponse('')
|
get the count of each unique value in column `country` of dataframe `df` and store in column `sum of accidents`,df.Country.value_counts().reset_index(name='Sum of Accidents')
|
matplotlib colorbar for scatter,plt.show()
|
how to apply ceiling to pandas datetime,pd.Series(pd.PeriodIndex(df.date.dt.to_period('T') + 1).to_timestamp())
|
splitting a nested list into two lists,"my_list2, my_list1 = map(list, zip(*my_list))"
|
print the concatenation of the digits of two numbers in python,"print('%d%d' % (2, 1))"
|
how to check if an element from list a is not present in list b in python?,list([a for a in A if a not in B])
|
change permissions via ftp in python,ftp.quit()
|
how to apply ceiling to pandas datetime,"df.date + pd.to_timedelta(-df.date.dt.second % 60, unit='s')"
|
how to submit http authentication with selenium python-binding webdriver,driver.get('https://username:password@somewebsite.com/')
|
sub matrix of a list of lists (without numpy),[row[2:5] for row in LoL[1:4]]
|
merge a list of dictionaries in list `l` into a single dict,"{k: v for d in L for k, v in list(d.items())}"
|
how to check if two permutations are symmetric?,"Al = [al1, al2, al3, al4, al5, al6]"
|
python: how to escape 'lambda',"print(getattr(args, 'lambda'))"
|
python split string based on regular expression,"re.findall('\\S+', str1)"
|
load module from string in python,sys.modules['mymodule'] = mymodule
|
python: one-liner to perform an operation upon elements in a 2d array (list of lists)?,"[map(int, x) for x in values]"
|
how to determine a numpy-array reshape strategy,"arr = np.arange(3 * 4 * 5).reshape(3, 4, 5)"
|
my matplotlib title gets cropped,plt.subplots_adjust(top=0.5)
|
use of findall and parenthesis in python,"re.findall('\\b[A-Z]', formula)"
|
extracting key value pairs from string with quotes,"{'key1': 'value1', 'key2': 'value2,still_value2,not_key1=""not_value1""'}"
|
flask: using multiple packages in one app,app.run()
|
flask get posted form data 'firstname',first_name = request.form.get('firstname')
|
pythonic way to append list of strings to an array,entry_list.extend([entry.title.text for entry in feed.entry])
|
how to get http headers in flask?,request.headers['your-header-name']
|
python split string based on regular expression,"re.split(' +', str1)"
|
pygame - sound delay,pygame.init()
|
pandas dataframe to list,pd['a'].tolist()
|
convert a list to a dictionary in python,"dict((k, 2) for k in a)"
|
recursively replace characters in a dictionary,"{'delicious_apples': {'green_apples': 2}, 'green_pear': 4, 'brown_muffins': 5}"
|
looping through a list from a specific key to the end of the list,l[1:]
|
dynamic order in django-mptt,Comment.objects.all().order_by('-hotness')
|
regex matching 5-digit substrings not enclosed with digits in `s`,"re.findall('(?<!\\d)\\d{5}(?!\\d)', s)"
|
create a dataframe containing the multiplication of element-wise in dataframe `df` and dataframe `df2` using index name and column labels of dataframe `df`,"pd.DataFrame(df.values * df2.values, columns=df.columns, index=df.index)"
|
getting only element from a single-element list in python?,singleitem = next(iter(mylist))
|
convert an rgb image 'messi5.jpg' into grayscale `img`,"img = cv2.imread('messi5.jpg', 0)"
|
how to add a new row to an empty numpy array,"arr = np.empty((0, 3), int)"
|
batch renaming of files in a directory,"rename('c:\\temp\\xx', '*.doc', 'new(%s)')"
|
python pandas: plot histogram of dates?,"df.groupby([df.date.dt.year, df.date.dt.month]).count().plot(kind='bar')"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.