text
stringlengths 4
1.08k
|
|---|
Pandas Data Frame Plotting,df.plot(title='Title Here')
|
Generate list of numbers in specific format,[('%.2d' % i) for i in range(16)]
|
Sorting numpy array on multiple columns in Python,"df.sort(['year', 'month', 'day'])"
|
How to change legend size with matplotlib.pyplot,"plot.legend(loc=2, prop={'size': 6})"
|
String formatting in Python,"""""""[{0}, {1}, {2}]"""""".format(1, 2, 3)"
|
How to obtain the day of the week in a 3 letter format from a datetime object in python?,datetime.datetime.now().strftime('%a')
|
How can I control the keyboard and mouse with Python?,"dogtail.rawinput.click(100, 100)"
|
How do I join two dataframes based on values in selected columns?,"pd.merge(a, b, on=['A', 'B'], how='outer')"
|
How to replace unicode characters in string with something else python?,"str.decode('utf-8').replace('\u2022', '*').encode('utf-8')"
|
Sorting dictionary keys based on their values,"sorted(d, key=lambda k: d[k][1])"
|
How to select only specific columns from a DataFrame with MultiIndex columns?,"data.loc[:, ([('one', 'a'), ('one', 'c'), ('two', 'a'), ('two', 'c')])]"
|
How to replace repeated instances of a character with a single instance of that character in python,"re.sub('\\*\\*+', '*', text)"
|
Combining rows in pandas,df.reset_index().groupby('city_id').sum()
|
Find an element in a list of tuples,[item for item in a if 1 in item]
|
Python: How to generate a 12-digit random number?,"'%0.12d' % random.randint(0, 999999999999)"
|
Django - Filter queryset by CharField value length,MyModel.objects.filter(text__regex='^.{254}.*')
|
change current working directory in python,os.chdir('.\\chapter3')
|
change current working directory in python,os.chdir('C:\\Users\\username\\Desktop\\headfirstpython\\chapter3')
|
Count number of rows in a many-to-many relationship (SQLAlchemy),session.query(Entry).join(Entry.tags).filter(Tag.id == 1).count()
|
login to a site using python and opening the login site in the browser,webbrowser.open('http://somesite.com/adminpanel/index.php')
|
Python: simplest way to get list of values from dict?,list(d.values())
|
How do I print a Celsius symbol with matplotlib?,ax.set_xlabel('Temperature ($^\\circ$C)')
|
Finding consecutive segments in a pandas data frame,"df.reset_index().groupby(['A', 'block'])['index'].apply(np.array)"
|
Accessing a value in a tuple that is in a list,[x[1] for x in L]
|
Regular expression to remove line breaks,"re.sub('(?<=[a-z])\\r?\\n', ' ', textblock)"
|
Normalizing a pandas DataFrame by row,"df.div(df.sum(axis=1), axis=0)"
|
Summing elements in a list,sum(your_list)
|
Lack of randomness in numpy.random,"x, y = np.random.randint(20, size=(2, 100)) + np.random.rand(2, 100)"
|
Python: How do I convert an array of strings to an array of numbers?,"map(int, ['1', '-1', '1'])"
|
Summing 2nd list items in a list of lists of lists,[sum([x[1] for x in i]) for i in data]
|
Python: get key of index in dictionary,"[k for k, v in i.items() if v == 0]"
|
Split dictionary of lists into list of dictionaries,"[{'key1': a, 'key2': b} for a, b in zip(d['key1'], d['key2'])]"
|
"Pandas read_csv expects wrong number of columns, with ragged csv file",pd.read_csv('D:/Temp/tt.csv')
|
How to keep a list of lists sorted as it is created,dataList.sort(key=lambda x: x[1])
|
Extracting only characters from a string in Python,"re.split('[^a-zA-Z]*', 'your string')"
|
Matplotlib.animation: how to remove white margin,"fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)"
|
Pandas DataFrame to list,df['a'].tolist()
|
"Python, print all floats to 2 decimal places in output","print('%.2f kg = %.2f lb = %.2f gal = %.2f l' % (var1, var2, var3, var4))"
|
How to produce an exponentially scaled axis?,plt.show()
|
How to order a list of lists by the first value,"sorted([[1, 'mike'], [1, 'bob']])"
|
How to input an integer tuple from user?,"tuple(int(x.strip()) for x in input().split(','))"
|
Remove duplicate chars using regex?,"re.sub('a*', 'a', 'aaabbbccc')"
|
Sorting a dictionary by a split key,"sorted(list(d.items()), key=lambda v: int(v[0].split('-')[0]))"
|
What's the shortest way to count the number of items in a generator/iterator?,sum(1 for i in it)
|
How can I turn a string into a list in Python?,list('hello')
|
How can I sum the product of two list items using for loop in python?,"sum(x * y for x, y in list(zip(a, b)))"
|
Printing numbers in python,print('%.3f' % 3.1415)
|
Sub matrix of a list of lists (without numpy),"[[2, 3, 4], [2, 3, 4], [2, 3, 4]]"
|
Python date string to date object,"datetime.datetime.strptime('24052010', '%d%m%Y').date()"
|
How can I call a python script from a python script,"p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr)"
|
How to set UTC offset for datetime?,dateutil.parser.parse('2013/09/11 00:17 +0900')
|
"python: dictionary to string, custom format?","""""""<br/>"""""".join([('%s:: %s' % (key, value)) for key, value in list(d.items())])"
|
Adding a new column in data frame after calculation on time,"df['period'] = df.apply(period, axis=1)"
|
How to get a list of variables in specific Python module?,print([item for item in dir(adfix) if not item.startswith('__')])
|
How can I scroll a web page using selenium webdriver in python?,"driver.execute_script('window.scrollTo(0, Y)')"
|
Take screenshot in Python on Mac OS X,os.system('screencapture screen.png')
|
Removing _id element from Pymongo results,"db.collection.find({}, {'_id': False})"
|
How can I return HTTP status code 204 from a Django view?,return HttpResponse(status=204)
|
Convert a row in pandas into list,"df.apply(lambda x: x.tolist(), axis=1)"
|
I'm looking for a pythonic way to insert a space before capital letters,"re.sub('(?<=\\w)([A-Z])', ' \\1', 'WordWordWWWWWWWord')"
|
How do I sort a list of strings in Python?,list.sort()
|
Create SVG / XML document without ns0 namespace using Python ElementTree,"etree.register_namespace('', 'http://www.w3.org/2000/svg')"
|
Delete row based on nulls in certain columns (pandas),"df.dropna(subset=['city', 'latitude', 'longitude'], how='all')"
|
how to slice a dataframe having date field as index?,df.index = pd.to_datetime(df['TRX_DATE'])
|
How to convert decimal to binary list in python,[int(x) for x in bin(8)[2:]]
|
How to find and replace nth occurence of word in a sentence using python regular expression?,"re.sub('^((.*?cat.*?){1})cat', '\\1Bull', s)"
|
How to find and replace nth occurence of word in a sentence using python regular expression?,"re.sub('^((?:(?!cat).)*cat(?:(?!cat).)*)cat', '\\1Bull', s)"
|
pandas create new column based on values from other columns,"df.apply(lambda row: label_race(row), axis=1)"
|
Python - How to cut a string in Python?,s[:s.rfind('&')]
|
How to display a pdf that has been downloaded in python,os.system('my_pdf.pdf')
|
sorting a list of tuples in Python,"sorted(list_of_tuples, key=lambda tup: tup[::-1])"
|
Finding consecutive segments in a pandas data frame,df.reset_index().groupby('A')['index'].apply(np.array)
|
How can I match the start and end in Python's regex?,"re.match('(ftp|http)://.*\\.(jpg|png)$', s)"
|
Select rows from a DataFrame based on values in a column in pandas,df.loc[df['column_name'].isin(some_values)]
|
Python - How to cut a string in Python?,s.rfind('&')
|
Pandas: How to plot a barchar with dataframes with labels?,"df.set_index(['timestamp', 'objectId'])['result'].unstack().plot(kind='bar')"
|
python: how to plot one line in different colors,plt.show()
|
How to convert list of intable strings to int,"[try_int(x) for x in ['sam', '1', 'dad', '21']]"
|
How to check if all elements of a list matches a condition?,[x for x in items if x[2] == 0]
|
Python - Extract folder path from file path,os.path.split(os.path.abspath(existGDBPath))
|
Pandas DataFrame to list,df['a'].values.tolist()
|
How to expand a string within a string in python?,"['yyya', 'yyyb', 'yyyc']"
|
Python re.findall print all patterns,"re.findall('(?=(a.*?a))', 'a 1 a 2 a 3 a 4 a')"
|
Python: Convert list of key-value tuples into dictionary?,"dict([('A', 1), ('B', 2), ('C', 3)])"
|
sorting list in python,l.sort(key=alphanum_key)
|
How to convert a tuple to a string in Python?,emaillist = '\n'.join([item[0] for item in queryresult])
|
Django database query: How to filter objects by date range?,"Sample.objects.filter(date__year='2011', date__month='01')"
|
Subtract values in one list from corresponding values in another list - Python,"C = [(a - b) for a, b in zip(A, B)]"
|
How do I sum values in a column that match a given condition using pandas?,"df.loc[df['a'] == 1, 'b'].sum()"
|
Converting from a string to boolean in Python?,"s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']"
|
String formatting in Python,"print('[%i, %i, %i]' % (1, 2, 3))"
|
Convert a list of characters into a string,""""""""""""".join(['a', 'b', 'c', 'd'])"
|
how can i check if a letter in a string is capitalized using python?,print(''.join(uppers))
|
IO Error while storing data in pickle,"output = open('/home/user/test/wsservice/data.pkl', 'wb')"
|
How to debug Celery/Django tasks running localy in Eclipse,CELERY_ALWAYS_EAGER = True
|
python selenium click nth element,browser.find_element_by_css_selector('ul...span.hover ').click()
|
sorting a list in python,"sorted(words, key=lambda x: 'a' + x if x[:1] == 's' else 'b' + x)"
|
python - iterating over a subset of a list of tuples,[x for x in l if x[1] == 1]
|
Python - Sort a list of dics by value of dict`s dict value,"sorted(persons, key=lambda x: x['passport']['birth_info']['date'])"
|
Fastest Way to Drop Duplicated Index in a Pandas DataFrame,df[~df.index.duplicated()]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.