text
stringlengths
4
1.08k
Is there any lib for python that will get me the synonyms of a word?,"['great', 'satisfying', 'exceptional', 'positive', 'acceptable']"
Python Pandas : How to skip columns when reading a file?,"a = pd.read_table('file', header=None, sep=' ', usecols=list(range(8)))"
Parse a tuple from a string?,"new_tuple = tuple('(1,2,3,4,5)'[1:-1].split(','))"
Python: converting a list of dictionaries to json,json.dumps(list)
How to dynamically load a Python class,my_import('foo.bar.baz.qux')
"Is there a matplotlib counterpart of Matlab ""stem3""?",plt.show()
Telling Python to save a .txt file to a certain directory on Windows and Mac,"os.path.join(os.path.expanduser('~'), 'Documents', completeName)"
Plot image color histogram using matplotlib,plt.show()
Replace with newline python,"print(a.replace('>', '> \n'))"
How to use sadd with multiple elements in Redis using Python API?,"r.sadd('a', 1, 2, 3)"
How to fetch only specific columns of a table in django?,"Entry.objects.values_list('id', 'headline')"
JSON->String in python,print(result[0]['status'])
Technique to remove common words(and their plural versions) from a string,"['long', 'string', 'text']"
how to sort a scipy array with order attribute when it does not have the field names?,"np.argsort(y, order=('x', 'y'))"
How to remove duplicates from Python list and keep order?,myList = sorted(set(myList))
Assigning a value to an element of a slice in Python,a[0:1][0][0] = 5
Create new columns in pandas from python nested lists,"df.A.apply(lambda x: pd.Series(1, x)).fillna(0).astype(int)"
zip lists in python,"zip(a, b, c)"
What's the proper way to write comparator as key in Python 3 for sorting?,"print(sorted(l, key=lambda x: x))"
How to split an array according to a condition in numpy?,"[array([[1, 2, 3], [2, 4, 7]]), array([[4, 5, 6], [7, 8, 9]])]"
gnuplot linecolor variable in matplotlib?,"plt.scatter(list(range(len(y))), y, c=z, cmap=cm.hot)"
Finding consecutive consonants in a word,"re.findall('[bcdfghjklmnpqrstvwxyz]+', 'concertation', re.IGNORECASE)"
how to use .get() in a nested dict?,"b.get('x', {}).get('y', {}).get('z')"
How to obtain values of parameters of get request in flask?,app.run(debug=True)
How to normalize by another row in a pandas DataFrame?,"df.loc[ii, cols]"
How can I compare a unicode type to a string in python?,'MyString' == 'MyString'
How do I access a object's method when the method's name is in a variable?,"getattr(test, method)()"
Trying to plot temperature,plt.show()
Exponential curve fitting in SciPy,np.exp(-x)
How to deal with certificates using Selenium?,driver.get('https://cacert.org/')
pandas unique values multiple columns,"pandas.concat([df['a'], df['b']]).unique()"
Getting an element from tuple of tuples in python,[x for x in COUNTRIES if x[0] == 'AS'][0][1]
How do I check if a string is valid JSON in Python?,print(json.dumps(foo))
How can I process a python dictionary with callables?,"{k: (v() if callable(v) else v) for k, v in a.items()}"
Python Pandas - Removing Rows From A DataFrame Based on a Previously Obtained Subset,grouped = df.groupby(df['zip'].isin(keep))
Reshape pandas dataframe from rows to columns,df2.groupby('Name').apply(tgrp).unstack()
Mask out specific values from an array,"np.in1d(a, [2, 3]).reshape(a.shape)"
Persistent Terminal Session in Python,"subprocess.call(['/bin/bash', '-c', '/bin/echo $HOME'])"
How do I remove rows from a dataframe?,df.drop(x[x].index)
Python: Compare a list to a integer,"int(''.join(your_list), 16)"
How can I filter for string values in a mixed datatype object in Python Pandas Dataframe,df['Admission_Source_Code'] = [str(i) for i in df['Admission_Source_Code']]
How do I change the representation of a Python function?,hehe()
Python MySQL CSV export to json strange encoding,data.to_csv('path_with_file_name')
How do I use a dictionary to update fields in Django models?,Book.objects.create(**d)
Remove lines in dataframe using a list in Pandas,df.query('field not in @ban_field')
Python . How to get rid of '\r' in string?,open('test_newlines.txt').read().split()
"dropping rows from dataframe based on a ""not in"" condtion",df = df[~df.datecolumn.isin(a)]
How to remove more than one space when reading text file,"reader = csv.reader(f, delimiter=' ', skipinitialspace=True)"
"How do I modify a single character in a string, in Python?",a = list('hello')
Python Accessing Values in A List of Dictionaries,print('\n'.join(d['Name'] for d in thisismylist))
Python with matplotlib - reusing drawing functions,plt.show()
Prevent anti-aliasing for imshow in matplotlib,"imshow(array, interpolation='nearest')"
How do I find the distance between two points?,"dist = math.hypot(x2 - x1, y2 - y1)"
count number of events in an array python,"1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0"
sorting a list in python,"sorted([-5, 2, 1, -8], key=abs)"
Selenium PhantomJS custom headers in Python,driver.get('http://cn.bing.com')
Sort a sublist of elements in a list leaving the rest in place,"s1 = ['11', '2', 'A', 'B', 'B1', 'B11', 'B2', 'B21', 'C', 'C11', 'C2']"
"Pandas crosstab, but with values from aggregation of third column","df.pivot_table(index='A', columns='B', values='C', fill_value=0)"
How can I determine the byte length of a utf-8 encoded string in Python?,len(s.encode('utf-8'))
Merge DataFrames in Pandas using the mean,"pd.merge(df1, df2, left_index=True, right_index=True, how='outer').mean(axis=1)"
How can I import a python module function dynamically?,"my_function = getattr(__import__('my_apps.views'), 'my_function')"
Flattening a list of NumPy arrays?,out = np.concatenate(input_list).ravel().tolist()
Count occurrence of a character in a string,"""""""Mary had a little lamb"""""".count('a')"
Python Interpolation with matplotlib/basemap,plt.show()
Set default directory of Pydev interactive console?,sys.path.append('F:\\projects\\python')
Find the indices of elements greater than x,"[(i, j) for i, j in zip(a, x) if i >= 4]"
"python - Using argparse, pass an arbitrary string as an argument to be used in the script","parser.add_argument('-a', action='store_true')"
Changing the text on a label,self.depositLabel['text'] = 'change the value'
Write data to a file in Python,f.write(str(yEst) + '\n')
How to limit the range of the x-axis with imshow()?,"ax1.set_xticks([int(j) for j in range(-4, 5)])"
"SyntaxError: invalid token in datetime.datetime(2012,05,22,09,03,41)?","datetime.datetime(2012, 5, 22, 9, 3, 41)"
How can I compare a date and a datetime in Python?,"datetime.datetime(d.year, d.month, d.day)"
How to delete a character from a string using python?,s = s[:pos] + s[pos + 1:]
Replace exact substring in python,"re.sub('\\bin\\b', '', 'office administration in delhi')"
Create multiple columns in pandas aggregation function,"ts.resample('30Min', how=mhl)"
How to print negative zero in Python,"print(('%.0f\xb0%.0f\'%.0f""' % (deg, fabs(min), fabs(sec))).encode('utf-8'))"
how to convert a list into a pandas dataframe,"df = pd.DataFrame({'col1': x, 'col2': y, 'col3': z})"
How can I find a process by name and kill using ctypes?,subprocess.call('taskkill /IM exename.exe')
sort values and return list of keys from dict python,"sorted(d, key=d.get)"
Python remove anything that is not a letter or number,"re.sub('\\W', '', 'text 1, 2, 3...')"
How to get the cumulative sum of numpy array in-place,"np.cumsum(a, axis=1, out=a)"
Putting a variable inside a string (python),plot.savefig('hanning%(num)s.pdf' % locals())
Returning NotImplemented from __eq__,raise TypeError('sth')
Regular Expression to match a dot,"re.findall('(\\w+[.]\\w+)@', s)"
How to sort list of lists according to length of sublists,"sorted(a, key=len)"
Merge DataFrames in Pandas using the mean,"pd.concat((df1, df2), axis=1)"
Check if dictionary key is filled with list of 2 numbers,"len(d[obj]) == 2 and isinstance(d[obj][0], int) and isinstance(d[obj][1], int)"
Pythonic way to create a long multi-line string,s = 'this is a verylong string toofor sure ...'
how to make subprocess called with call/Popen inherit environment variables,subprocess.check_output(['newscript.sh'])
How to build and fill pandas dataframe from for loop?,"pd.DataFrame(d, columns=('Player', 'Team', 'Passer Rating'))"
Run a python script with arguments,"mrsync.sync('/tmp/targets.list', '/tmp/sourcedata', '/tmp/targetdata')"
How to sort the letters in a string alphabetically in Python,""""""""""""".join(sorted(a))"
How do I get the filepath for a class in Python?,inspect.getfile(C.__class__)
Convert decimal to binary in python,"""""""{0:#b}"""""".format(my_int)"
Finding the most popular words in a list,"[('all', 3), ('yeah', 2), ('bye', 1), ('awesome', 1)]"
"Determine if 2 lists have the same elements, regardless of order?",sorted(x) == sorted(y)
"Regex in Python to find words that follow pattern: vowel, consonant, vowel, consonant","""""""([bcdfghjklmnpqrstvwxz][aeiou])+"""""""
"Regex in Python to find words that follow pattern: vowel, consonant, vowel, consonant","""""""([aeiou]+[bcdfghjklmnpqrstvwxz]+)+"""""""
Python How to use extended path length,'\\\\?\\' + os.path.abspath(file_name)
How can I compare a date and a datetime in Python?,"from_date = from_date.replace(hour=0, minute=0, second=0, microsecond=0)"