text
stringlengths
4
1.08k
How to refine a mesh in python quickly,"np.array([j for i in arr for j in np.arange(i - 0.2, i + 0.25, 0.1)])"
How to sort a list of strings with a different order?,"['a\xc3\xa1', 'ab', 'abc']"
How to read CSV file with of data frame with row names in Pandas,"pd.io.parsers.read_csv('tmp.csv', sep='\t', index_col=0)"
Python Matplotlib: Change Colorbar Tick Width,CB.lines[0].set_linewidth(10)
How would I sum a multi-dimensional array in the most succinct python?,"sum(map(sum, my_list))"
How do I get the whole content between two xml tags in Python?,"tostring(element).split('>', 1)[1].rsplit('</', 1)[0]"
How should I take the max of 2 columns in a dataframe and make it another column?,df['C'] = df.max(axis=1)
Find specific link text with bs4,"links = soup.find_all('a', {'id': 'c1'})"
How to give a pandas/matplotlib bar graph custom colors,"df.plot(kind='bar', stacked=True, colormap='Paired')"
Can I repeat a string format descriptor in python?,print(('{:5d} ' * 5).format(*values))
How to configure Logging in Python,handler.setLevel(logging.DEBUG)
How do I split an ndarray based on array of indexes?,"print(np.split(a, b, axis=0))"
How do I convert local time to UTC in Python?,utc_dt.strftime('%Y-%m-%d %H:%M:%S')
how to add an xml node based on the value of a text node,"tree.xpath('//phylo:name[text()=""Espresso""]', namespaces=nsmap)"
Transform unicode string in python,"normalize('NFKD', s).encode('ASCII', 'ignore')"
flask : how to architect the project with multiple apps?,app.run(debug=True)
getting the opposite diagonal of a numpy array,np.diag(np.fliplr(array))
Comparing elements between elements in two lists of tuples,"[x[0] for x, y in zip(l1, l2) if x[0] == y[0]]"
arrange labels for plots on multiple panels to be in one line in matplotlib,ax.yaxis.set_major_formatter(formatter)
Get unique values from a list in python,"a = ['a', 'b', 'c', 'd', 'b']"
How to deal with SettingWithCopyWarning in Pandas?,"df.ix[0, 'a'] = 3"
using python logging in multiple modules,logger = logging.getLogger(__name__)
"Difference between using commas, concatenation, and string formatters in Python","print('I am printing {0} and {y}'.format(x, y=y))"
How to write binary data in stdout in python 3?,sys.stdout.write('Your string to Stdout\n')
Printing tuple with string formatting in Python,"print('this is a tuple: %s' % (thetuple,))"
Deleting columns in a CSV with python,"wtr.writerow((r[0], r[1], r[3], r[4]))"
How to resample a dataframe with different functions applied to each column?,"frame.resample('1H', how={'radiation': np.sum, 'tamb': np.mean})"
"Pandas lookup, mapping one column in a dataframe to another in a different dataframe","df1 = df1.merge(df2[['weeknum', 'datetime']], on=['weeknum'])"
Method of Multiple Assignment in Python,"a, b, c = [1, 2, 3]"
Python pandas: replace values multiple columns matching multiple columns from another dataframe,"df_merged = pd.merge(df1, df2, how='inner', on=['chr', 'pos'])"
Subsetting a 2D numpy array,"a[[1, 2, 3], [1, 2, 3]]"
How can I add an additional row and column to an array?,"L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]"
Setting a clip on a seaborn plot,plt.show()
Convert list to tuple in Python,tuple(l)
Writing a list of sentences to a single column in csv with Python,writer.writerows([val])
Is there a way to remove duplicate and continuous words/phrases in a string?,"re.sub('\\b(.+)\\s+\\1\\b', '\\1', s)"
How to append in a json file in Python?,"json.dump(data, f)"
Remove all occurrences of several chars from a string,"re.sub('[ -.:]', '', ""'::2012-05-14 18:10:20.856000::'"")"
Sort a part of a list in place,a[i:j] = sorted(a[i:j])
Python: How can I include the delimiter(s) in a string split?,"['(', 'two', 'plus', 'three', ')', 'plus', 'four']"
Find/extract a sequence of integers within a list in python,"[1, 2, 3, 4]"
How do I count unique values inside an array in Python?,len(set(new_words))
Apply function with args in pandas,"df['Result'] = df.apply(func, axis=1)"
How do I start up remote debugging with PyCharm?,sys.path.append('/home/john/app-dependancies/pycharm-debug.egg')
How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?,"pd.set_option('display.max_colwidth', -1)"
How to draw line inside a scatter plot,ax.set_xlabel('FPR or (1 - specificity)')
convert string to hex in python,"int('0x77', 16)"
How to avoid line color repetition in matplotlib.pyplot?,plt.savefig('pal3.png')
Pandas group by time windows,df.groupby(df['date_time'].apply(my_grouper))
using pandas in python to append csv files into one,"df = pd.concat([df1, df2], ignore_index=True)"
How can I ensure that my Python regular expression outputs a dictionary?,"json.loads('{""hello"" : 4}')"
Python: Using a dictionary to count the items in a list,"Counter(['apple', 'red', 'apple', 'red', 'red', 'pear'])"
python split function -avoids last empy space,my_str.rstrip(';').split(';')
how do I make a single legend for many subplots with matplotlib?,"fig.legend(lines, labels, loc=(0.5, 0), ncol=5)"
Creating a JSON response using Django and Python,return JsonResponse({'foo': 'bar'})
How to find the difference between two lists of dictionaries?,[i for i in a if i not in b]
Character reading from file in Python,f.close()
Python: Test if value can be converted to an int in a list comprehension,[row for row in listOfLists if row[x].isdigit()]
Python: How do I convert from binary to base 64 and back?,bin(int(s.decode('base64')))
matplotlib - How to plot a random-oriented rectangle (or any shape)?,plt.show()
Splitting a string by list of indices,print('\n'.join(parts))
How to get an UTC date string in Python?,datetime.utcnow().strftime('%Y%m%d')
How to find match items from two lists?,set(data1).intersection(data2)
Python Map List of Strings to Integer List,"s = ['michael', 'michael', 'alice', 'carter']"
"Plotting within a for loop, with 'hold on' effect in matplotlib?",plt.show()
How to detect exceptions in concurrent.futures in Python3?,time.sleep(1)
How do you count cars in OpenCV with Python?,"plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)), plt.title('Original')"
Python - NumPy - tuples as elements of an array,"a = zeros((ph, pw), dtype=(float, 3))"
"Pandas, filter rows which column contain another column",df[df['B'].str.contains('|'.join(df['A']))]
How do I import modules in pycharm?,__init__.py
Elegant way to transform a list of dict into a dict of dicts,{i.pop('name'): i for i in listofdict}
How to find elements by class,"soup.find_all('div', class_='stylelistrow')"
How to find elements by class,"soup.find_all('div', class_='stylelistrowone stylelistrowtwo')"
Create pdf with tooltips in python,plt.savefig('tooltips.pdf')
"return max value from panda dataframe as a whole, not based on column or rows",df.values.max()
how to replace the characters in strings with '#'s by using regex in Python,"re.sub('\\w', '#', s)"
List Comprehensions in Python : efficient selection in a list,(f(x) for x in list)
Replace all non-alphanumeric characters in a string,"s = re.sub('[^0-9a-zA-Z]+', '*', s)"
Delete a group after pandas groupby,df.drop(grouped.get_group(group_name).index)
Cannot return results from stored procedure using Python cursor,"cursor.callproc('getperson', ['1'])"
How to create a fix size list in python?,[None for _ in range(10)]
extract columns from multiple text file with Python,file_name.split('.')
What does the 'b' character do in front of a string literal?,"""""""€"""""".decode('UTF-8')"
Python - How to calculate equal parts of two dictionaries?,"d3 = {k: v for k, v in list(d3.items()) if v}"
How do I create a new database in MongoDB using PyMongo?,collection = db['test-collection']
Can't execute an INSERT statement in a Python script via MySQLdb,conn.commit()
sorting a list of dictionary values by date in python,"your_list.sort(key=itemgetter('date'), reverse=True)"
Python print key in all dictionaries,""""""", """""".join(['William', 'Shatner', 'Speaks', 'Like', 'This'])"
Hiding axis text in matplotlib plots,ax.xaxis.set_major_formatter(plt.NullFormatter())
How can I do an atomic write to stdout in python?,sys.stdout.write(msg)
How do I add a header to urllib2 opener?,opener.open('http://www.example.com/')
Individual alpha values in scatter plot / Matplotlib,plt.show()
How to concatenate string cell contents,workbook.close()
Break string into list elements based on keywords,"['Na', '1', 'H', '1', 'C', '2', 'H', '3', 'O', '2']"
How to count number of rows in a group in pandas group by object?,"df[['col3', 'col4', 'col5', 'col6']].astype(float)"
Pandas groupby: Count the number of occurences within a time range for each group,df['yes'] = df['WIN'].map(lambda x: 1 if x == 'Yes' else np.nan)
Convert string representation of list to list in Python,"ast.literal_eval('[""A"",""B"" ,""C"" ,"" D""]')"
Create block diagonal numpy array from a given numpy array,"np.kron(np.eye(n), a)"
Convert dataFrame to list,df[0].values.tolist()
hexadecimal string to byte array in python,bytearray.fromhex('de ad be ef 00')