text
stringlengths
4
1.08k
Pythonic way to eval all octal values in a string as integers,"re.sub('\\b0+(?!\\b)', '', '012+2+0-01+204-0')"
How to plot a gradient color line in matplotlib?,plt.show()
How to use variables in SQL statement in Python?,"cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))"
Turn dataframe into frequency list with two column variables in Python,"pd.concat([df1, df2], axis=1, keys=['precedingWord', 'comp'])"
How do you split a list into evenly sized chunks?,"[l[i:i + n] for i in range(0, len(l), n)]"
listing files from a directory using glob python,glob.glob('hello*.txt')
listing files from a directory using glob python,glob.glob('[!hello]*.txt')
How to do many-to-many Django query to find book with 2 given authors?,Book.objects.filter(author__id=1).filter(author__id=2)
How to merge two Python dictionaries in a single expression?,"{k: v for d in dicts for k, v in list(d.items())}"
Is there a way to remove duplicate and continuous words/phrases in a string?,"re.sub('\\b(.+)(\\s+\\1\\b)+', '\\1', s)"
How to set the timezone in Django?,TIME_ZONE = 'Europe/Istanbul'
Python - Locating the position of a regex match in a string?,"re.search('is', String).start()"
How to use regular expression in lxml xpath?,"doc.xpath(""//a[starts-with(text(),'some text')]"")"
Delete column from pandas DataFrame,"df.drop('column_name', axis=1, inplace=True)"
Logarithmic y-axis bins in python,"plt.yscale('log', nonposy='clip')"
Python - sum values in dictionary,sum(item['gold'] for item in myLIst)
Regex for removing data in parenthesis,"item = re.sub(' \\(\\w+\\)', '', item)"
Best way to remove elements from a list,[item for item in my_list if 1 <= item <= 5]
"Extracting words from a string, removing punctuation and returning a list with separated words in Python","re.compile('\\w+').findall('Hello world, my name is...James the 2nd!')"
How can I increase the frequency of xticks/ labels for dates on a bar plot?,"plt.xticks(dates, rotation='25')"
Python - Insert numbers in string between quotes,"re.sub('(\\d+)', '""\\1""', 'This is number 1 and this is number 22')"
Django: How to get the root path of a site in template?,"url('^mah_root/$', 'someapp.views.mah_view', name='mah_view'),"
Convert list of dictionaries to Dataframe,pd.DataFrame(d)
How to get rid of punctuation using NLTK tokenizer?,"['Eighty', 'seven', 'miles', 'to', 'go', 'yet', 'Onward']"
Sum all values of a counter in Python,sum(my_counter.values())
converting string to tuple,"[tuple(int(i) for i in el.strip('()').split(',')) for el in s.split('),(')]"
Python(pandas): removing duplicates based on two columns keeping row with max value in another column,"df.sort('C').drop_duplicates(subset=['A', 'B'], take_last=True)"
sort dict by value python,"sorted(list(data.items()), key=lambda x: x[1])"
How to sort a Pandas DataFrame according to multiple criteria?,"df.sort(['Peak', 'Weeks'], ascending=[True, False], inplace=True)"
how to turn a string of letters embedded in squared brackets into embedded lists,"[i.split() for i in re.findall('\\[([^\\[\\]]+)\\]', a)]"
"how to get around ""Single '}' encountered in format string"" when using .format and formatting in printing","print('{0:<15}{1:<15}{2:<8}'.format('1', '2', '3'))"
How do I disable log messages from the Requests library?,logging.getLogger('urllib3').setLevel(logging.WARNING)
NumPy List Comprehension Syntax,[[X[i][j] for j in range(len(X[i]))] for i in range(len(X))]
What is the easiest way to convert list with str into list with int?,"map(int, ['1', '2', '3'])"
Removing entries from a dictionary based on values,"dict((k, v) for k, v in hand.items() if v)"
How to replace values with None in Pandas data frame in Python?,"df.replace('-', np.nan)"
applying regex to a pandas dataframe,df['Season2'] = df['Season'].apply(split_it)
Python Pandas: How to move one row to the first row of a Dataframe?,"df = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])"
Python - Locating the position of a regex match in a string?,"re.search('\\bis\\b', String).start()"
sort dict by value python,sorted(data.values())
how to access the class variable by string in Python?,"getattr(test, a_string)"
What is the best way to convert a zope DateTime object into Python datetime object?,"time.strptime('04/25/2005 10:19', '%m/%d/%Y %H:%M')"
Looping through files in a folder,"folder = os.path.join('C:\\', 'Users', 'Sprinting', 'blue')"
Importing a Python package from a script with the same name,"sys.path.insert(0, '..')"
Joining pandas dataframes by column names,"pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')"
How can I send email using Python?,"server = smtplib.SMTP(host='smtp.gmail.com', port=587)"
Get the number of all keys in a dictionary of dictionaries in Python,len(dict_test) + sum(len(v) for v in dict_test.values())
How to extract from a list of objects a list of specific attribute?,[o.my_attr for o in my_list]
Python: How to find the slope of a graph drawn using matplotlib?,plt.show()
gzip a file in Python,f.close()
How do I sort a Python list of time values?,"sorted(['14:10:01', '03:12:08'])"
First common element from two lists,[i for i in x if i in y]
Python Pandas - Date Column to Column index,df.set_index('month')
Trying to use reduce() and lambda with a list containing strings,"from functools import reduce
reduce(lambda x, y: x * int(y), ['2', '3', '4'])"
How to convert from infix to postfix/prefix using AST python module?,"['w', 'time', '*', 'sin']"
Convert Unicode to UTF-8 Python,print(text.encode('windows-1252'))
Sorting numpy array on multiple columns in Python,"order_array.sort(order=['year', 'month', 'day'])"
Convert binary string to list of integers using Python,"list(range(0, len(s), 3))"
Sort list of mixed strings based on digits,"sorted(l, key=lambda x: int(re.search('\\d+', x).group(0)))"
applying regex to a pandas dataframe,df['Season'].str[:4].astype(int)
How to extract data from matplotlib plot,gca().get_lines()[n].get_xydata()
Find rows with non zero values in a subset of columns in pandas dataframe,"df.loc[(df.loc[:, (df.dtypes != object)] != 0).any(1)]"
How to avoid line color repetition in matplotlib.pyplot?,"pyplot.plot(x, y, color='#112233')"
Removing letters from a list of both numbers and letters,""""""""""""".join([c for c in strs if c.isdigit()])"
Creating a dictionary from a string,"dict((k, int(v)) for k, v in (e.split(' - ') for e in s.split(',')))"
Convert generator object to a dictionary,"dict((i, i * 2) for i in range(10))"
convert string to dict using list comprehension in python,dict([x.split('=') for x in s.split()])
Python: elegant way of creating a list of tuples?,"[(x + tuple(y)) for x, y in zip(zip(a, b), c)]"
python - replace the boolean value of a list with the values from two different lists,"['BMW', 'VW', 'b', 'Volvo', 'c']"
Convert generator object to a dictionary,{i: (i * 2) for i in range(10)}
Python pandas: replace values multiple columns matching multiple columns from another dataframe,"df2.rename(columns={'OCHR': 'chr', 'OSTOP': 'pos'}, inplace=True)"
How to find overlapping matches with a regexp?,"re.findall('(?=(\\w\\w))', 'hello')"
Python datetime to microtime,time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0
Replace one item in a string with one item from a list,"list(replace([1, 2, 3, 2, 2, 3, 1, 2, 4, 2], to_replace=2, fill='apple'))"
Pandas changing cell values based on another cell,df.loc[df['column_name'].isin(b)]
Problems trying to format currency with Python (Django),"locale.setlocale(locale.LC_ALL, '')"
How to create a list from another list using specific criteria in Python?,print([i.split('/')[1] for i in input if '/' in i])
Python: How to convert a string containing hex bytes to a hex string,binascii.a2b_hex(s)
How to use variables in SQL statement in Python?,"cursor.execute('INSERT INTO table VALUES (?, ?, ?)', (var1, var2, var3))"
Pythonic way to insert every 2 elements in a string,"s[::2], s[1::2]"
How to print a unicode string in python in Windows console,print('\u5f15\u8d77\u7684\u6216')
python comprehension loop for dictionary,sum(item['one'] for item in list(tadas.values()))
How to plot with x-axis at the top of the figure?,plt.show()
How to replace the white space in a string in a pandas dataframe?,"df.replace(' ', '_', regex=True)"
How to subtract two lists in python,"[(x1 - x2) for x1, x2 in zip(List1, List2)]"
Python : how to append new elements in a list of list?,[[] for i in range(3)]
re.split with spaces in python,"re.findall('\\s+|\\S+', s)"
Sort a list in python based on another sorted list,"sorted(unsorted_list, key=lambda x: order.get(x, -1))"
Reverse indices of a sorted list,"sorted(x[::-1] for x in enumerate(['z', 'a', 'c', 'x', 'm']))"
What is the best way to remove a dictionary item by value in python?,"myDict = {key: val for key, val in list(myDict.items()) if val != 42}"
How do you split a list into evenly sized chunks?,"[l[i:i + n] for i in range(0, len(l), n)]"
BeautifulSoup - search by text inside a tag,"soup.find_all('a', string='Elsie')"
Is it possible to call a Python module from ObjC?,print(urllib.request.urlopen('http://google.com').read())
Numpy: Find column index for element on each row,"array([0, 1, 2, 3], dtype=int64), array([1, 0, 1, 2], dtype=int64)"
How to sort a dataFrame in python pandas by two or more columns?,"df.sort_values(['a', 'b'], ascending=[True, False])"
Get values from matplotlib AxesSubplot,plt.show()
Implementing Google's DiffMatchPatch API for Python 2/3,"[(-1, 'stackoverflow'), (1, 'so'), (0, ' is '), (-1, 'very'), (0, ' cool')]"
How do i add two lists' elements into one list?,"list3 = [(a + b) for a, b in zip(list1, list2)]"
is it possible to plot timelines with matplotlib?,ax.xaxis.set_ticks_position('bottom')