text
stringlengths
4
1.08k
Pandas DataFrame Groupby two columns and get counts,"df.groupby(['col5', 'col2']).size().groupby(level=1).max()"
How would I check a string for a certain letter in Python?,"'x' in ['x', 'd', 'a', 's', 'd', 's']"
Delete a dictionary item if the key exists,"mydict.pop('key', None)"
Delete a dictionary item if the key exists,del mydict[key]
Delete a dictionary item if the key exists,del mydict[key]
Multiple positional arguments with Python and argparse,"parser.add_argument('input', nargs='+')"
How to avoid line color repetition in matplotlib.pyplot?,"pyplot.plot(x, y, color='#112233')"
Strip HTML from strings in Python,"re.sub('<[^<]+?>', '', text)"
Align numpy array according to another array,"a[np.in1d(a, b)]"
how to split a string on the first instance of delimiter in python,"""""""jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,"""""".split('=', 1)"
Control a print format when printing a list in Python,"print('[%s]' % ', '.join('%.3f' % val for val in list))"
Control a print format when printing a list in Python,"print('[' + ', '.join('%5.3f' % v for v in l) + ']')"
Control a print format when printing a list in Python,print([('%5.3f' % val) for val in l])
How to move to one folder back in python,os.chdir('..')
Convert Unicode to UTF-8 Python,print(text.encode('windows-1252'))
How can I convert a binary to a float number,"struct.unpack('d', struct.pack('Q', int(s2, 0)))[0]"
How can I convert a binary to a float number,"float(int('-0b1110', 0))"
How can I convert a binary to a float number,"struct.unpack('d', b8)[0]"
Plotting categorical data with pandas and matplotlib,df.colour.value_counts().plot(kind='bar')
Plotting categorical data with pandas and matplotlib,df.groupby('colour').size().plot(kind='bar')
Read lines containing integers from a file in Python?,line.strip().split(' ')
Pandas how to apply multiple functions to dataframe,"df.groupby(lambda idx: 0).agg(['mean', 'std'])"
sorting dictionary by numeric value,"sorted(list(tag_weight.items()), key=lambda x: int(x[1]), reverse=True)"
How do I find the largest integer less than x?,int(math.ceil(x)) - 1
check if the string is empty,"if (not myString):
pass"
Most elegant way to check if the string is empty,"if (not some_string):
pass"
Most elegant way to check if the string is empty,"if (not my_string):
pass"
check if the string is empty,"if some_string:
pass"
iterate over a dictionary in sorted order,it = iter(sorted(d.items()))
iterate over a dictionary in sorted order,"for (key, value) in sorted(d.items()):
pass"
iterate over a dictionary in sorted order,return sorted(dict.items())
iterate over a dictionary in sorted order,return iter(sorted(dict.items()))
iterate over a dictionary in sorted order,"for (k, v) in sorted(foo.items()):
pass"
iterate over a dictionary in sorted order,"for k in sorted(foo.keys()):
pass"
finding the last occurrence of an item in a list python,last = len(s) - s[::-1].index(x) - 1
convert list to string,str1 = ''.join(list1)
convert list to string,' '.join((str(x) for x in L))
convert list to string,str1 = ''.join((str(e) for e in list1))
convert list to string,"makeitastring = ''.join(map(str, L))"
remove None value from a list without removing the 0 value,[x for x in L if x is not None]
How do I select a random element from an array in Python?,"random.choice([1, 2, 3])"
Creating a 2d matrix in python,x = [[None for _ in range(5)] for _ in range(6)]
Numpy: Get random set of rows from 2D array,"A[(np.random.choice(A.shape[0], 2, replace=False)), :]"
Numpy: Get random set of rows from 2D array,"A[(np.random.randint(A.shape[0], size=2)), :]"
Combining rows in pandas,df.groupby(df.index).sum()
Parsing XML with namespace in Python via 'ElementTree',root.findall('{http://www.w3.org/2002/07/owl#}Class')
"How do I generate a random string (of length X, a-z only) in Python?",""""""""""""".join(random.choice(string.lowercase) for x in range(X))"
Python cant find module in the same folder,sys.path.append('/path/to/2014_07_13_test')
round number to nearest integer,int(round(x))
round number to nearest integer,h = int(round(h))
round number to nearest integer,"round(32.268907563, 3)"
round number to nearest integer,"round(value, significantDigit)"
round number to nearest integer,"round(1.0005, 3)"
round number to nearest integer,"round(2.0005, 3)"
round number to nearest integer,"round(3.0005, 3)"
round number to nearest integer,"round(4.0005, 3)"
round number to nearest integer,"round(8.005, 2)"
round number to nearest integer,"round(7.005, 2)"
round number to nearest integer,"round(6.005, 2)"
round number to nearest integer,"round(1.005, 2)"
Pandas - FillNa with another column,df['Cat1'].fillna(df['Cat2'])
Python: Logging TypeError: not all arguments converted during string formatting,"logging.info('date=%s', date)"
Python: Logging TypeError: not all arguments converted during string formatting,logging.info('date={}'.format(date))
"In dictionary, converting the value from string to integer","{k: int(v) for k, v in d.items()}"
How can I add the corresponding elements of several lists of numbers?,"map(sum, zip(*lists))"
Python: How to convert a string containing hex bytes to a hex string,s.decode('hex')
Python: How to convert a string containing hex bytes to a hex string,binascii.a2b_hex(s)
MITM proxy over SSL hangs on wrap_socket with client,connection.send('HTTP/1.0 200 established\r\n\r\n')
MITM proxy over SSL hangs on wrap_socket with client,connection.send('HTTP/1.0 200 OK\r\n\r\n')
Set value for particular cell in pandas DataFrame,df['x']['C'] = 10
Norm along row in pandas,np.sqrt(np.square(df).sum(axis=1))
How do I remove identical items from a list and sort it in Python?,sorted(set(my_list))
Python Finding Index of Maximum in List,"max(enumerate(a), key=lambda x: x[1])[0]"
Python Accessing Values in A List of Dictionaries,[d['Name'] for d in thisismylist]
Python Accessing Values in A List of Dictionaries,"[(d['Name'], d['Age']) for d in thisismylist]"
How to grab one random item from a database in Django/postgreSQL?,model.objects.all().order_by('?')[0]
"Run a python script from another python script, passing in args",os.system('script2.py 1')
Python Regex for hyphenated words,"re.findall('\\w+(?:-\\w+)+', text)"
Create variable key/value pairs with argparse (python),"parser.add_argument('--conf', nargs=2, action='append')"
"How do you pick ""x"" number of unique numbers from a list in Python?","random.sample(list(range(1, 16)), 3)"
Sort a list of strings based on regular expression match or something similar,"strings.sort(key=lambda str: re.sub('.*%(.).*', '\\1', str))"
Sort a list of strings based on regular expression match or something similar,"strings.sort(key=lambda str: re.sub('.*%', '', str))"
Appending to 2D lists in Python,listy = [[] for i in range(3)]
Sort NumPy float array column by column,"A = np.array(sorted(A, key=tuple))"
Python list comprehension for loops,[(x + y) for x in '12345' for y in 'ab']
Trimming a string,' Hello '.strip()
Trimming a string,myString.strip()
Trimming a string,' Hello '.strip()
Trimming a string,' Hello'.strip()
Trimming a string,'Bob has a cat'.strip()
Trimming a string,' Hello '.strip()
Trimming a string,str.strip()
Trimming a string,myString.strip('\n')