text stringlengths 4 1.08k |
|---|
pandas split string into columns,"df['stats'].str[1:-1].str.split(',').apply(pd.Series).astype(float)" |
pandas split string into columns,df['stats'].apply(pd.Series) |
wait for shell command to complete,p.wait() |
Unescaping escaped characters in a string using Python 3.2,s.encode('utf8') |
Parse a string with a date to a datetime object,"datetime.datetime.strptime('01-Jan-1995', '%d-%b-%Y')" |
copy a file,"copyfile(src, dst)" |
copy a file,"shutil.copy2('/dir/file.ext', '/new/dir/newname.ext')" |
copy a file,"shutil.copy2('/dir/file.ext', '/new/dir')" |
Joining a list that has Integer values with Python,"print(', '.join(str(x) for x in list_of_ints))" |
how to multiply multiple columns by a column in Pandas,"df[['A', 'B']].multiply(df['C'], axis='index')" |
convert string to hex in python,hex(ord('a')) |
How to sum the values of list to the power of their indices,"sum(j ** i for i, j in enumerate(l, 1))" |
Python/Django: How to remove extra white spaces & tabs from a string?,""""""" """""".join(s.split())" |
How to strip comma in Python string,"s = s.replace(',', '')" |
How to resample a dataframe with different functions applied to each column?,"frame.resample('1H').agg({'radiation': np.sum, 'tamb': np.mean})" |
How do I get rid of Python Tkinter root window?,root.destroy() |
Creating a Pandas dataframe from elements of a dictionary,"df = pd.DataFrame.from_dict({k: v for k, v in list(nvalues.items()) if k != 'y3'})" |
How to obtain values of request variables using Python and Flask,first_name = request.args.get('firstname') |
How to obtain values of request variables using Python and Flask,first_name = request.form.get('firstname') |
How to read only part of a list of strings in python,[s[:5] for s in buckets] |
how to sort by length of string followed by alphabetical order?,"the_list.sort(key=lambda item: (-len(item), item))" |
how to slice a dataframe having date field as index?,df = df.set_index(['TRX_DATE']) |
List comprehension with an accumulator,list(accumulate(list(range(10)))) |
How to convert a date string to different format,"datetime.datetime.strptime('2013-1-25', '%Y-%m-%d').strftime('%m/%d/%y')" |
How to convert a date string to different format,"datetime.datetime.strptime('2013-1-25', '%Y-%m-%d').strftime('%-m/%d/%y')" |
How to remove multiple columns that end with same text in Pandas?,"df2 = df.ix[:, (~df.columns.str.endswith('prefix'))]" |
Python - How to extract the last x elements from a list,new_list = my_list[-10:] |
Python - How to extract the last x elements from a list,my_list[-10:] |
How to efficiently convert Matlab engine arrays to numpy ndarray?,np.array(x._data).reshape(x.size[::-1]).T |
In pandas Dataframe with multiindex how can I filter by order?,"df.groupby(level=0, as_index=False).nth(0)" |
How to convert list of numpy arrays into single numpy array?,"numpy.concatenate(LIST, axis=0)" |
How can I convert literal escape sequences in a string to the corresponding bytes?,"""""""\\xc3\\x85あ"""""".encode('utf-8').decode('unicode_escape')" |
How can I convert literal escape sequences in a string to the corresponding bytes?,"""""""\\xc3\\x85あ"""""".encode('utf-8')" |
How do I merge two lists into a single list?,"[j for i in zip(a, b) for j in i]" |
How do I merge two lists into a single list?,"[j for i in zip(a, b) for j in i]" |
Removing character in list of strings,"print([s.replace('8', '') for s in lst])" |
How to split a word into letters in Python,""""""","""""".join('Hello')" |
"In Django, how do I select 100 random records from the database?",Content.objects.all().order_by('?')[:100] |
Indexing one array by another in numpy,"A[np.arange(A.shape[0])[:, (None)], B]" |
pandas pivot table of sales,"df.pivot_table(index='saleid', columns='upc', aggfunc='size', fill_value=0)" |
Confusing with the usage of regex in Python,"re.findall('([a-z]*)', 'f233op')" |
Confusing with the usage of regex in Python,"re.findall('([a-z])*', 'f233op')" |
Splitting a string based on a certain set of words,"re.split('_for_', 'happy_hats_for_cats')" |
Splitting a string based on a certain set of words,"re.split('_(?:for|or|and)_', 'sad_pandas_and_happy_cats_for_people')" |
Splitting a string based on a certain set of words,"[re.split('_(?:f?or|and)_', s) for s in l]" |
How do I zip keys with individual values in my lists in python?,"[dict(zip(k, x)) for x in v]" |
Python how to sort this list?,"sorted(lst, reverse=True)" |
Sorting numpy array on multiple columns in Python,"order_array.sort(order=['year', 'month', 'day'])" |
Sorting numpy array on multiple columns in Python,"df.sort(['year', 'month', 'day'])" |
Python: find out whether a list of integers is coherent,"return my_list == list(range(my_list[0], my_list[-1] + 1))" |
Concatenate rows of pandas DataFrame with same id,df.groupby('id').agg(lambda x: x.tolist()) |
Double-decoding unicode in python,'X\xc3\xbcY\xc3\x9f'.encode('raw_unicode_escape').decode('utf-8') |
Parse String to Float or Int,float(a) |
know if an object has an attribute,"if hasattr(a, 'property'): |
pass" |
know if an object has an attribute,"if hasattr(a, 'property'): |
pass" |
know if an object has an attribute,"getattr(a, 'property', 'default value')" |
delete every nth row or column in a matrix using Python,"np.delete(a, list(range(0, a.shape[1], 8)), axis=1)" |
How do I create a datetime in Python from milliseconds?,datetime.datetime.fromtimestamp(ms / 1000.0) |
fastest way to find the magnitude (length) squared of a vector field,"np.einsum('...j,...j->...', vf, vf)" |
Simple URL GET/POST function,r = requests.get(url) |
Simple URL GET/POST function,"r = requests.get(url, params=payload)" |
Simple URL GET/POST function,"r = requests.post(url, data=payload)" |
Simple URL GET/POST,"post_response = requests.post(url='http://httpbin.org/post', json=post_data)" |
Slicing a list in Django template,{{(mylist | slice): '3:8'}} |
pandas HDFStore - how to reopen?,"df1 = pd.read_hdf('/home/.../data.h5', 'firstSet')" |
find last occurence of multiple characters in a string in Python,max(test_string.rfind(i) for i in '([{') |
How to print Unicode character in Python?,print('here is your checkmark: ' + '\u2713') |
How to print Unicode character in Python?,print('\u0420\u043e\u0441\u0441\u0438\u044f') |
in python how do I convert a single digit number into a double digits string?,print('{0}'.format('5'.zfill(2))) |
Best / most pythonic way to get an ordered list of unique items,sorted(set(itertools.chain.from_iterable(sequences))) |
Pandas DataFrame to list,df['a'].values.tolist() |
Pandas DataFrame to list,df['a'].tolist() |
Escaping quotes in string,"replace('""', '\\""')" |
How to check if a character is upper-case in Python?,print(all(word[0].isupper() for word in words)) |
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}" |
What is the best way to remove a dictionary item by value in python?,"{key: val for key, val in list(myDict.items()) if val != 42}" |
How can I determine the byte length of a utf-8 encoded string in Python?,return len(s.encode('utf-8')) |
"In Python 2.5, how do I kill a subprocess?","os.kill(process.pid, signal.SIGKILL)" |
Python Pandas How to select rows with one or more nulls from a DataFrame without listing columns explicitly?,df[pd.isnull(df).any(axis=1)] |
Strip random characters from url,"url.split('&')[-1].replace('=', '') + '.html'" |
Expat parsing in python 3,"parser.ParseFile(open('sample.xml', 'rb'))" |
how do I halt execution in a python script?,sys.exit() |
How to dynamically assign values to class properties in Python?,"setattr(self, attr, group)" |
How to decode a 'url-encoded' string in python,urllib.parse.unquote(urllib.parse.unquote(some_string)) |
How to decode a 'url-encoded' string in python,urllib.parse.unquote(urllib.parse.unquote('FireShot3%2B%25282%2529.png')) |
How to use Flask-Security register view?,app.config['SECURITY_REGISTER_URL'] = '/create_account' |
IO Error while storing data in pickle,"output = open('/home/user/test/wsservice/data.pkl', 'wb')" |
remove an element from a list by index,del a[(-1)] |
remove an element from a list by index,a.pop(1) |
remove an element from a list by index,a.pop() |
remove an element from a list by index,a.pop(index) |
remove an element from a list by index,del a[index] |
How do I print a Celsius symbol with matplotlib?,ax.set_xlabel('Temperature (\u2103)') |
How do I print a Celsius symbol with matplotlib?,ax.set_xlabel('Temperature ($^\\circ$C)') |
'List of lists' to 'list' without losing empty lists from the original list of lists,[''.join(l) for l in list_of_lists] |
How do I get a list of all the duplicate items using pandas in python?,"pd.concat(g for _, g in df.groupby('ID') if len(g) > 1)" |
deleting rows in numpy array,"x = numpy.delete(x, 2, axis=1)" |
deleting rows in numpy array,"x = numpy.delete(x, 0, axis=0)" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.