text
stringlengths
4
1.08k
embed bash in python,"os.system(""bash -c 'echo $0'"")"
"convert hex string ""a"" to integer","int('a', 16)"
applying regex to a pandas dataframe,df['Season'].str.split('-').str[0].astype(int)
python: find the sum of all the multiples of 3 or 5 below 1000,"sum(set(list(range(0, 1000, 3)) + list(range(0, 1000, 5))))"
removing duplicates in each row of a numpy array,numpy.array([v for v in vals if len(set(v)) == len(v)])
matplotlib scatter plot colour as function of third variable,plt.show()
string formatting options: pros and cons,'This is a string: %s' % 'abc'
python logging across multiple modules,logging.info('Doing something')
how to use flask-security register view?,app.config['SECURITY_REGISTER_URL'] = '/create_account'
parse fb graph api date string into python datetime,"time.strptime('2011-03-06T03:36:45+0000', '%Y-%m-%dT%H:%M:%S+0000')"
how to generate a continuous string?,"map(''.join, itertools.product(string.ascii_lowercase, repeat=3))"
delete all elements from a list `x` if a function `fn` taking value as parameter returns `0`,[x for x in lst if fn(x) != 0]
python pickle/unpickle a list to/from a file,"pickle.load(open('afile', 'rb'))"
how to find the index of a value in 2d array in python?,zip(*np.where(a == 1))
how can i determine the byte length of a utf-8 encoded string in python?,len(s.encode('utf-8'))
insert item into case-insensitive sorted list in python,"['aa', 'bb', 'CC', 'Dd', 'ee']"
converting perl regular expressions to python regular expressions,re.compile('Author\\(s\\) :((.+\\n)+)')
how can i use python finding particular json value by key?,"['cccc', 'aaa', 'ss']"
python thinks a 3000-line text file is one line long?,"open('textbase.txt', 'Ur')"
how to convert a list by mapping an element into multiple elements in python?,"print(list(chain.from_iterable((x, x + 1) for x in l)))"
convert a string of numbers 'example_string' separated by comma into a list of numbers,"[int(s) for s in example_string.split(',')]"
how to update a plot with python and matplotlib,mpl.use('WXAgg')
filtering all rows with nat in a column in dataframe python,"df.drop(['TMP'], axis=1, inplace=True)"
python string slice indices - slice to end of string,word[1:]
pythonic way to import data from multiple files into an array,all_data.append(data)
set colorbar range from `0` to `15` for pyplot object `quadmesh` in matplotlib,"quadmesh.set_clim(vmin=0, vmax=15)"
combine date column and time column into datetime column,"df.apply(lambda x: combine(x['MEETING DATE'], x['MEETING TIME']), axis=1)"
how to remove tags from a string in python using regular expressions? (not in html),"re.sub('<[^>]*>', '', mystring)"
adding custom django model validation,"super(BaseModel, self).save(*args, **kwargs)"
is there a way to make multiple horizontal boxplots in matplotlib?,"plt.subplot('{0}{1}{2}'.format(1, totfigs, i + 1))"
append several variables to a list in python,"vol.extend((volumeA, volumeB, volumeC))"
check if a key exists in a python list,"test(['important', 'comment'])"
how to create a density plot in matplotlib?,plt.show()
replacing particular elements in a list,mylist = [('XXX' if v == 'abc' else v) for v in mylist]
pythonic way to populate numpy array,"X = numpy.loadtxt('somefile.csv', delimiter=',')"
how can you group a very specfic pattern with regex?,rgx = re.compile('(?<!\\+)[a-zA-Z]|[a-zA-Z](?!\\+)')
"for each row, what is the fastest way to find the column holding nth element that is not nan?",(df.notnull().cumsum(axis=1) == 4).idxmax(axis=1)
using scss with flask,app.run(debug=True)
getting the average of a certain hour on weekdays over several years in a pandas dataframe,"df1.groupby([df1.index.year, df1.index.hour]).mean()"
how to extract data from json object in python?,"json.loads('{""foo"": 42, ""bar"": ""baz""}')['bar']"
find the nth occurrence of substring in a string,"find_nth('foofoofoofoo', 'foofoo', 2)"
scatter and hist in one subplot in python,plt.show()
how do you filter pandas dataframes by multiple columns,"df = df[df[['col_1', 'col_2']].apply(lambda x: f(*x), axis=1)]"
numpy: replace every value in the array with the mean of its adjacent elements,"A = np.random.randn(1000, 1000)"
how to initialise a 2d array in python?,"[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]"
how to get every element in a list of list of lists?,"['QS', '5H', 'AS', '2H', '8H', '7C', '9H', '5C', 'JH', '7D']"
color range python,"print((i, [round(255 * x) for x in rgb]))"
get load at a moment in time or getloadavg() for a smaller time period in python in linux (centos),print(int(open('/proc/loadavg').next().split()[3].split('/')[0]))
python + pymongo: how to insert a new field on an existing document in mongo from a for loop,"db.Doc.update({'_id': b['_id']}, {'$set': {'geolocCountry': myGeolocCountry}})"
how to center a window on the screen in tkinter?,root.title('Not centered')
remove all words which contains number from a string `words` using regex,"re.sub('\\w*\\d\\w*', '', words).strip()"
python - read text file with weird utf-16 format,"file = io.open('data.txt', 'r', encoding='utf-16-le')"
two different color colormaps in the same imshow matplotlib,plt.show()
python max length of j-th item across sublists of a list,"[max(len(a), len(b)) for a, b in zip(*x)]"
how do i do a get_or_create in pymongo (python mongodb)?,"db.test.update({'x': '42'}, {'$set': {'a': '21'}}, True)"
check if a numpy array `a1` contains any element of another array `a2`,"np.any(np.in1d(a1, a2))"
how do you serialize a model instance in django?,"serialized_obj = serializers.serialize('json', [obj])"
encode string `data` as `hex`,data.encode('hex')
"how to use regular expression to separate numbers and characters in strings like ""30m1000n20m""","re.findall('([0-9]+|[A-Z])', '20M10000N80M')"
python: write a list of tuples to a file,fp.write('\n'.join('%s %s' % x for x in mylist))
"getting x,y from a scatter plot with multiple datasets?",plt.show()
is there a way to instantiate a class without calling __init__?,"a.__init__(*args, **kwargs)"
python plot: how to remove grid lines not within the circle?,plt.show()
limit the number of sentences in a string,"re.match('(.*?[.?!](?:\\s+.*?[.?!]){0,1})', phrase).group(1)"
sum each value in a list of tuples,"map(sum, zip(*l))"
reading integers from binary file in python,"print(struct.unpack('i', fin.read(4)))"
"in python, how can i turn this format into a unix timestamp?","time.strptime('Mon Jul 09 09:20:28 +0000 2012', '%a %b %d %H:%M:%S +0000 %Y')"
"python, subprocess: reading output from subprocess",sys.stdout.flush()
how to dynamically change base class of instances at runtime?,"setattr(Person, '__mro__', (Person, Friendly, object))"
sum numbers in a list 'your_list',sum(your_list)
how to delete rows from a pandas dataframe based on a conditional expression,df[df['column name'].map(len) < 2]
how can i create a list from two dictionaries?,"fu_list = [(k, fus_d.get(k), fus_s.get(k)) for k in fus_d.keys() | fus_s]"
is there a more pythonic way to build this dictionary?,{v: (v ** 2) for v in l}
using django view variables inside templates,"return render_to_response('your_template.html', {'h': h})"
how to group by date range,"df.groupby(['employer_key', 'account_id'])['login_date']"
efficient way to convert a list to dictionary,{x.split(':')[0]: x.split(':')[1] for x in a}
django-userena: adding extra non-null fields to a user's profile,"start_year = models.IntegerField(max_length=4, blank=False, null=True)"
sorting list of list in python,"sorted((sorted(item) for item in data), key=lambda x: (len(x), x))"
remove frame of legend in plot `plt`,plt.legend(frameon=False)
create a dictionary `d` from list `iterable`,"d = dict(((key, value) for (key, value) in iterable))"
create list `levels` containing 3 empty dictionaries,"levels = [{}, {}, {}]"
count the frequency of a recurring list -- inside a list of lists,"Counter(map(tuple, list1))"
how to use python_dateutil 1.5 'parse' function to work with unicode?,"['8th', 'of', '\u0418\u044e\u043d\u044c']"
how to write a confusion matrix in python?,"array([[3, 0, 0], [0, 1, 2], [2, 1, 3]])"
find the minimum value in a numpy array `arr` excluding 0,arr[arr != 0].min()
creating 2d dictionary in python,d['set1']['name']
split string 'abcdefg' into a list of characters,"re.findall('\\w', 'abcdefg')"
create a list of sets of atoms,"[('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]"
convert hex '\xff' to integer,ord('\xff')
manipulating binary data in python,print(data.encode('hex'))
setting different bar color in matplotlib python,plt.show()
python lambda function,"f = lambda x, y: x + y"
"python-requests, extract url parameters from a string","requests.get(url, params=query)"
python json encoding,"json.dumps({'apple': 'cat', 'banana': 'dog', 'pear': 'fish'})"
"get index of character 'b' in list '['a', 'b']'","['a', 'b'].index('b')"
python: convert string to byte array,[elem.encode('hex') for elem in str]
find xml element based on its attribute and change its value,"elem.find('.//number[@topic=""sys/phoneNumber/1""]')"
map two lists `keys` and `values` into a dictionary,"dict((k, v) for k, v in zip(keys, values))"
how to convert a list of multiple integers into a single integer?,"sum(d * 10 ** i for i, d in enumerate(x[::-1]))"
avoid rounding in new python string formatting,"""""""{:02}:{:02}:{:02}"""""".format(int(0.0), int(0.9), int(67.5))"