text
stringlengths
4
1.08k
how to combine two data frames in python pandas,"df_row_merged = pd.concat([df_a, df_b], ignore_index=True)"
Pipe output from shell command to a python script,print(sys.stdin.read())
How to resolve DNS in Python?,"exec(compile(open('C:\\python\\main_menu.py').read(), 'C:\\python\\main_menu.py', 'exec'))"
Parallel running of several jobs in a python script,p.wait()
Reading formatted text using python,g.write('# comment\n')
Creating link to an url of Flask app in jinja2 template,"{{url_for('static', filename='[filenameofstaticfile]')}}"
How to write a cell with multiple columns in xlwt?,"sheet.write(1, 0, 1)"
How can I strip the file extension from a list full of filenames?,lst = [os.path.splitext(x)[0] for x in accounts]
Python - How can I pad a string with spaces from the right and left?,"""""""{:*^30}"""""".format('centered')"
Streaming data with Python and Flask,"app.run(host='localhost', port=23423)"
Reading and running a mathematical expression in Python,"eval(""__import__('sys').exit(1)"")"
Reading and running a mathematical expression in Python,eval('1 + 1')
How to pass arguments as tuple to odeint?,"odeint(func, y0, t, a, b, c)"
Numpy: get 1D array as 2D array without reshape,"np.hstack([np.atleast_2d([1, 2, 3, 4, 5]).T, np.atleast_2d([1, 2, 3, 4, 5]).T])"
numpy: efficiently add rows of a matrix,"np.dot(I, np.ones((7,), int))"
Using BeautifulSoup to search html for string,soup.body.findAll(text=re.compile('^Python$'))
Replace keys in a dictionary,"{' '.join([keys[char] for char in k]): v for k, v in list(event_types.items())}"
Distributed programming in Python,"print(p.map_async(f, [1, 2, 3]))"
Python lambda with if but without else,lambda x: x if x < 3 else None
Matplotlib 3D Scatter Plot with Colorbar,fig.colorbar(p)
Import file from parent directory?,sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
pandas dataframe with 2-rows header and export to csv,"df.to_csv(f, index=False, header=False)"
Reversing lists of numbers in python,bids.append(int(bid))
How do you get the text from an HTML 'datacell' using BeautifulSoup,headerRows[0][10].findNext('b').string
How to close urllib2 connection?,connection.close()
Delete Duplicate Rows in Django DB,Some_Model.objects.filter(id__in=ids_list).delete()
Apply vs transform on a group object,df.groupby('A')['C'].transform(zscore)
How do I detect if Python is running as a 64-bit application?,platform.architecture()
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'))"
matplotlib colorbar for scatter,plt.show()
How to embed python tkinter window into a browser?,matplotlib.use('module://mplh5canvas.backend_h5canvas')
Splitting a nested list into two lists,"my_list2, my_list1 = map(list, zip(*my_list))"
Count lower case characters in a string,return sum(1 for c in string if c.islower())
Matplotlib imshow/matshow display values on plot,plt.show()
duplicate each member in a list - python,[a[i // 2] for i in range(len(a) * 2)]
"How do I get the ""visible"" length of a combining Unicode string in Python?",wcswidth('\xe1\x84\x80\xe1\x85\xa1\xe1\x86\xa8')
Python Requests encoding POST data,urllib.parse.unquote_plus('Andr%C3%A9+T%C3%A9chin%C3%A9').decode('utf-8')
JSON in Python: How do I get specific parts of an array?,[1505]
two's complement of numbers in python,"format(num, '016b')"
How to delete rows from a pandas DataFrame based on a conditional expression,df[df['column name'].map(len) < 2]
How do I add a % symbol to my Python script,"print('The average is: ' + format(average, ',.3f') + '%')"
Nested parallelism in Python,pickle.dumps(threading.Lock())
Save matplotlib file to a directory,fig.savefig('Sub Directory/graph.png')
Select everything but a list of columns from pandas dataframe,df[df.columns.difference(['T1_V6'])]
Python - convert list of tuples to string,""""""", """""".join(map(str, tups))"
retrieving a variable's name in python at runtime?,locals()['i']
How can I clear the Python pdb screen?,os.system('cls')
More Pythonic/Pandorable approach to looping over a pandas Series,"pd.Series(np.einsum('ij->i', s.values.reshape(-1, 3)))"
How to post data structure like json to flask?,content = request.json['content']
What can I do with a closed file object?,open(f.name).read()
Python: Built-in Keyboard Signal/Interrupts,sys.exit()
Plotting a 2D Array with Matplotlib,"ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet)"
Pandas replace all items in a row with NaN if one value is NaN,"df.loc[(df.isnull().any(axis=1)), :] = np.nan"
Plot specific rows of a pandas dataframe,data.iloc[499:999].plot(y='value')
How to convert Spark RDD to pandas dataframe in ipython?,df.toPandas()
Extract day of year and Julian day from a string date in python,"int(sum(jdcal.gcal2jd(dt.year, dt.month, dt.day)))"
Case insensitive dictionary search with Python,"a_lower = dict((k.lower(), v) for k, v in list(a.items()))"
Python - Intersection of two lists of lists,"{tuple(x) for x in l1}.intersection(map(tuple, l2))"
Getting task_id inside a Celery task,print(celery.current_task.task_id)
A better way to assign list into a var,starf = [int(i) for i in starf]
Sum the second value of each tuple in a list,sum(zip(*structure)[1])
How To Plot Multiple Histograms On Same Plot With Seaborn,"plt.hist([x, y], color=['r', 'b'], alpha=0.5)"
Reshaping array into a square array Python,"x.reshape(2, 2, 5).transpose(1, 0, 2)"
Python: Using vars() to assign a string to a variable,locals()[4]
How to set a default string for raw_input?,i = input('Please enter name[Jack]:') or 'Jack'
pymongo: how to use $or operator to an column that is an array?,"collection1.find({'albums': {'$in': [3, 7, 8]}})"
How to check if one of the following items is in a list?,S1.intersection(S2)
Matplotlib: How to remove the vertical space when displaying circles on a grid?,plt.gca().invert_yaxis()
How to zip two lists of lists in Python?,"[list(itertools.chain(*x)) for x in zip(L1, L2)]"
Python: How do I display a timer in a terminal,sys.stdout.write('\rComplete! \n')
Referring a single Google datastore kind multiple times in another kind with ndb,"ndb.KeyProperty(kind='Foo', required=True)"
Python Sockets: Enabling Promiscuous Mode in Linux,"s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)"
How do I get the whole content between two xml tags in Python?,"tostring(element).split('>', 1)[1]"
Parallel Coordinates plot in Matplotlib,plt.show()
Summation of elements of dictionary that are list of lists,"{k: [(a + b) for a, b in zip(*v)] for k, v in list(d.items())}"
How to keep all my django applications in specific folder,"sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))"
How do you get the current text contents of a QComboBox?,text = str(combobox1.currentText())
JSON load/dump in Python,"the_dump = json.dumps(['foo', {'bar': ['baz', None, 1.0, 2]}])"
Python: how to count overlapping occurrences of a substring,"len([_ for s in re.finditer('(?=aa)', 'aaa')])"
Would it be possible to create multiple dataframes in one go?,"df.groupby(['A', 'S'])[cols].agg(['sum', 'size'])"
Subtracting Dates With Python,"datetime.datetime.combine(birthdate, datetime.time())"
read HDF5 file to pandas DataFrame with conditions,"pd.read_hdf('/tmp/out.h5', 'results_table', where='A in [1,3,4]')"
"Python, Encoding output to UTF-8",s.encode('utf8')
Efficiently select rows that match one of several values in Pandas DataFrame,"df[df.Name.isin(['Alice', 'Bob'])]"
"In numpy, what is the fastest way to multiply the second dimension of a 3 dimensional array by a 1 dimensional array?","A * B[:, (np.newaxis)]"
How to make a histogram from a list of strings in Python?,"a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']"
numpy: efficiently add rows of a matrix,"np.dot(np.dot(I, np.ones((7,), int)), mat)"
Merge two integers in Python,z = int(str(x) + str(y))
How do I remove \n from my python dictionary?,"x = line.rstrip('\n').split(',')"
"Access all elements at given x, y position in 3-dimensional numpy array","np.mgrid[0:5, 0:5].transpose(1, 2, 0).reshape(-1, 2)"
Access an arbitrary element in a dictionary in Python,list(dict.keys())
Write a binary integer or string to a file in python,"f.write(struct.pack('i', value))"
matplotlib: is a changing background color possible?,"plt.axvspan(x, x2, facecolor='g', alpha=0.5)"
Suppress the u'prefix indicating unicode' in python strings,print(str('a'))
Correct way to escape a subprocess call in python,"cmd = subprocess.Popen(['sed', '-n', '$=', filename], stdout=subprocess.PIPE)"
Python: Best Way to remove duplicate character from string,""""""""""""".join(ch for ch, _ in itertools.groupby(foo))"
How can I Change type Of Django Calender With Persian Calender?,widgets = {'delivery_date': forms.DateInput(attrs={'id': 'datepicker'})}
How does Numpy infers dtype for array,"np.array(12345678901234, dtype=np.int32)"
Table legend with header in matplotlib,plt.show()
How to add new object attribute with Python/Django,{{post.featured_image}}