text
stringlengths
4
1.08k
Merging items in a list - Python,"from functools import reduce
reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5])"
Count the number of Occurrence of Values based on another column,df.Country.value_counts().reset_index(name='Sum of Accidents')
Python Regex - Remove special characters but preserve apostraphes,"re.sub(""[^\\w' ]"", '', ""doesn't this mean it -technically- works?"")"
How can I handle an alert with GhostDriver via Python?,driver.execute_script('window.confirm = function(){return true;}')
Divide the values of two dictionaries in python,{k: (d2[k] / d1[k]) for k in list(d1.keys()) & d2}
Replacing the empty strings in a string,"string2.replace('', string1)[len(string1):-len(string1)]"
How do I use extended characters in Python's curses library?,window.addstr('\xcf\x80')
"in Python, how to convert list of float numbers to string with certain format?",str_list = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in lst]
Sort numpy matrix row values in ascending order,"numpy.sort(arr, axis=0)"
Comparing two .txt files using difflib in Python,"difflib.SequenceMatcher(None, file1.read(), file2.read())"
Convert tab-delimited txt file into a csv file using Python,"open('demo.txt', 'rb').read()"
pandas: how do I select first row in each GROUP BY group?,"df.sort('A', inplace=True)"
matplotlib colorbar formatting,cb.ax.yaxis.set_major_formatter(plt.FuncFormatter(myfmt))
Adding a y-axis label to secondary y-axis in matplotlib,plt.show()
How do I transform a multi-level list into a list of strings in Python?,"list(map(''.join, a))"
How to set same color for markers and lines in a matplotlib plot loop?,plt.savefig('test.png')
Select rows from a DataFrame based on values in a column in pandas,print(df.loc[df['A'] == 'foo'])
How to make curvilinear plots in matplotlib,plt.axis('off')
Pandas DataFrame Add column to index without resetting,"df.set_index(['d'], append=True)"
send xml file to http using python,print(response.read())
How to plot events on time on using matplotlib,plt.show()
Named tuples in a list,a = [mynamedtuple(*el) for el in a]
Unable to click the checkbox via Selenium in Python,element.click()
Accessing dictionary by key in Django template,{{json.key1}}
Why Pandas Transform fails if you only have a single column,df.groupby('a').transform('count')
Inheritance of attributes in python using _init_,"super(Teenager, self).__init__(name, phone)"
Percentage match in pandas Dataframe,(trace_df['ratio'] > 0).mean()
How to get a list of all integer points in an n-dimensional cube using python?,"list(itertools.product(list(range(-x, y)), repeat=dim))"
Append tuples to a tuples,"(1, 2), (3, 4), (5, 6), (8, 9), (0, 0)"
Python . How to get rid of '\r' in string?,line.strip()
Shortest way to convert these bytes to int in python?,"struct.unpack('>q', s)[0]"
convert a string of bytes into an int (python),"struct.unpack('<L', 'y\xcc\xa6\xbb')[0]"
How do I properly use connection pools in redis?,redis_conn = redis.Redis(connection_pool=redis_pool)
How to write unittest for variable assignment in python?,do_something()
How to sort python list of strings of numbers,"a = sorted(a, key=lambda x: float(x))"
How to convert list of numpy arrays into single numpy array?,"numpy.concatenate(LIST, axis=0)"
Running Python code contained in a string,"eval(""print('Hello')"")"
Python: How to check a string for substrings from a list?,any(substring in string for substring in substring_list)
Unescaping escaped characters in a string using Python 3.2,s.encode('utf8')
Getting the indices of several elements in a NumPy array at once,"np.in1d(b, a).nonzero()[0]"
How to calculate cointegrations of two lists?,"b = [5.23, 6.1, 8.3, 4.98]"
how to sort lists within list in user defined order?,"[['*', '+', '-'], ['*', '*', '-'], ['/', '+', '-']]"
How to round each item in a list of floats to 2 decmial places,"['0.30', '0.50', '0.20']"
pandas dataframe groupby and get nth row,df.groupby('ID').apply(lambda t: t.iloc[1])
How do I compile a Visual Studio project from the command-line?,os.system('msbuild project.sln /p:Configuration=Debug')
Counting array elements in Python,len(myArray)
Python creating a smaller sub-array from a larger 2D NumPy array?,"data[:, ([1, 2, 4, 5, 7, 8])]"
Sorting a defaultdict by value in python,"sorted(iter(cityPopulation.items()), key=lambda k_v: k_v[1][2], reverse=True)"
How do I integrate Ajax with Django applications?,"return render_to_response('index.html', {'variable': 'world'})"
How do I merge a 2D array in Python into one string with List Comprehension?,[item for innerlist in outerlist for item in innerlist]
How to use Beautiful Soup to find a tag with changing id?,soup.findAll(id=re.compile('para$'))
rename index of a pandas dataframe,df.ix['c']
pandas dataframe create new columns and fill with calculated values from same df,df['A_perc'] = df['A'] / df['sum']
how to annotate heatmap with text in matplotlib?,plt.show()
Efficient Python array with 100 million zeros?,a[i] += 1
How can I exit Fullscreen mode in Pygame?,"pygame.display.set_mode(size, FULLSCREEN)"
Most efficient way to split strings in Python,"['Item 1 ', ' Item 2 ', ' Item 3 ', ' Item 4 ', ' Item 5']"
Faster way to rank rows in subgroups in pandas dataframe,df.groupby('group')['value'].rank(ascending=False)
Regex to match space and a string until a forward slash,regexp = re.compile('^group/(?P<group>[^/]+)/users$')
Regex to match space and a string until a forward slash,regexp = re.compile('^group/(?P<group>[^/]+)/users/(?P<user>[^/]+)$')
How to remove empty string in a list?,cleaned = [x for x in your_list if x]
"Using matplotlib, how can I print something ""actual size""?","fig.savefig('ten_x_seven_cm.png', dpi=128)"
How to group similar items in a list?,"[list(g) for _, g in itertools.groupby(test, lambda x: x.split('_')[0])]"
How to do a less than or equal to filter in Django queryset?,User.objects.filter(userprofile__level__gte=0)
How to convert list of intable strings to int,list_of_lists = [[try_int(x) for x in lst] for lst in list_of_lists]
How to share the global app object in flask?,app = Flask(__name__)
python import a module from a directory(package) one level up,sys.path.append('../..')
Rotate axis text in python matplotlib,"ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)"
Finding tuple in the list of tuples (sorting by multiple keys),"sorted(t, key=lambda i: (i[1], -i[2]))"
Is there a generator version of `string.split()` in Python?,"list(split_iter(""A programmer's RegEx test.""))"
How do you debug url routing in Flask?,app.run(debug=True)
Capture stdout from a script in Python,sys.stdout.write('foobar')
How can I get the color of the last figure in matplotlib?,"ebar = plt.errorbar(x, y, yerr=err, ecolor='y')"
Django App Engine: AttributeError: 'AnonymousUser' object has no attribute 'backend',"django.contrib.auth.authenticate(username=username, password=password)"
Creating a simple XML file using python,tree.write('filename.xml')
Rotating a two-dimensional array in Python,"[[1, 2, 3], [4, 5, 6], [7, 8, 9]]"
Django logging to console,logger = logging.getLogger(__name__)
How to make a 3D scatter plot in Python?,pyplot.show()
2D array of objects in Python,nodes = [[Node() for j in range(cols)] for i in range(rows)]
Capturing group with findall?,"re.findall('abc(de)fg(123)', 'abcdefg123 and again abcdefg123')"
Python - How to cut a string in Python?,s = 'http://www.domain.com/?s=some&two=20'
how to call python function from NodeJS,sys.stdout.flush()
How to overplot a line on a scatter plot in python?,plt.show()
Point and figure chart with matplotlib,plt.show()
How to set number of ticks in plt.colorbar?,plt.show()
Removing character in list of strings,"print([s.replace('8', '') for s in lst])"
Create a list of integers with duplicate values in Python,"print([u for v in [[i, i] for i in range(5)] for u in v])"
Convert datetime object to a String of date only in Python,dt.strftime('%m/%d/%Y')
How to get output from subprocess.Popen(),sys.stdout.flush()
Transform comma separated string into a list but ignore comma in quotes,"['1', '', '2', '3,4']"
Merge sorted lists in python,"sorted(itertools.chain(args), cmp)"
Remove or adapt border of frame of legend using matplotlib,plt.legend(frameon=False)
How to crop an image in OpenCV using Python,cv2.waitKey(0)
Python: Assign each element of a List to a separate Variable,"a, b, c = [1, 2, 3]"
Multiple 'in' operators in Python?,"all(word in d for word in ['somekey', 'someotherkey', 'somekeyggg'])"
"from list of integers, get number closest to a given value","min(myList, key=lambda x: abs(x - myNumber))"
Python regex split a string by one of two delimiters,"sep = re.compile('[\\s,]+')"
How can a pandas merge preserve order?,"x.reset_index().merge(y, how='left', on='state', sort=False).sort('index')"
Index of element in Numpy array,"i, j = np.where(a == value)"