text
stringlengths
4
1.08k
Convert DataFrame column type from string to datetime,df['col'] = pd.to_datetime(df['col'])
Can a list of all member-dict keys be created from a dict of dicts using a list comprehension?,[k for d in list(foo.values()) for k in d]
Possible to get user input without inserting a new line?,"print('Hello, {0}, how do you do?'.format(input('Enter name here: ')))"
Create Pandas DataFrame from txt file with specific pattern,"df = pd.read_csv('filename.txt', sep=';', names=['Region Name'])"
Pandas: How can I use the apply() function for a single column?,df['a'] = df['a'].apply(lambda x: x + 1)
How to check whether the system is FreeBSD in a python script?,platform.system()
How to sort python list of strings of numbers,"a = sorted(a, key=lambda x: float(x))"
Finding words after keyword in python,"re.search('name (.*)', s)"
Removing _id element from Pymongo results,"db.collection.find({}, {'_id': False})"
How do you extract a column from a multi-dimensional array?,[row[1] for row in A]
How do you extract a column from a multi-dimensional array?,[row[0] for row in a]
Python - how to sort a list of numerical values in ascending order,"sorted(['10', '3', '2'], key=int)"
How can I tell if a file is a descendant of a given directory?,"os.path.commonprefix(['/the/dir/', os.path.realpath(filename)]) == '/the/dir/'"
Python: How to check a string for substrings from a list?,any(substring in string for substring in substring_list)
Construct pandas DataFrame from list of tuples,"df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])"
How to find and replace nth occurence of word in a sentence using python regular expression?,"re.sub('^((?:(?!cat).)*cat(?:(?!cat).)*)cat', '\\1Bull', s)"
How to find and replace nth occurence of word in a sentence using python regular expression?,"re.sub('^((.*?cat.*?){1})cat', '\\1Bull', s)"
Sort list of strings by integer suffix in python,"sorted(the_list, key=lambda k: int(k.split('_')[1]))"
Sort list of strings by integer suffix in python,"sorted(the_list, key=lambda x: int(x.split('_')[1]))"
How to group similar items in a list?,"[list(g) for _, g in itertools.groupby(test, lambda x: x.split('_')[0])]"
How to group similar items in a list?,"[list(g) for _, g in itertools.groupby(test, lambda x: x.partition('_')[0])]"
How do I use the HTMLUnit driver with Selenium from Python?,driver.get('http://www.google.com')
"Using Python's datetime module, can I get the year that UTC-11 is currently in?",(datetime.datetime.utcnow() - datetime.timedelta(hours=11)).year
How to find the difference between 3 lists that may have duplicate numbers,"Counter([1, 2, 2, 2, 3]) - Counter([1, 2])"
How to remove tags from a string in python using regular expressions? (NOT in HTML),"re.sub('<[^>]*>', '', mystring)"
How can I unpack binary hex formatted data in Python?,data.encode('hex')
How to do a less than or equal to filter in Django queryset?,User.objects.filter(userprofile__level__gte=0)
How to use Beautiful Soup to find a tag with changing id?,soup.findAll(id=re.compile('para$'))
How to use Beautiful Soup to find a tag with changing id?,"soup.select('div[id^=""value_xxx_c_1_f_8_a_""]')"
How to delete an item in a list if it exists?,cleaned_list = [x for x in some_list if x is not thing]
user input and commandline arguments,var = input('Please enter something: ')
Add to integers in a list,foo.append(4)
Add to integers in a list,"foo.append([8, 7])"
Add to integers in a list,"x.insert(2, 77)"
Removing white space around a saved image in matplotlib,"plt.savefig('test.png', bbox_inches='tight')"
concatenate lists,(listone + listtwo)
concatenate lists,"for item in itertools.chain(listone, listtwo):
pass"
how do you filter pandas dataframes by multiple columns,males = df[(df[Gender] == 'Male') & (df[Year] == 2014)]
How to print backslash with Python?,print('\\')
How to replace values with None in Pandas data frame in Python?,"df.replace('-', np.nan)"
Delete column from pandas DataFrame,"df = df.drop('column_name', 1)"
Delete column from pandas DataFrame,"df.drop(df.columns[[0, 1, 3]], axis=1)"
Delete column from pandas DataFrame,"df.drop('column_name', axis=1, inplace=True)"
Disable abbreviation in argparse,parser = argparse.ArgumentParser(allow_abbrev=False)
Extract dictionary value from column in data frame,feature3 = [d.get('Feature3') for d in df.dic]
How to access pandas groupby dataframe by key,"df.loc[gb.groups['foo'], ('A', 'B')]"
String formatting in Python,"print('[%s, %s, %s]' % (1, 2, 3))"
String formatting in Python,"print('[{0}, {1}, {2}]'.format(1, 2, 3))"
Accessing Python dict values with the key start characters,"[v for k, v in list(my_dict.items()) if 'Date' in k]"
Python date string formatting,"""""""{0.month}/{0.day}/{0.year}"""""".format(my_date)"
Dropping a single (sub-) column from a MultiIndex,"df.drop(('col1', 'a'), axis=1)"
Dropping a single (sub-) column from a MultiIndex,"df.drop('a', level=1, axis=1)"
Build Dictionary in Python Loop - List and Dictionary Comprehensions,{_key: _value(_key) for _key in _container}
How to click on the text button using selenium python,browser.find_element_by_class_name('section-select-all').click()
"Python - Combine two dictionaries, concatenate string values?","dict((k, d.get(k, '') + d1.get(k, '')) for k in keys)"
How to generate unique equal hash for equal dictionaries?,hash(pformat(a)) == hash(pformat(b))
How to convert nested list of lists into a list of tuples in python 3.3?,"list(map(tuple, [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]))"
Summing across rows of Pandas Dataframe,"df.groupby(['stock', 'same1', 'same2'], as_index=False)['positions'].sum()"
Summing across rows of Pandas Dataframe,"df.groupby(['stock', 'same1', 'same2'])['positions'].sum().reset_index()"
change a string into uppercase,s.upper()
"Splitting a semicolon-separated string to a dictionary, in Python",dict(item.split('=') for item in s.split(';'))
how to set cookie in python mechanize,"br.addheaders = [('Cookie', 'cookiename=cookie value')]"
How to remove square bracket from pandas dataframe,df['value'] = df['value'].str[0]
How to remove square bracket from pandas dataframe,df['value'] = df['value'].str.get(0)
How to remove square bracket from pandas dataframe,df['value'] = df['value'].str.strip('[]')
Python getting a string (key + value) from Python Dictionary,""""""", """""".join(['{}_{}'.format(k, v) for k, v in d.items()])"
Easier way to add multiple list items?,sum(sum(x) for x in lists)
testing whether a Numpy array contains a given row,"any(np.equal(a, [1, 2]).all(1))"
How do I check if all elements in a list are the same?,len(set(mylist)) == 1
How to split a string at line breaks in python?,"[map(int, x.split('\t')) for x in s.rstrip().split('\r\n')]"
Create a hierarchy from a dictionary of lists,"t = sorted(list(a.items()), key=lambda x: x[1])"
Search for string in txt file,"if ('blabla' in open('example.txt').read()):
pass"
Replacing the empty strings in a string,"string2.replace('', string1)[len(string1):-len(string1)]"
getting every possible combination in a list,"list(itertools.combinations([1, 2, 3, 4, 5, 6], 2))"
Python 3: How do I get a string literal representation of a byte string?,"""""""x = {}"""""".format(x.decode('utf8')).encode('utf8')"
Checking whether a variable is an integer,"isinstance(x, int)"
Checking whether a variable is an integer,(type(x) == int)
Play a Sound with Python,"winsound.PlaySound('sound.wav', winsound.SND_FILENAME)"
How to get the n next values of a generator in a list (python),[next(it) for _ in range(n)]
How to get the n next values of a generator in a list (python),"list(itertools.islice(it, 0, n, 1))"
How can I compare two lists in python and return matches,set(a).intersection(b)
How can I compare two lists in python and return matches,"[i for i, j in zip(a, b) if i == j]"
"How to print a list with integers without the brackets, commas and no quotes?","print(''.join(map(str, data)))"
python regex: match a string with only one instance of a character,"re.match('\\$[0-9]+[^\\$]*$', '$1 off delicious $5 ham.')"
How to import a module in Python with importlib.import_module,"importlib.import_module('.c', 'a.b')"
How to import a module in Python with importlib.import_module,importlib.import_module('a.b.c')
how to convert 2d list to 2d numpy array?,a = np.array(a)
Python regular expression for Beautiful Soup,"soup.find_all('div', class_=re.compile('comment-'))"
A sequence of empty lists of length n in Python?,[[] for _ in range(n)]
create dictionary from list of variables,"dict((k, globals()[k]) for k in ('foo', 'bar'))"
How to get two random records with Django,MyModel.objects.order_by('?')[:2]
How to use a dot in Python format strings?,"""""""Hello {user[name]}"""""".format(**{'user': {'name': 'Markus'}})"
Python: using a dict to speed sorting of a list of tuples,list_dict = {t[0]: t for t in tuple_list}
Generate random integers between 0 and 9,"randint(0, 9)"
Generate random integers between 0 and 9,"random.randint(a, b)"
Generate random integers between 0 and 9,"print((random.randint(0, 9)))"
Reverse a string in Python two characters at a time (Network byte order),""""""""""""".join(reversed([a[i:i + 2] for i in range(0, len(a), 2)]))"
How to transform a time series pandas dataframe using the index attributes?,"pd.pivot_table(df, index=df.index.date, columns=df.index.time, values='Close')"