text
stringlengths
4
1.08k
time data does not match format,"datetime.strptime('07/28/2014 18:54:55.099', '%m/%d/%Y %H:%M:%S.%f')"
Consuming a kinesis stream in python,time.sleep(1)
Merge 2 dataframes with same values in a column,df2.CET.map(df1.set_index('date')['revenue'])
Python MySQL Parameterized Queries,"c.execute('SELECT * FROM foo WHERE bar = %s AND baz = %s', (param1, param2))"
applying regex to a pandas dataframe,df['Season'].apply(split_it)
Reading XML using Python minidom and iterating over each node,node.getElementsByTagName('author')[0].childNodes[0].nodeValue
How do I get mouse position relative to the parent widget in tkinter?,root.mainloop()
Python- insert a character into a string,print(''.join(parts[1:]))
Indexing one array by another in numpy,"A[np.arange(A.shape[0])[:, (None)], B]"
How can I generalize my pandas data grouping to more than 3 dimensions?,"df2.xs('b', axis=1, level=1)"
Python/Matplotlib - Is there a way to make a discontinuous axis?,"ax.set_xlim(0, 1)"
Get seconds since midnight in python,datetime.now() - datetime.now()
How can I do a batch insert into an Oracle database using Python?,connection.close()
How to set font size of Matplotlib axis Legend?,"plt.setp(legend.get_title(), fontsize='xx-small')"
Python: How to add three text files into one variable and then split it into a list,"msglist = [hextotal[i:i + 4096] for i in range(0, len(hextotal), 4096)]"
How to pickle unicodes and save them in utf-8 databases,pickled_data.decode('latin1')
Is there a way to make the Tkinter text widget read only?,text.config(state=DISABLED)
How to resample a dataframe with different functions applied to each column?,"frame.resample('1H').agg({'radiation': np.sum, 'tamb': np.mean})"
Python - How to extract the last x elements from a list,new_list = my_list[-10:]
How to deal with SettingWithCopyWarning in Pandas?,"df.loc[df['A'] > 2, 'B'] = new_val"
Insert 0s into 2d array,"array([[-1, -1], [0, 0], [1, 1]])"
How do i find the iloc of a row in pandas dataframe?,df[df.index < '2000-01-04'].index[-1]
Inserting a string into a list without getting split into characters,list.append('foo')
How to make a copy of a 2D array in Python?,y = [row[:] for row in x]
How do I convert a datetime.date object into datetime.datetime in python?,"datetime.datetime.combine(dateobject, datetime.time())"
How can I unpack binary hex formatted data in Python?,data.encode('hex')
How to check if something exists in a postgresql database using django?,"Entry.objects.filter(name='name', title='title').exists()"
Overriding initial value in ModelForm,"super(ArtefactForm, self).__init__(*args, **kwargs)"
Sort a list of strings based on regular expression match or something similar,"strings.sort(key=lambda str: re.sub('.*%(.).*', '\\1', str))"
How do I sort a list of strings in Python?,mylist.sort(key=lambda x: x.lower())
Horizontal stacked bar chart in Matplotlib,plt.show()
Hash Map in Python,"streetno = dict({'1': 'Sachine Tendulkar', '2': 'Dravid'})"
"In Python, find out number of differences between two ordered lists","sum(1 for i, j in zip(a, b) if i != j)"
using pyodbc on ubuntu to insert a image field on SQL Server,cur.execute('SET TEXTSIZE 2147483647 SELECT myimage FROM testing WHERE id = 1')
How do I turn a dataframe into a series of lists?,pd.Series(df.T.to_dict('list'))
Calculating difference between two rows in Python / Pandas,data.set_index('Date').diff()
How to print container object with unicode-containing values?,print(str(x).decode('raw_unicode_escape'))
How do I remove identical items from a list and sort it in Python?,sorted(set(my_list))
Google App Engine: how can I programmatically access the properties of my Model class?,p.properties()[s].get_value_for_datastore(p)
python import a module from a directory(package) one level up,sys.path.append('/path/to/pkg1')
Formatting floats in a numpy array,np.random.randn(5) * 10
Flask and SqlAlchemy how to delete records from ManyToMany Table?,db.session.commit()
"dropping a row in pandas with dates indexes, python",df.ix[:-1]
How to merge two columns together in Pandas,"pd.melt(df, id_vars='year')['year', 'value']"
Django ORM way of going through multiple Many-to-Many relationship,Toy.objects.filter(toy_owners__parents=parent)
how to clear the screen in python,os.system('cls')
Can I read and write file in one line with Python?,"f.write(open('xxx.mp4', 'rb').read())"
lambda returns lambda in python,"curry = lambda f, a: lambda x: f(a, x)"
changing the values of the diagonal of a matrix in numpy,A.ravel()[A.shape[1] * i:A.shape[1] * (i + A.shape[1]):A.shape[1] + 1]
What is a maximum number of arguments in a Python function?,"exec ('f(' + ','.join(str(i) for i in range(5000)) + ')')"
Find string with regular expression in python,print(url.split('/')[-1].split('.')[0])
Mark ticks in latex in matplotlib,plt.show()
Upload files to Google cloud storage from appengine app,"upload_url = blobstore.create_upload_url('/upload', gs_bucket_name='my_bucket')"
How to put the legend out of the plot,plt.show()
How to specify date format when using pandas.to_csv?,"df.to_csv(filename, date_format='%Y%m%d')"
How to convert a hex string to hex number,"print(hex(int('0xAD4', 16) + int('0x200', 16)))"
Python split string by pattern,repeat = re.compile('(?P<start>[a-z])(?P=start)*-?')
Matplotlib: draw a series of radial lines on PolarAxes,ax.axes.get_yaxis().set_visible(False)
First non-null value per row from a list of Pandas columns,df.stack().groupby(level=0).first()
PyQt - how to detect and close UI if it's already running?,sys.exit(app.exec_())
Is there a way to reopen a socket?,"sck.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)"
Prepend the same string to all items in a list,['hello{0}'.format(i) for i in a]
Reading hex to double-precision float python,"struct.unpack('d', binascii.unhexlify('4081637ef7d0424a'))"
Python/Regex - Expansion of Parentheses and Slashes,"['1', '(15/-23)s', '4']"
Sort a string in lexicographic order python,"sorted(sorted(s), key=str.upper)"
Can I have a non-greedy regex with dotall?,"re.findall('a*?bc*?', 'aabcc', re.DOTALL)"
How to print Unicode character in Python?,print('here is your checkmark: ' + '\u2713')
Reading a text file and splitting it into single words in python,[line.split() for line in f]
Find the sum of subsets of a list in python,"weekly = [sum(visitors[x:x + 7]) for x in range(0, len(daily), 7)]"
Line plot with arrows in matplotlib,plt.show()
Extract data from HTML table using Python,"r.sub('\\1_STATUS = ""\\2""\\n\\1_TIME = \\3', content)"
How to get raw sql from session.add() in sqlalchemy?,"engine = create_engine('postgresql://localhost/dbname', echo=True)"
Normalizing colors in matplotlib,plt.show()
How to convert a nested list into a one-dimensional list in Python?,"list(flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))"
list of ints into a list of tuples python,"print(zip(my_list[0::2], my_list[1::2]))"
Python: how to create a file .txt and record information in it,file.close()
How to serialize SqlAlchemy result to JSON?,json.dumps([dict(list(row.items())) for row in rs])
Get required fields from Document in mongoengine?,"[k for k, v in User._fields.items() if v.required]"
"python, locating and clicking a specific button with selenium",next = driver.find_element_by_css_selector('li.next>a')
How to pass a list of lists through a for loop in Python?,"[[0.5, 0.625], [0.625, 0.375]]"
How can i split a single tuple into multiple using python?,d = {t[0]: t[1:] for t in l}
split elements of a list in python,"[i.split('\t', 1)[0] for i in l]"
How do I abort the execution of a Python script?,sys.exit('aa! errors!')
How to copy files to network path or drive using Python,"shutil.copyfile('foo.txt', 'P:\\foo.txt')"
Extracting first n columns of a numpy matrix,"A = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]"
How to set xlim and ylim for a subplot in matplotlib,"ax2.set_ylim([0, 5])"
How do I abort the execution of a Python script?,sys.exit(0)
How to filter only printable characters in a file on Bash (linux) or Python?,print('\n'.join(lines))
How to redirect python warnings to a custom stream?,warnings.warn('test warning')
how to login to a website with python and mechanize,browser.submit()
how to sort by a computed value in django,"sorted(Profile.objects.all(), key=lambda p: p.reputation)"
Write dictionary of lists to a CSV file,writer.writerows(zip(*[d[key] for key in keys]))
How to display the first few characters of a string in Python?,"""""""string"""""""
Python: Passing a function name as an argument in a function,var = dork1
How can I format a float using matplotlib's LaTeX formatter?,"ax.set_title('$%s \\times 10^{%s}$' % ('3.5', '+20'))"
Functional statement in Python to return the sum of certain lists in a list of lists,sum(len(y) for y in x if len(y) > 1)
Getting the correct timezone offset in Python using local timezone,dt = datetime.datetime.utcfromtimestamp(1288483950)
Remove one column for a numpy array,"b = np.delete(a, -1, 1)"
Printing lists onto tables in python,"print('\n'.join(' '.join(map(str, row)) for row in t))"
How can I change a specific row label in a Pandas dataframe?,df = df.rename(index={last: 'a'})