text
stringlengths
4
1.08k
how to keep a list of lists sorted as it is created,dataList.sort(key=lambda x: x[1])
check if dictionary `l[0].f.items()` is in dictionary `a3.f.items()`,set(L[0].f.items()).issubset(set(a3.f.items()))
remove strings containing only white spaces from list,[name for name in starring if name.strip()]
replace each value in column 'prod_type' of dataframe `df` with string 'responsive',df['prod_type'] = 'responsive'
"need to add space between subplots for x axis label, maybe remove labelling of axis notches",ax1.set_xticklabels([])
pandas: create another column while splitting each row from the first column,"df['B'] = df['A'].apply(lambda x: '#' + x.replace(' ', ''))"
create a dictionary `d` from list `iterable`,"d = {key: value for (key, value) in iterable}"
how can i create a set of sets in python?,"t = [[], [1, 2], [5], [1, 2, 5], [1, 2, 3, 4], [1, 2, 3, 6]]"
get current cpu and ram usage,"psutil.cpu_percent()
psutil.virtual_memory()"
scrapy:how to print request referrer,"response.request.headers.get('Referer', None)"
pandas: how to run a pivot with a multi-index?,"df.pivot_table(values='value', index=['year', 'month'], columns='item')"
regex matching between two strings?,"m = re.findall('<!--(.*?)-->', string, re.DOTALL)"
python: built-in keyboard signal/interrupts,sys.exit()
passing table name as a parameter in psycopg2,"cursor.execute('SELECT * FROM %(table)s', {'table': AsIs('my_awesome_table')})"
how can i convert the time in a datetime string from 24:00 to 00:00 in python?,"print(date.strftime('%a, %d %b %Y %H:%M:%S'))"
how to filter a dictionary in python?,"dict((k, 'updated') for k, v in d.items() if v != 'None')"
pandas (python): how to add column to dataframe for index?,df = df.reset_index()
sorting list of nested dictionaries in python,"yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)"
python - how to cut a string in python?,"""""""foobar""""""[:4]"
flipping the boolean values in a list python,"[False, False, True]"
pandas merge - how to avoid duplicating columns,cols_to_use = df2.columns.difference(df.columns)
is there any lib for python that will get me the synonyms of a word?,"['great', 'satisfying', 'exceptional', 'positive', 'acceptable']"
sorting a list of tuples by the addition of second and third element of the tuple,"sorted(lst, key=lambda x: (sum(x[1:]), x[0]))"
python: creating a 2d histogram from a numpy matrix,"plt.imshow(Z, interpolation='none')"
how to load a c# dll in python?,clr.AddReference('MyDll')
get the value of attribute 'property' of object `a` with default value 'default value',"getattr(a, 'property', 'default value')"
python regular expression with codons,"re.findall('TAA(?:[ATGC]{3})+?TAA', seq)"
how to set sys.stdout encoding in python 3?,sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())
how to retrieve facebook friend's information with python-social-auth and django,"SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'user_friends', 'friends_location']"
how to specify where a tkinter window opens?,root.mainloop()
django 1.4 - bulk_create with a list,"list = ['abc', 'def', 'ghi']"
is there a simple way to change a column of yes/no to 1/0 in a pandas dataframe?,"pd.Series(np.searchsorted(['no', 'yes'], sample.housing.values), sample.index)"
subtracting the mean of each row in numpy with broadcasting,"Y = X - X.mean(axis=1).reshape(-1, 1)"
is it possible to print a string at a certain screen position inside idle?,sys.stdout.flush()
how to write a cell with multiple columns in xlwt?,"sheet.write(1, 0, 1)"
display current time in readable format,"time.strftime('%l:%M%p %z on %b %d, %Y')"
removing white space from txt with python,"re.sub('\\s{2,}', '|', line.strip())"
how to plot events on time on using matplotlib,plt.show()
"can you create a python list from a string, while keeping characters in specific keywords together?","re.findall('car|rat|[a-z]', s)"
efficient way to convert a list to dictionary,dict(x.split(':') for x in lis)
convert a list of booleans to string,"print(''.join(chr(ord('A') + i) if b else ' ' for i, b in enumerate(bools)))"
any functional programming method of traversing a nested dictionary?,"from functools import reduce
reduce(dict.__getitem__, l, d)"
matplotlib: how to prevent x-axis labels from overlapping each other,plt.show()
get subdomain from url using python,subdomain = url.hostname.split('.')[0]
lxml removes spaces and line breaks in <head>,"print(etree.tostring(e, pretty_print=True))"
tkinter: wait for item in queue,time.sleep(1)
set font size of axis legend of plot `plt` to 'xx-small',"plt.setp(legend.get_title(), fontsize='xx-small')"
sort numpy matrix row values in ascending order,"arr[arr[:, (2)].argsort()]"
how do i model a many-to-many relationship over 3 tables in sqlalchemy (orm)?,session.query(Shots).filter_by(event_id=event_id)
trying to find majority element in a list,"find_majority([1, 2, 3, 4, 3, 3, 2, 4, 5, 6, 1, 2, 3, 4, 5, 1, 2, 3, 4, 6, 5])"
how to loop backwards in python?,"[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]"
add value to each element in array python,"[(a + i.reshape(2, 2)) for i in np.identity(4)]"
replace values of dataframe `df` with true if numeric,"df.applymap(lambda x: isinstance(x, (int, float)))"
"set an array of unicode characters `[u'\xe9', u'\xe3', u'\xe2']` as labels in matplotlib `ax`","ax.set_yticklabels(['\xe9', '\xe3', '\xe2'])"
is there a way to remove duplicate and continuous words/phrases in a string?,"re.sub('\\b(.+)\\s+\\1\\b', '\\1', s)"
else if in list comprehension in python3,"['A', 'b', 'C', 'D', 'E', 'F']"
using python string formatting in a django template,{{(variable | stringformat): '.3f'}}
"how to remove hashtag, @user, link of a tweet using regular expression","result = re.sub('(?:@\\S*|#\\S*|http(?=.*://)\\S*)', '', subject)"
can i read and write file in one line with python?,"f.write(open('xxx.mp4', 'rb').read())"
getting an element from tuple of tuples in python,[x[1] for x in COUNTRIES if x[0] == 'AS'][0]
summing rows from a multiindex pandas df based on index label,print(df.head())
pandas - resampling datetime index and extending to end of the month,df.resample('M').ffill().resample('H').ffill().tail()
mathematical equation manipulation in python,sympy.sstr(_)
how to test if one string is a subsequence of another?,"assert not is_subseq('ca', 'abc')"
testing whether a numpy array contains a given row,"equal([1, 2], a).all(axis=1).any()"
finding the most popular words in a list,"[('all', 3), ('yeah', 2), ('bye', 1), ('awesome', 1)]"
convert the elements of list `l` from hex byte strings to hex integers,"[int(x, 16) for x in L]"
transpose/rotate a block of a matrix in python,"block3[:] = np.rot90(block3.copy(), -1)"
creating a list of dictionaries in python,"[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]"
convert column of date objects in pandas dataframe to strings,df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y')
converting file from .txt to .csv doesn't write last column of data,writer.writerows(row.strip().split() for row in infile if row.strip())
how can i change password for domain user(windows active directory) using python?,"host = 'LDAP://10.172.0.79/dc=directory,dc=example,dc=com'"
changing the text on a label,self.labelText = 'change the value'
"how to bind multiple widgets with one ""bind"" in tkinter?",root.mainloop()
what is the easiest way to convert list with str into list with int?,new = [int(i) for i in old]
how do i display add model in tabular format in the django admin?,"{'fields': (('first_name', 'last_name'), 'address', 'city', 'state')}"
importing from a relative path in python,"sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))"
combine two columns `foo` and `bar` in a pandas data frame,"pandas.concat([df['foo'].dropna(), df['bar'].dropna()]).reindex_like(df)"
how can i get a list of all classes within current module in python?,current_module = sys.modules[__name__]
get a string after a specific substring,"print(my_string.split('world', 1)[1])"
conditional removing of duplicates pandas python,"df.drop_duplicates(['Col1', 'Col2'])"
how do i modify the width of a textctrl in wxpython?,"wx.TextCtrl(self, -1, size=(300, -1))"
"how to use regular expression to separate numbers and characters in strings like ""30m1000n20m""","re.findall('(([0-9]+)([A-Z]))', '20M10000N80M')"
getting the output of a python subprocess,out = p.communicate()
how to get output of exe in python script?,"output = subprocess.Popen(['mycmd', 'myarg'], stdout=PIPE).communicate()[0]"
add legends to linecollection plot,plt.show()
how to add multiple values to a dictionary key in python?,"a['abc'] = [1, 2, 'bob']"
"get value of environment variable ""home""",os.environ['HOME']
how to sort python list of strings of numbers,"a = sorted(a, key=lambda x: float(x))"
match start and end of file in python with regex,"print(re.findall('^.*\\.$\\Z', data, re.MULTILINE))"
how to get request object in django unit testing?,"self.assertEqual(response.status_code, 200)"
reverse y-axis in pyplot,plt.gca().invert_yaxis()
is there a way to refer to the entire matched expression in re.sub without the use of a group?,"print(re.sub('[_%^$]', '\\\\\\g<0>', line))"
check if a python list item contains a string inside another string,[x for x in lst if 'abc' in x]
how do i add accents to a letter?,'fue' + '\u0301'
how to choose value from an option list using pyqt4.qtwebkit,"option.setAttribute('selected', 'true')"
python - find index postion in list based of partial string,"indices = [i for i, s in enumerate(mylist) if 'aa' in s]"
how to delete a character from a string using python?,s = s[:pos] + s[pos + 1:]