text
stringlengths
4
1.08k
how to execute manage.py from the python shell,"execute_from_command_line(['manage.py', 'syncdb'])"
filtering elements from list of lists in python?,[item for item in a if sum(item) > 10]
how to import a module from a directory on level above the current script,sys.path.append('..')
python matplotlib - contour plot - confidence intervals,plt.show()
get a list comparing two lists of tuples `l1` and `l2` if any first value in `l1` matches with first value in `l2`,[x[0] for x in l1 if any(x[0] == y[0] for y in l2)]
is there a python equivalent of ruby's 'any?' function?,any(pred(x) for x in lst)
how can i convert a tensor into a numpy array in tensorflow?,"print(type(tf.Session().run(tf.constant([1, 2, 3]))))"
"list all files of a directory ""somedirectory""",os.listdir('somedirectory')
increase the linewidth of the legend lines in matplotlib,plt.show()
find next sibling element in python selenium?,"driver.find_element_by_xpath(""//p[@id, 'one']/following-sibling::p"")"
how to print a list of tuples,"a, b, c = 'a', 'b', 'c'"
'module' object has no attribute 'now' will trying to create a csv,datetime.datetime.now()
skip the newline while printing `line`,print(line.rstrip('\n'))
"how can i ""unpivot"" specific columns from a pandas dataframe?","pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value')"
numpy array: replace nan values with average of columns,"ma.array(a, mask=np.isnan(a)).mean(axis=0)"
substitute two or more whitespace characters with character '|' in string `line`,"re.sub('\\s{2,}', '|', line.strip())"
more pythonic way to format a json string from a list of tuples,"(lambda lst: json.dumps({item[0]: item[1] for item in lst}))([(1, 2), (3, 4)])"
how to keep a python script output window open?,input('Press enter to exit ;)')
how to save a list as numpy array in python?,"myArray = np.load(open('array.npy', 'rb'))"
"reversal of string.contains in python, pandas",df['A'].str.contains('^(?:(?!Hello|World).)*$')
how do i print bold text in python?,print('\x1b[1m' + 'Hello')
how to sort pandas data frame using values from several columns?,"df.sort(['c1', 'c2'], ascending=[True, True])"
pythonic way of comparing all adjacent elements in a list,A = [(A[i + 1] + A[i]) for i in range(len(A) - 1)]
python dict to numpy structured array,"numpy.array([(key, val) for key, val in result.items()], dtype)"
sort list `l` based on its elements' digits,"sorted(l, key=lambda x: int(re.search('\\d+', x).group(0)))"
print file age in seconds using python,print('mdatetime = {}'.format(datetime.datetime.fromtimestamp(mtime)))
how to get the size of a string in python?,print(len('please anwser my question'))
using multiple colors in matplotlib plot,plt.show()
"formatting ""yesterday's"" date in python",print(yesterday.strftime('%m%d%y'))
get the dot product of two one dimensional numpy arrays,"np.dot(a[:, (None)], b[(None), :])"
convert float series into an integer series in pandas,"df['time'] = pd.to_datetime(df['time'], unit='s')"
"open a file ""$file"" under unix","os.system('start ""$file""')"
sorting json data by keys value,"sorted(results, key=itemgetter('year'))"
access an arbitrary element in a dictionary in python,list(dict.keys())[0]
how do i check if all elements in a list are the same?,all(x == mylist[0] for x in mylist)
having trouble with beautifulsoup in python,divs = soup.select('#fnd_content div.fnd_day')
"sorting a list of tuples `lst` by the sum of the second elements onwards, and third element of the tuple","sorted(lst, key=lambda x: (sum(x[1:]), x[0]))"
first non-null value per row from a list of pandas columns,df.stack().groupby(level=0).first()
how to equalize the scales of x-axis and y-axis in python matplotlib?,plt.draw()
regular expression parsing a binary file?,r = re.compile('(This)')
calling a function of a module from a string with the function's name in python,globals()['myfunction']()
python: get the first character of a the first string in a list?,"['b', 's', 't']"
get the dimensions of numpy array `a`,a.shape
removing element from a list in python,del L[index]
search for a file using a wildcard,glob.glob('?.gif')
compare python pandas dataframes for matching rows,"pd.merge(df1, df2, on=common_cols, how='inner')"
how do i escape closing '/' in html tags in json with python?,"""""""{""asset_id"": ""575155948f7d4c4ebccb02d4e8f84d2f"", ""body"": ""\\u003cscript\\u003e\\u003c/script\\u003e"", ""asset_created"": null}"""""""
wildcard matching a string in python regex search,pattern = '6 of\\s+(.+?)\\s+fans'
numpy - group data into sum values,"[(1, 4), (2, 3), (0, 1, 4), (0, 2, 3)]"
tokenize a string keeping delimiters in python,re.compile('(\\s+)').split('\tthis is an example')
pandas: how to find the max n values for each category in a column,"[['A', 'Book2', '10'], ['B', 'Book1', '7'], ['B', 'Book2', '5']]"
python creating tuple groups in list from another list,"[([1, 2, 3], [-4, -5]), ([3, 2, 4], [-2]), ([5, 6], [-5, -1]), ([1], [])]"
python add comma into number string,"print('Total cost is: ${:,.2f}'.format(TotalAmount))"
how do you filter pandas dataframes by multiple columns,males = df[(df[Gender] == 'Male') & (df[Year] == 2014)]
simple/efficient way to expand a pandas dataframe,"pd.merge(y, x, on='k')[['a', 'b', 'y']]"
"syntaxerror: invalid token in datetime.datetime(2012,05,22,09,03,41)?","datetime.datetime(2012, 5, 22, 9, 3, 41)"
python numpy: how to count the number of true elements in a bool array,np.count_nonzero(boolarr)
convert string `s` to lowercase,s.lower()
get a new string including the last two characters of string `x`,x[(-2):]
removing key values pairs with key 'mykey1' from a list of dictionaries `mylist`,"[{k: v for k, v in d.items() if k != 'mykey1'} for d in mylist]"
"sort a list of tuples 'unsorted' based on two elements, second and third","sorted(unsorted, key=lambda element: (element[1], element[2]))"
"getting a sublist of a python list, with the given indices?","[0, 2, 4, 5]"
is there a random letter generator with a range?,random.choice(string.ascii_letters[0:4])
"turn list of categorical variables into (0,1) list","c = np.unique(a, return_inverse=1)[1]"
appending to a pandas dataframe from a pd.read_sql output,"df = df.append(pd.read_sql(querystring, cnxn, params=[i]))"
sort a list of strings `list`,list.sort()
converting a list to a string,""""""""""""".join(buffer)"
generate all possible strings from a list of token,"print(list(combinations(['hel', 'lo', 'bye'], 2)))"
pythonic way to convert list of dicts into list of namedtuples,"items = [some(a.split(), d, n) for a, d, n in (list(m.values()) for m in dl)]"
remove dtype at the end of numpy array,"data = numpy.loadtxt(fileName, dtype='float')"
select rows of dataframe `df` whose value for column `a` is `foo`,print(df.loc[df['A'] == 'foo'])
sum of products for multiple lists in python,"sum([(x * y) for x, y in zip(*lists)])"
case insensitive python string split() method,regex = re.compile('\\s*[Ff]eat\\.\\s*')
splitting a string into a list (but not separating adjacent numbers) in python,"re.findall('\\d+|[^\\d\\s]+', string)"
create list `randomlist` with 10 random floating point numbers between 0.0 and 1.0,randomList = [random.random() for _ in range(10)]
how can i convert an rgb image into grayscale in python?,"gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)"
"python: dictionary to string, custom format?",""""""", """""".join('='.join((str(k), str(v))) for k, v in list(mydict.items()))"
what's the best way to search for a python dictionary value in a list of dictionaries?,any(d['site'] == 'Superuser' for d in data)
is it possible to plot timelines with matplotlib?,ax.spines['right'].set_visible(False)
pandas: how can i remove duplicate rows from dataframe and calculate their frequency?,"df1.groupby(['key', 'year']).size().reset_index()"
"write variable to file, including name",f.close()
can i set dataframe values without using iterrows()?,df.C[df.B == 'x'] = df.C.shift(-1)
"string split on new line, tab and some number of spaces",[s.strip().split(': ') for s in data_string.splitlines()]
calling types via their name as a string in python,"getattr(__builtin__, 'int')"
merge two existing plots into one plot,plt.show()
regex add character to matched string,"re.sub('(?<=\\.)(?!\\s)', ' ', para)"
deep copy list `old_list` as `new_list`,new_list = copy.deepcopy(old_list)
"is it ok to raise a built-in exception, but with a different message, in python?",raise ValueError('some problem: %s' % value)
changing image hue with python pil,new_img.save('tweeter_green.png')
pandas: check if row exists with certain values,index_list = df[(df['A'] == 2) & (df['B'] == 3)].index.tolist()
"python list comprehension, with unique items","['n', 'e', 'v', 'r', ' ', 'g', 'o', 'a', 'i', 'y', 'u', 'p']"
how do i stack vectors of different lengths in numpy?,"ma.vstack([a, ma.array(np.resize(b, a.shape[0]), mask=[False, False, True])])"
how do i model a many-to-many relationship over 3 tables in sqlalchemy (orm)?,session.query(Shots).filter_by(event_id=event_id).count()
convert the sum of list `walls` into a hex presentation,"hex(sum(b << i for i, b in enumerate(reversed(walls))))"
how do i convert a numpy array into a pandas dataframe?,"df = pd.DataFrame({'R': px2[:, (0)], 'G': px2[:, (1)], 'B': px2[:, (2)]})"
find the indices of elements greater than x,"[i for i, v in enumerate(a) if v > 4]"
how to compute weighted sum of all elements in a row in pandas?,df.dot(weight)
kill process with python,os.system('your_command_here; second_command; third; etc')
convert list into string with spaces in python,""""""" """""".join(my_list)"
filter django objects by `author` with ids `1` and `2`,Book.objects.filter(author__id=1).filter(author__id=2)