text
stringlengths
4
1.08k
remove word characters in parenthesis from string `item` with a regex,"item = re.sub(' ?\\(\\w+\\)', '', item)"
multiple linear regression with python,"x = np.array([[1, 2, 3, 4, 5], [4, 5, 6, 7, 8]], np.int32)"
concatenate a series `students` onto a dataframe `marks` with pandas,"pd.concat([students, pd.DataFrame(marks)], axis=1)"
automate png formatting with python,img.save('titled_plot.png')
sort list `the_list` by the length of string followed by alphabetical order,"the_list.sort(key=lambda item: (-len(item), item))"
how can i capture return value with python timeit module?,time.sleep(1)
get the first element of each tuple in a list in python,res_list = [x[0] for x in rows]
python: how to sort lists alphabetically with respect to capitalized letters,"sorted(lst, key=lambda L: (L.lower(), L))"
call a method of an object with arguments in python,"getattr(o, 'A')(1)"
accessing elements of python dictionary,dict['Apple']['American']
how to receive json data using http post request in django 1.6?,received_json_data = json.loads(request.body.decode('utf-8'))
remove all duplicate items from a list `lseperatedorblist`,woduplicates = list(set(lseperatedOrblist))
pandas scatter plotting datetime,"df.plot(x=x, y=y, style='.')"
list of strings to integers while keeping a format in python,integers = [(int(i) - 1) for i in line.split()]
how to remove empty string in a list?,cleaned = [x for x in your_list if x]
"sort list `['10', '3', '2']` in ascending order based on the integer value of its elements","sorted(['10', '3', '2'], key=int)"
inverse of a matrix in sympy?,"M = Matrix(2, 3, [1, 2, 3, 4, 5, 6])"
writing hex data into a file,fout.write(binascii.unhexlify(''.join(line.split())))
sscanf in python,"print((a, b, c, d))"
python: how to remove a list containing nones from a list of lists?,"[[3, 4, None, None, None]]"
how to reset index in a pandas data frame?,df = df.reset_index(drop=True)
set the value in column 'b' to nan if the corresponding value in column 'a' is equal to 0 in pandas dataframe `df`,"df.ix[df.A == 0, 'B'] = np.nan"
selenium webdriver - nosuchelementexceptions,driver.switch_to_frame('frameName')
how to count number of rows in a group in pandas group by object?,"df[['col3', 'col4', 'col5', 'col6']].astype(float)"
flask: how to remove cookies?,"resp.set_cookie('sessionID', '', expires=0)"
filtering pandas dataframes on dates,df.ix['2014-01-01':'2014-02-01']
convert scientific notation of variable `a` to decimal,"""""""{:.50f}"""""".format(float(a[0] / a[1]))"
find the index of element closest to number 11.5 in list `a`,"min(enumerate(a), key=lambda x: abs(x[1] - 11.5))"
logoff computer having windows operating system using python,"subprocess.call(['shutdown', '/l '])"
how can i insert data into a mysql database?,db.rollback()
how to create a huge sparse matrix in scipy,np.int32(np.int64(3289288566))
how to multiply all integers inside list,"l = map(lambda x: x * 2, l)"
change a string of integers separated by spaces to a list of int,x = [int(i) for i in x.split()]
sorting in python - how to sort a list containing alphanumeric values?,list1.sort(key=convert)
"print a string `s` by splitting with comma `,`","print(s.split(','))"
"split string `str` with delimiter '; ' or delimiter ', '","re.split('; |, ', str)"
get all `a` tags where the text starts with value `some text` using regex,"doc.xpath(""//a[starts-with(text(),'some text')]"")"
convert dictionaries into string python,""""""", """""".join([(str(k) + ' ' + str(v)) for k, v in list(a.items())])"
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')"
python: how to round 123 to 100 instead of 100.0?,"int(round(123, -2))"
how to rotate a video with opencv,cv.WaitKey(0)
return dataframe `df` with last row dropped,df.ix[:-1]
join float list into space-separated string in python,"print(''.join(format(x, '10.3f') for x in a))"
how to modify css by class name in selenium,"driver.execute_script(""arguments[0].style.border = '1px solid red';"")"
proper way to store guid in sqlite,"c.execute('CREATE TABLE test (guid GUID PRIMARY KEY, name TEXT)')"
to replace but the last occurrence of string in a text,"re.sub(' and (?=.* and )', ', ', str)"
pandas: how to change all the values of a column?,df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
python: unescape special characters without splitting data,""""""""""""".join(['I ', '<', '3s U ', '&', ' you luvz me'])"
is there a way to get a list of column names in sqlite?,"names = list(map(lambda x: x[0], cursor.description))"
how to download a file via ftp with python ftplib,"ftp.retrbinary('RETR %s' % filename, file.write)"
join float list into space-separated string in python,print(' '.join([str(i) for i in a]))
get line count of file 'myfile.txt',sum((1 for line in open('myfile.txt')))
format number 1000000000.0 using latex notation,print('\\num{{{0:.2g}}}'.format(1000000000.0))
get list of sums of neighboring integers in string `example`,"[sum(map(int, s)) for s in example.split()]"
"pythonic way to fetch all elements in a dictionary, falling between two keys?","{key: val for key, val in parent_dict.items() if 2 < key < 4}"
retrieving contents from a directory on a network drive (windows),os.listdir('\\networkshares\\folder1\\folder2\\folder3')
python: check if a string contains chinese character?,"print(re.findall('[\u4e00-\u9fff]+', ipath))"
multiplying values from two different dictionaries together in python,"{k: (v * dict2[k]) for k, v in list(dict1.items()) if k in dict2}"
efficient way to round to arbitrary precision in python,round(number * 2) / 2.0
efficient serialization of numpy boolean arrays,"numpy.array(b).reshape(5, 5)"
what's the difference between a python module and a python package?,import my_module
find the current directory,os.path.realpath(__file__)
how to display an image using kivy,return Image(source='b1.png')
python/matplotlib - is there a way to make a discontinuous axis?,ax.set_xscale('custom')
parse string `datestr` into a datetime object using format pattern '%y-%m-%d',"dateobj = datetime.datetime.strptime(datestr, '%Y-%m-%d').date()"
is there a cake equivalent for python?,print('Executing task {0}.'.format(sys.argv[1]))
change directory to the directory of a python script,os.chdir(os.path.dirname(__file__))
make a dictionary in python from input values,"{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}"
how to send email attachments with python,msg.attach(MIMEText(text))
"saving dictionary whose keys are tuples with json, python","json.dumps({str(k): v for k, v in list(data.items())})"
find a max value of the key `count` in a nested dictionary `d`,"max(d, key=lambda x: d[x]['count'])"
how to tell if string starts with a number?,string[0].isdigit()
insert directory 'libs' at the 0th index of current directory,"sys.path.insert(0, 'libs')"
text with unicode escape sequences to unicode in python,print('test \\u0259'.decode('unicode-escape'))
is it possible to have multiple statements in a python lambda expression?,"map(lambda x: heapq.nsmallest(x, 2)[1], list_of_lists)"
how do i remove the background from this kind of image?,"plt.imsave('girl_2.png', img_a)"
setting the size of the plotting canvas in matplotlib,"plt.savefig('D:\\mpl_logo_with_title.png', dpi=dpi)"
"remove characters ""!@#$"" from a string `line`","line = re.sub('[!@#$]', '', line)"
convert a string literal `s` with values `\\` to raw string literal,"s = s.replace('\\', '\\\\')"
creating a matplotlib scatter legend size related,plt.show()
"concat each values in a tuple `(34.2424, -64.2344, 76.3534, 45.2344)` to get a string",""""""""""""".join(str(i) for i in (34.2424, -64.2344, 76.3534, 45.2344))"
create list `c` containing items from list `b` whose index is in list `index`,c = [b[i] for i in index]
specify multiple positional arguments with argparse,"parser.add_argument('input', nargs='+')"
iterate over a dictionary `foo` in sorted order,"for (k, v) in sorted(foo.items()):
pass"
how can i compare two lists in python and return matches,"[i for i, j in zip(a, b) if i == j]"
convert list of ints to one number?,return int(''.join([('%d' % x) for x in numbers]))
check if all values in the columns of a numpy matrix `a` are same,"np.all(a == a[(0), :], axis=0)"
how can i apply a namedtuple onto a function?,func(*r)
add missing date index in dataframe,df.to_csv('test.csv')
python split string based on regular expression,str1.split()
get the average of a list values for each key in dictionary `d`),"[(i, sum(j) / len(j)) for i, j in list(d.items())]"
sum values greater than 0 in dictionary `d`,sum(v for v in list(d.values()) if v > 0)
python seaborn matplotlib setting line style as legend,plt.show()
convert a string to datetime object in python,"dateobj = datetime.datetime.strptime(datestr, '%Y-%m-%d').date()"
how to use regex with multiple data formats,"""""""\\bCVE-\\d+(?:-\\d+)?"""""""
writing utf-8 string to mysql with python,"conn = MySQLdb.connect(charset='utf8', init_command='SET NAMES UTF8')"
get index values of pandas dataframe as list?,df.index.values.tolist()
remove the last element in list `a`,a.pop()
how to retrieve only arabic texts from a string using regular expression?,"print(re.findall('[u0600-u06FF]+', my_string))"