text
stringlengths
4
1.08k
getting unique values from lists(containing tags) in dataframe row,df.genres.apply(pd.Series).stack().drop_duplicates().tolist()
python filter/remove urls from a list,list2 = [line for line in file if 'CONTENT_ITEM_ID' in line]
select multiple columns in pandas data frame with column index as sequential number,"df.iloc[:, (your_col_index)]"
add second axis to polar plot,plt.show()
replace non-ascii characters with a single space,"re.sub('[^\\x00-\\x7f]', ' ', n)"
how to reverse query objects for multiple levels in django?,Level4.objects.filter(level3__level2__level1=my_level1_object)
multiple assigments with a comma in python,"a = b, c = 'AB'"
how do i divide the members of a list by the corresponding members of another list in python?,"[(c / t) for c, t in zip(conversions, trials)]"
clamping floating numbers in python?,"max(min(my_value, max_value), min_value)"
getting unique indices of minimum values in multiple lists,"[0, 3, 1, 2]"
normalize columns of pandas data frame,df = df / df.max().astype(np.float64)
python comprehension loop for dictionary,sum(item['one'] for item in list(tadas.values()))
how do i vectorize this loop in numpy?,"np.ma.array(np.tile(arr, 2).reshape(2, 3), mask=~cond).argmax(axis=1)"
gets the `n` th-to-last element in list `some_list`,some_list[(- n)]
"from list of integers, get number closest to a given value","min(myList, key=lambda x: abs(x - myNumber))"
round number `value` up to `significantdigit` decimal places,"round(value, significantDigit)"
"concatenate strings in tuple `('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')` into a single string",""""""""""""".join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))"
how to set first column to a constant value of an empty np.zeros numpy matrix?,"myArray = np.zeros((6, 6))"
python - delete blank lines of text at the end of the file,file_out[-1] = file_out[-1].strip('\n')
pandas: keeping only first row of data in each 60 second bin,df[df.time.diff().fillna(pd.Timedelta('60S')) >= pd.Timedelta('60S')]
redirecting a user in a django template,return HttpResponseRedirect('/path/')
creating unit tests for methods with global variables,unittest.main()
is it possible for beautifulsoup to work in a case-insensitive manner?,"soup.findAll('meta', name=re.compile('^description$', re.I))"
split dictionary of lists into list of dictionaries,"[{'key1': a, 'key2': b} for a, b in zip(d['key1'], d['key2'])]"
reverse each word in a string,""""""" """""".join(w[::-1] for w in s.split())"
log message 'test' on the root logger.,logging.info('test')
removing white space from txt with python,"subbed = re.sub('\\s{2,}', '|', line.strip())"
get the size of list `s`,len(s)
how to upload image file from django admin panel ?,"urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)"
"in python, find out number of differences between two ordered lists","sum(1 for i, j in zip(a, b) if i != j)"
"in python, is there a concise way to use a list comprehension with multiple iterators?","[(i, j) for i in range(10) for j in range(i)]"
"python, numpy; how to insert element at the start of an array","np.insert(my_array, 0, myvalue, axis=1)"
does python have a built in function for string natural sort?,"['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']"
pandas dataframe with 2-rows header and export to csv,"df.to_csv(f, index=False, header=False)"
django equivalent of count with group by,Player.objects.values('player_type').order_by().annotate(Count('player_type'))
how do i format axis number format to thousands with a comma in matplotlib?,"""""""{:,}"""""".format(10000.21)"
find all the lists from a lists of list 'items' if third element in all sub-lists is '0',[x for x in items if x[2] == 0]
python regex split case insensitive in 2.6,"re.compile('XYZ', re.IGNORECASE).split('fooxyzbar')"
replace console output in python,sys.stdout.flush()
how can i get a file's permission mask?,stat.S_IMODE(os.lstat('file').st_mode)
how to subset a data frame using pandas based on a group criteria?,df.loc[df.groupby('User')['X'].transform(sum) == 0]
how are post and get variables handled in python?,print(request.form['username'])
google app engine: webtest simulating logged in user and administrator,os.environ['USER_EMAIL'] = 'info@example.com'
problems while trying to generate pandas dataframe columns from regulars expressions?,"print(pd.DataFrame(list(file_to_adverb_dict.items()), columns=['file_names', 'col1']))"
python: is there a library function for chunking an input stream?,"[data[i:i + n] for i in range(0, len(data), n)]"
how to get week number in python?,"datetime.date(2010, 6, 16).isocalendar()[1]"
how to properly split this list of strings?,"[['z', '+', '2', '-', '44'], ['4', '+', '55', '+((', 'z', '+', '88', '))']]"
python how to sort this list?,"sorted(lst, reverse=True)"
numpy - set values in structured array based on other values in structured array,"a = numpy.zeros((10, 10), dtype=[('x', int), ('y', 'a10')])"
pandas data frame indexing using loc,"pd.Series([pd.Timestamp('2014-01-02'), 'THU', 'THU'])"
close a tkinter window?,root.quit()
sort a list of strings based on regular expression match or something similar,"strings.sort(key=lambda str: re.sub('.*%(.).*', '\\1', str))"
assign float 9.8 to variable `gravity`,GRAVITY = 9.8
multiply two pandas series with mismatched indices,s1.reset_index(drop=True) * s2.reset_index(drop=True)
how to hide output of subprocess in python 2.7,"subprocess._check_call(['espeak', text], stdout=FNULL, stderr=FNULL)"
unable to click the checkbox via selenium in python,element.click()
sum elements of tuple `b` to their respective elements of each tuple in list `a`,"c = [[(i + j) for i, j in zip(e, b)] for e in a]"
merging data frame columns of strings into one single column in pandas,"df.apply(' '.join, axis=1)"
binarize the values in columns of list `order` in a pandas data frame,"pd.concat([df, pd.get_dummies(df, '', '').astype(int)], axis=1)[order]"
getting the opposite diagonal of a numpy array,np.diag(np.rot90(array))
how to import a module from a folder next to the current folder?,"sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))"
appending data into an undeclared list,"l = [(x * x) for x in range(0, 10)]"
how to redirect python warnings to a custom stream?,warnings.warn('test warning')
creating a list of objects in python,simplelist.append(x)
selecting element followed by text with selenium webdriver,"driver.find_element_by_xpath(""//li/label/input[contains(..,'polishpottery')]"")"
how to define two-dimensional array in python,matrix = [([0] * 5) for i in range(5)]
equivalent of j in numpy,1j * np.arange(5)
debianzing a python program to get a .deb,myscript.py
python: find the first mismatch in two lists,"next((idx, x, y) for idx, (x, y) in enumerate(zip(list1, list2)) if x != y)"
is there a way to use phantomjs in python?,driver.get('https://google.com/')
how can i generate more colors on pie chart matplotlib,plt.show()
python regex split a string by one of two delimiters,"sep = re.compile('[\\s,]+')"
how to compute a new column based on the values of other columns in pandas - python,df['c'] = (df.a.str[-1] == df.b).astype(int)
matplotlib: how to plot images instead of points?,plt.show()
variable number of digit in format string,"""""""{0:.{1}%}"""""".format(value, digits)"
how to add an image in tkinter (python 2.7),root.mainloop()
webbrowser open url 'http://example.com',webbrowser.open('http://example.com')
how to parse dst date in python?,"datetime.datetime(2013, 4, 25, 13, 32)"
replace values in an array,"np.place(a, np.isnan(a), 0)"
recursively remove folder `name`,os.removedirs(name)
abort the execution of the script using message 'aa! errors!',sys.exit('aa! errors!')
two combination lists from one list,itertools.combinations
django orm query group by multiple columns combined by max,"MM.objects.all().values('b', 'a').annotate(max=Max('c'))"
is there a fast way to generate a dict of the alphabet in python?,"d = dict.fromkeys(string.ascii_lowercase, 0)"
how to count the number of a specific character at the end of a string ignoring duplicates?,len(my_text) - len(my_text.rstrip('?'))
retrieve parameter 'var_name' from a get request.,self.request.get('var_name')
join last element in list,""""""" & """""".join(['_'.join(inp[i:j]) for i, j in zip([0, 2], [2, None])])"
sort objects in model `profile` based on theirs `reputation` attribute,"sorted(Profile.objects.all(), key=lambda p: p.reputation)"
python - bulk select then insert from one db to another,"cursor.execute('ATTACH ""/path/to/main.sqlite"" AS master')"
gpgpu programming in python,"sum(clarray1, clarray2, clarray3)"
case insensitive string comparison between `first` and `second`,(first.lower() == second.lower())
how to use map to lowercase strings in a dictionary?,[{'content': x['content'].lower()} for x in messages]
select all rows whose values in a column `column_name` equals a scalar `some_value` in pandas data frame object `df`,df.loc[df['column_name'] == some_value]
extracting date from a string in python,"dparser.parse('monkey 10/01/1980 love banana', fuzzy=True)"
convert radians 1 to degrees,math.cos(math.radians(1))
fastest way to remove first and last lines from a python string,s[s.find('\n') + 1:s.rfind('\n')]
convert integer to hex-string with specific format,hex(x)[2:].decode('hex')
what is the most pythonic way to test for match with first item of tuple in sequence of 2-tuples?,any(x[0] == 'a' for x in seq_of_tups)
how to customize the time format for python logging?,formatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s')
finding and substituting a list of words in a file using regex in python,"a = ['cat', 'dog', 'mouse']"