text
stringlengths
4
1.08k
joining two dataframes from the same source,"df_one.join(df_two, df_one['col1'] == df_two['col1'], 'inner')"
display first 5 characters of string 'aaabbbccc',"""""""{:.5}"""""".format('aaabbbccc')"
is there any way to get a repl in pydev?,pdb.set_trace()
how to specify the endiannes directly in the numpy datatype for a 16bit unsigned integer?,"np.memmap('test.bin', dtype=np.dtype('>u2'), mode='r')"
equivalent of notimplementederror for fields in python,raise NotImplementedError('Subclasses should implement this!')
remove string between 2 characters from text string,"re.sub('\\[.*?\\]', '', 'abcd[e]yth[ac]ytwec')"
convert dictionary `dict` into a string formatted object,"'{' + ','.join('{0!r}:{1!r}'.format(*x) for x in list(dct.items())) + '}'"
how to set environment variables in python,os.environ['DEBUSSY'] = str(myintvariable)
how to convert pandas dataframe so that index is the unique set of values and data is the count of each value?,df['Qu1'].value_counts()
django filter by datetime on a range of dates,"queryset.filter(created_at__range=(start_date, end_date))"
understanding == applied to a numpy array,np.array([(labels == i).astype(np.float32) for i in np.arange(3)])
how to show matplotlib plots in python,"plt.plot(x, y)"
algorithm - how to delete duplicate elements in a list efficiently?,M = list(set(L))
get a numpy array that contains the element wise minimum of three 3x1 arrays,"np.array([np.arange(3), np.arange(2, -1, -1), np.ones((3,))]).min(axis=0)"
getting today's date in yyyy-mm-dd,datetime.datetime.today().strftime('%Y-%m-%d')
"replace items in list, python","yourlist = ['{}_{}_{}'.format(s.rsplit('_', 2)[0], x, y) for s in yourlist]"
unpack keys and values of a dictionary `d` into two lists,"keys, values = zip(*list(d.items()))"
how to remove the space between subplots in matplotlib.pyplot?,plt.show()
insert elements of list `k` into list `a` at position `n`,a = a[:n] + k + a[n:]
how to add border around an image in opencv python,cv2.destroyAllWindows()
python: dots in the name of variable in a format string,"""""""Name: {0[person.name]}"""""".format({'person.name': 'Joe'})"
python find list lengths in a sublist,[len(x) for x in a[0]]
"print the string `total score for`, the value of the variable `name`, the string `is` and the value of the variable `score` in one print call.","print(('Total score for', name, 'is', score))"
how to find most common elements of a list?,"['you', 'i', 'a']"
pythonic shorthand for keys in a dictionary?,"{'foo', 'bar', 'baz'}.issubset(list(dct.keys()))"
printing tuple with string formatting in python,"print('this is a tuple: %s' % (thetuple,))"
"how to create ""virtual root"" with python's elementtree?",tree.write('outfile.htm')
how to convert string to byte arrays?,"map(ord, 'Hello, \u9a6c\u514b')"
how to retrieve table names in a mysql database with python and mysqldb?,cursor.execute('USE mydatabase')
remove first word in string `s`,"s.split(' ', 1)[1]"
how to use lxml to find an element by text?,"e = root.xpath('.//a[contains(text(),""TEXT A"")]')"
delete all columns in dataframe `df` that do not hold a non-zero value in its records,"df.loc[:, ((df != 0).any(axis=0))]"
how to remove a column from a structured numpy array *without copying it*?,a[0]
regex for repeating words in a string in python,"re.sub('(?<!\\S)((\\S+)(?:\\s+\\2))(?:\\s+\\2)+(?!\\S)', '\\1', s)"
python list comprehension with multiple 'if's,[i for i in range(100) if i > 10 if i < 50]
writing a log file from python program,logging.debug('next line')
an elegant way to get hashtags out of a string in python?,set([i[1:] for i in line.split() if i.startswith('#')])
how to make matrices in python?,[x[1] for x in L]
getting two strings in variable from url in django,"""""""^/rss/(?P<anynumber>\\d+)/(?P<anystring>.+)/$"""""""
create multiple columns in pandas dataframe from one function,"return pandas.Series({'IV': iv, 'Vega': vega})"
how to get pandas.read_csv() to infer datetime and timedelta types from csv file columns?,"df = pd.read_csv('c:\\temp1.txt', parse_dates=[0], infer_datetime_format=True)"
invoke perl script './uireplace.pl' using perl interpeter '/usr/bin/perl' and send argument `var` to it,"subprocess.call(['/usr/bin/perl', './uireplace.pl', var])"
python getting a list of value from list of dict,[d['value'] for d in l]
how can i split a string into tokens?,"print([i for i in re.split('([\\d.]+|\\W+)', 'x+13.5*10x-4e1') if i])"
fast way to convert strings into lists of ints in a pandas column?,"[3, 2, 1, 0, 3, 2, 3]"
convert a list `l` of ascii values to a string,""""""""""""".join(chr(i) for i in L)"
how to extract the year from a python datetime object?,a = datetime.date.today().year
how to plot two columns of a pandas data frame using points?,"df.plot(x='col_name_1', y='col_name_2', style='o')"
sum of all values in a python dict,sum(d.values())
fastest way to drop duplicated index in a pandas dataframe,df[~df.index.duplicated()]
replacing instances of a character in a string,"line = line.replace(';', ':')"
how to call a system command with specified time limit in python?,self.process.terminate()
python/numpy: how to get 2d array column length?,a.shape[1]
draw lines from x axis to points,plt.show()
format strings and named arguments in python,"""""""{} {}"""""".format(10, 20)"
merge dataframes in pandas using the mean,"pd.concat((df1, df2), axis=1).mean(axis=1)"
set the value of cell `['x']['c']` equal to 10 in dataframe `df`,df['x']['C'] = 10
how to get raw sql from session.add() in sqlalchemy?,"engine = create_engine('postgresql://localhost/dbname', echo=True)"
set color marker styles `--bo` in matplotlib,"plt.plot(list(range(10)), '--bo')"
change string `s` to upper case,s.upper()
clear session key 'mykey',del request.session['mykey']
how to convert 'binary string' to normal string in python3?,"""""""a string"""""".decode('utf-8')"
set max number of threads at runtime on numpy/openblas,"np.dot(x, y)"
how to return all the minimum indices in numpy,numpy.where(x == x.min())
hacking javascript array into json with python,print(json.dumps(result))
convert a list of lists `lol` to a dictionary with key as second value of a list and value as list itself,{x[1]: x for x in lol}
django urlsafe base64 decoding with decryption,base64.urlsafe_b64decode(uenc.encode('ascii'))
numpy: get random set of rows from 2d array,"A[(np.random.randint(A.shape[0], size=2)), :]"
"parse string ""aug 28 1999 12:00am"" into datetime",parser.parse('Aug 28 1999 12:00AM')
split data to 'classes' with pandas or numpy,[x.index.tolist() for x in dfs]
plot logarithmic axes with matplotlib in python,ax.set_yscale('log')
best way to encode tuples with json,"simplejson.dumps(dict([('%d,%d' % k, v) for k, v in list(d.items())]))"
find the sum of subsets of a list in python,"weekly = [sum(visitors[x:x + 7]) for x in range(0, len(daily), 7)]"
parse string `a` to float,float(a)
fastest way to remove all multiple occurrence items from a list?,list_of_tuples = [tuple(k) for k in list_of_lists]
how do i implement a null coalescing operator in sqlalchemy?,session.query(Task).filter(Task.time_spent > timedelta(hours=3)).all()
"manually throw an exception ""i know python!""",raise Exception('I know python!')
how do i transform a multi-level list into a list of strings in python?,"map(''.join, a)"
most efficient way to remove multiple substrings from string?,"re.sub('|'.join(map(re.escape, replace_list)), '', words)"
how to convert xml to objects?,"print(lxml.etree.tostring(order, pretty_print=True))"
sort dictionary `tag_weight` in reverse order by values cast to integers,"sorted(list(tag_weight.items()), key=lambda x: int(x[1]), reverse=True)"
how to convert decimal to binary list in python,[int(x) for x in bin(8)[2:]]
adding url to mysql row in python,"cursor.execute('INSERT INTO index(url) VALUES(%s)', (url,))"
delete the element `c` from list `a`,"if (c in a):
a.remove(c)"
get every thing after last `/`,"url.rsplit('/', 1)"
creating a relative symlink in python without using os.chdir(),"os.symlink('file.ext', '/path/to/some/directory/symlink')"
"pandas: change all the values of a column 'date' into ""int(str(x)[-4:])""",df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
counting the amount of occurences in a list of tuples,"sum(v for k, v in c.items() if v > 1)"
how to compare dates in django,return {'date_now': datetime.datetime.now()}
how to split a string into integers in python?,"a, b = (int(x) for x in s.split())"
check if a global variable `myvar` exists,('myVar' in globals())
python - convert dictionary into list with length based on values,"[1, 1, 1, 10, 10, 5, 5, 5, 5, 5, 5]"
split a list of tuples into sub-lists of the same tuple field,"zip(*[(1, 4), (2, 5), (3, 6)])"
remove parentheses around integers in a string,"re.sub('\\((\\d+)\\)', '\\1', a)"
how to get an isoformat datetime string including the default timezone?,datetime.datetime.now(pytz.timezone('US/Central')).isoformat()
regex to match space and a string until a forward slash,regexp = re.compile('^group/(?P<group>[^/]+)/users/(?P<user>[^/]+)$')
how to convert a tuple to a string in python?,[item[0] for item in queryresult]
reading a csv file into pandas dataframe with invalid characters (accents),sys.setdefaultencoding('utf8')
"difference between using commas, concatenation, and string formatters in python","print('I am printing {0} and {y}'.format(x, y=y))"