text
stringlengths
4
1.08k
How to subtract values from dictionaries,"d3 = {key: (d1[key] - d2.get(key, 0)) for key in list(d1.keys())}"
python + matplotlib: how can I change the bar's line width for a single bar?,plt.show()
Defining the midpoint of a colormap in matplotlib,ax.set_xticks([])
Python convert long to date,datetime.datetime.fromtimestamp(myNumber).strftime('%Y-%m-%d %H:%M:%S')
How to get full path of current file's directory in Python?,os.path.dirname(os.path.abspath(__file__))
How can I convert this string to list of lists?,"ast.literal_eval('[(0,0,0), (0,0,1), (1,1,0)]')"
load csv into 2D matrix with numpy for plotting,"numpy.loadtxt(open('test.csv', 'rb'), delimiter=',', skiprows=1)"
Multiple linear regression with python,"x = np.array([[1, 2, 3, 4, 5], [4, 5, 6, 7, 8]], np.int32)"
How to extract data from JSON Object in Python?,"json.loads('{""foo"": 42, ""bar"": ""baz""}')['bar']"
How to find row of 2d array in 3d numpy array,"array([True, False, False, True], dtype=bool)"
How to decode encodeURIComponent in GAE (python)?,urllib.parse.unquote(h.path.encode('utf-8')).decode('utf-8')
Python Accessing Nested JSON Data,print(data['places'][0]['post code'])
Python/Matplotlib - Is there a way to make a discontinuous axis?,plt.show()
How do I use a regular expression to match a name?,"re.match('[a-zA-Z][\\w-]*$', '!A_B')"
python pandas: plot histogram of dates?,df.groupby(df.date.dt.month).count().plot(kind='bar')
How do I efficiently combine similar dataframes in Pandas into one giant dataframe,"df1.set_index('Date', inplace=True)"
How to sort a Python dictionary by value?,"sorted(list(a_dict.items()), key=lambda item: item[1][1])"
How to merge two Python dictionaries in a single expression?,"dict((k, v) for d in dicts for k, v in list(d.items()))"
Simple way to create matrix of random numbers,"numpy.random.random((3, 3))"
python getting a list of value from list of dict,[x['value'] for x in list_of_dicts]
How to iterate over time periods in pandas,"s.resample('3M', how='sum')"
pandas read csv with extra commas in column,"df = pd.read_csv('comma.csv', quotechar=""'"")"
Cannot insert data into an sqlite3 database using Python,db.commit()
Convert string to image in python,"img = Image.new('RGB', (200, 100), (255, 255, 255))"
How to get http headers in flask?,request.headers['your-header-name']
Remove strings from a list that contains numbers in python,[x for x in my_list if not any(c.isdigit() for c in x)]
How to find the minimum value in a numpy matrix?,arr[arr != 0].min()
How to convert integer value to array of four bytes in python,"struct.unpack('4b', struct.pack('I', 100))"
Change directory to the directory of a Python script,os.chdir(os.path.dirname(__file__))
Generate a sequence of numbers in Python,""""""","""""".join(str(i) for i in range(100) if i % 4 in (1, 2))"
best way to extract subset of key-value pairs from python dictionary object,"{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}"
Python/Matplotlib - Is there a way to make a discontinuous axis?,plt.show()
How do I load a file into the python console?,"exec(compile(open('file.py').read(), 'file.py', 'exec'))"
Python: how to get rid of spaces in str(dict)?,"'{' + ','.join('{0!r}:{1!r}'.format(*x) for x in list(dct.items())) + '}'"
How can I split a string into tokens?,"print([i for i in re.split('([\\d.]+|\\W+)', 'x+13.5*10x-4e1') if i])"
Extracting an attribute value with beautifulsoup,inputTag = soup.findAll(attrs={'name': 'stainfo'})
How to extract tuple values in pandas dataframe for use of matplotlib?,df.head()
How to hide output of subprocess in Python 2.7,"subprocess.check_output(['espeak', text], stderr=subprocess.STDOUT)"
How to overwrite a file in Python?,"open('some_path', 'r+')"
How can I concatenate a Series onto a DataFrame with Pandas?,"pd.concat([students, pd.DataFrame(marks)], axis=1)"
python dict comprehension with two ranges,"dict(zip(list(range(1, 5)), list(range(7, 11))))"
How do I convert a string to a buffer in Python 3.1?,"""""""insert into egg values ('egg');"""""".encode('ascii')"
How to run two functions simultaneously,threading.Thread(target=SudsMove).start()
Most pythonic way to convert a list of tuples,zip(*list_of_tuples)
pandas: How do I split text in a column into multiple rows?,df.join(s.apply(lambda x: Series(x.split(':'))))
How to perform search on a list of tuples,"[('jamy', 'Park', 'kick'), ('see', 'it', 'works')]"
How to convert column with dtype as object to string in Pandas Dataframe,df['column'] = df['column'].astype('str')
How to base64 encode a PDF file in Python,"a = open('pdf_reference.pdf', 'rb').read().encode('base64')"
Sum of all values in a Python dict,sum(d.values())
In Tkinter is there any way to make a widget not visible? ,root.mainloop()
Check if a key exists in a Python list,"test(['important', 'comment', 'bar'])"
python sorting dictionary by length of values,"print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))"
Plotting Ellipsoid with Matplotlib,plt.show()
What does a for loop within a list do in Python?,myList = [i for i in range(10)]
Python : how to append new elements in a list of list?,a = [[] for i in range(3)]
How do I convert a unicode to a string at the Python level?,""""""""""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9').decode('utf8')"
Python Pandas: Multiple aggregations of the same column,"df.groupby('dummy').agg({'returns': [np.mean, np.sum]})"
Efficient way to convert a list to dictionary,"dict(map(lambda s: s.split(':'), ['A:1', 'B:2', 'C:3', 'D:4']))"
Summing across rows of Pandas Dataframe,"df.groupby(['stock', 'same1', 'same2'], as_index=False)['positions'].sum()"
How do i plot multiple plots in a single rectangular grid in matplotlib?,plt.show()
split a string in python,a.split('\n')[:-1]
case sensitive string replacement in Python,"""""""Abc"""""".translate(maketrans('abcABC', 'defDEF'))"
How to remove multiple indexes from a list at the same time?,del my_list[2:6]
Print to the same line and not a new line in python,sys.stdout.flush()
"How to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/a '])"
"How to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/s'])"
How do I increase the timeout for imaplib requests?,"urlfetch.fetch(url, deadline=10 * 60)"
How do I check if a string is unicode or ascii?,s.decode('ascii')
Nonlinear colormap with Matplotlib,plt.show()
How can I create a borderless application in Python (windows)?,sys.exit(app.exec_())
Read a local file in django,PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
How to use and plot only a part of a colorbar in matplotlib?,plt.show()
Close a tkinter window?,root.destroy()
How to create a legend for 3D bar in matplotlib?,plt.show()
Get date format in Python in Windows,"locale.setlocale(locale.LC_ALL, 'english')"
How to order a list of lists by the first value,l1.sort(key=lambda x: int(x[0]))
Sort tuples based on second parameter,my_list.sort(key=lambda x: x[1])
"How to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/r', '/t', '900'])"
Print multiple arguments in python,"print('Total score for %s is %s ' % (name, score))"
Python Mechanize select a form with no name,br.select_form(nr=0)
How to auto-scroll a gtk.scrolledwindow?,"self.treeview.connect('size-allocate', self.treeview_changed)"
Dynamically updating a bar plot in matplotlib,plt.show()
Summarizing a dictionary of arrays in Python,"heapq.nlargest(3, iter(mydict.items()), key=lambda tup: sum(tup[1]))"
How to write/read a Pandas DataFrame with MultiIndex from/to an ASCII file?,"df.to_csv('mydf.tsv', sep='\t')"
Python initializing a list of lists,x = [[] for i in range(3)]
How to delete an RDD in PySpark for the purpose of releasing resources?,"thisRDD = sc.parallelize(range(10), 2).cache()"
Creating a Multiplayer game in python,time.sleep(5)
Removing runs from a 2D numpy array,"unset_ones(np.array([0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0]), 3)"
Fit a curve using matplotlib on loglog scale,plt.show()
How to get the resolution of a monitor in Pygame?,"pygame.display.set_mode((0, 0), pygame.FULLSCREEN)"
Extract all keys from a list of dictionaries,[list(d.keys()) for d in LoD]
Create Pandas DataFrame from txt file with specific pattern,"df = pd.read_csv('filename.txt', sep=';', names=['Region Name'])"
Split pandas dataframe column based on number of digits,df.value.astype(str).apply(list).apply(pd.Series).astype(int)
Changing user in python,"os.system('su hadoop -c ""bin/hadoop-daemon.sh stop tasktracker""')"
applying regex to a pandas dataframe,df['Season'].str.split('-').str[0].astype(int)
Using a variable in xpath in Python Selenium,"driver.find_element_by_xpath(""//option[@value='"" + state + ""']"").click()"
How do I convert a unicode to a string at the Python level?,""""""""""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9')"
Python regex to remove all words which contains number,"re.sub('\\w*\\d\\w*', '', words).strip()"
How can I send email using Python?,server = smtplib.SMTP('smtp.gmail.com:587')
How to work with surrogate pairs in Python?,"""""""\\ud83d\\ude4f"""""".encode('utf-16', 'surrogatepass').decode('utf-16')"