text
stringlengths
4
1.08k
"Missing data, insert rows in Pandas and fill with NAN",df.set_index('A')
How do I fix a dimension error in TensorFlow?,"x_image = tf.reshape(tf_in, [-1, 2, 4, 1])"
Find maximum value of a column and return the corresponding row values using Pandas,"df.groupby(['country', 'place'], as_index=False)['value'].max()"
What is the most Pythonic way to test for match with first item of tuple in sequence of 2-tuples?,any(x[0] == 'a' for x in seq_of_tups)
How to remove two chars from the beginning of a line,[line[2:] for line in lines]
Expanding a block of numbers in Python,"L = ['1', '2', '3', '7-10', '15', '20-25']"
What's the difference between a Python module and a Python package?,import my_module
How to check if an element from List A is not present in List B in Python?,list([a for a in A if a not in B])
Returning the product of a list,"from functools import reduce
reduce(lambda x, y: x * y, list, 1)"
private members in python,"['_Test__private_symbol', '__doc__', '__module__', 'normal_symbol']"
How do I make a Django ModelForm menu item selected by default?,form = MyModelForm(initial={'gender': 'M'})
Python: How to get PID by process name?,get_pid('java')
How do you remove the column name row from a pandas DataFrame?,"df.to_csv('filename.csv', header=False)"
List Manipulation in Python with pop(),"newlist = [x for x in oldlist if x not in ['a', 'c']]"
Python max length of j-th item across sublists of a list,[max(len(b) for b in a) for a in zip(*x)]
What is a Pythonic way to alter a dict with a key and multiple values to get the desired output?,"[(10, 'India'), (12, 'USA'), (12, 'UK'), (11, 'Other')]"
How can I create a simple message box in Python?,"ctypes.windll.user32.MessageBoxW(0, 'Your text', 'Your title', 1)"
How to embed a Python interpreter in a PyQT widget,app.exec_()
"Python zlib output, how to recover out of mysql utf-8 table?",zlib.decompress(u.encode('latin1'))
A list of data structures in Python,"dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}"
how can i get the executable's current directory in py2exe?,os.path.realpath(os.path.dirname(sys.argv[0]))
using regular expression to split string in python,[match.group(0) for match in pattern.finditer('44442(2)2(2)44')]
"In Python, how can I find the index of the first item in a list that is NOT some value?","return next((i for i, v in enumerate(L) if v != x), -1)"
String of bytes into an int,"int(s.replace(' ', ''), 16)"
"Reversal of string.contains In python, pandas",df['A'].str.contains('^(?:(?!Hello|World).)*$')
How to unzip a list of tuples into individual lists?,zip(*l)
How to combine two list containing dictionary with similar keys?,"result = [{k: (d1[k] + d2[k]) for k in d1} for d1, d2 in zip(var1, var2)]"
First non-null value per row from a list of Pandas columns,df.stack().groupby(level=0).first().reindex(df.index)
Convert list of strings to dictionary,"{' Failures': 0, 'Tests run': 1, ' Errors': 0}"
Check if multiple rows exist in another dataframe,"pd.merge(df1, df2, indicator=True, how='outer')"
Multiple files for one argument in argparse Python 2.7,"parser.add_argument('file', type=argparse.FileType('r'), nargs='+')"
Regex to match space and a string until a forward slash,regexp = re.compile('^group/(?P<group>[^/]+)$')
Combining two Series into a DataFrame in pandas,"pd.concat([s1, s2], axis=1).reset_index()"
How can I capture all exceptions from a wxPython application?,app.MainLoop()
disabling autoescape in flask,app.run(debug=True)
Converting a list of strings in a numpy array in a faster way,"map(float, i.split()[:2])"
Python's ConfigParser unique keys per section,"[('spam', 'eggs'), ('spam', 'ham')]"
closing python comand subprocesses,os.system('fsutil file createnew r:\\dummy.txt 6553600')
How to create a function that outputs a matplotlib figure?,plt.figure().canvas.draw()
How do I merge two lists into a single list?,"[item for pair in zip(a, b) for item in pair]"
Reading a triangle of numbers into a 2d array of ints in Python,arr = [[int(i) for i in line.split()] for line in open('input.txt')]
Printing each item of a variable on a separate line in Python,"print('\n'.join(map(str, ports)))"
Python Pandas Group by date using datetime data,df = df.groupby([df['Date_Time'].dt.date]).mean()
How to create inline objects with properties in Python?,"obj = type('obj', (object,), {'propertyName': 'propertyValue'})"
How to make Matplotlib scatterplots transparent as a group?,fig.savefig('test_scatter.png')
Disable output of root logger,logging.getLogger().setLevel(logging.DEBUG)
Python: How can I run python functions in parallel?,p.start()
pandas unique values multiple columns,"pd.unique(df[['Col1', 'Col2']].values.ravel())"
pandas dataframe count row values,pd.DataFrame({name: df['path'].str.count(name) for name in wordlist})
How to remove item from a python list if a condition is True?,y = [s for s in x if len(s) == 2]
Sort at various levels in Python,"top_n.sort(key=lambda t: (-t[1], t[0]))"
Get a string after a specific substring,"print(my_string.split('world', 1)[1])"
Python Pandas - How to flatten a hierarchical index in columns,[' '.join(col).strip() for col in df.columns.values]
The most efficient way to remove first N elements in a Python List?,del mylist[:n]
How do I treat an ASCII string as unicode and unescape the escaped characters in it in python?,s.decode('unicode-escape').encode('ascii')
Extract Number from String - Python,int(str1.split()[0])
How do I select from multiple tables in one query with Django?,Employee.objects.select_related()
Python Check if all of the following items is in a list,"set(l).issuperset(set(['a', 'b']))"
Removing control characters from a string in python,return ''.join(c for c in line if ord(c) >= 32)
Downloading file to specified location with Selenium and python,driver.find_element_by_partial_link_text('DEV.tgz').click()
Python numpy 2D array indexing,b[a].shape
parsing json python,print(json.dumps(data))
Tensorflow: How to get a tensor by name?,sess.run('add:0')
Using multiple indicies for arrays in python,test_rec[(test_rec.age == 1) & (test_rec.sex == 1)]
Create a list of sets of atoms,"[('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]"
Python: download a file over an FTP server,"urllib.request.urlretrieve('ftp://server/path/to/file', 'file')"
Python regex match date,match.group(1)
Removing Duplicates from Nested List Based on First 2 Elements,"list({(x[0], x[1]): x for x in L}.values())"
Extracting just Month and Year from Pandas Datetime column (Python),df['date_column'] = pd.to_datetime(df['date_column'])
How to recognize whether a script is running on a tty?,sys.stdout.isatty()
How to create a self resizing grid of buttons in tkinter?,"btn.grid(column=x, row=y, sticky=N + S + E + W)"
Pandas: union duplicate strings,"df.groupby(['ID', 'url'])['active_seconds'].cumsum()"
matplotlib: inset axes for multiple boxplots,plt.show()
Replace all the occurrences of specific words,"sentence = re.sub('\\bbeans\\b', 'cars', sentence)"
set environment variable in python script,os.environ['LD_LIBRARY_PATH'] = 'my_path'
Read lines containing integers from a file in Python?,"line = ['3', '4', '1\r\n']"
switching keys and values in a dictionary in python,"my_dict2 = dict((y, x) for x, y in my_dict.items())"
python and tkinter: using scrollbars on a canvas,root.mainloop()
Check if a Python list item contains a string inside another string,[x for x in lst if 'abc' in x]
How do I wrap a string in a file in Python?,f.read()
Adding up all columns in a dataframe,"pd.concat([df, df.sum(axis=1)], axis=1)"
Numpy: find index of elements in one array that occur in another array,"np.searchsorted(A, np.intersect1d(A, B))"
Get last inserted value from MySQL using SQLAlchemy,session.commit()
Python: Index a Dictionary?,"l = [('blue', '5'), ('red', '6'), ('yellow', '8')]"
How to disable input to a Text widget but allow programatic input?,text_widget.configure(state='disabled')
"Is it OK to raise a built-in exception, but with a different message, in Python?",raise ValueError('invalid input encoding')
How can I get an array of alternating values in python?,"np.resize([1, -1], 10)"
How do I plot multiple X or Y axes in matplotlib?,"ax.plot(x, y, 'k^')"
Matplotlib: text color code in the legend instead of a line,plt.show()
Matplotlib - add colorbar to a sequence of line plots,plt.show()
Return a random word from a word list in python,random.choice(list(open('/etc/dictionaries-common/words')))
Append Level to Column Index in python pandas,"pd.concat([df1, df2, df3], axis=1, keys=['df1', 'df2', 'df3'])"
Correct code to remove the vowels from a string in Python,""""""""""""".join([x for x in c if x not in vowels])"
Iteration order of sets in Python,"set(['a', 'b', 'c'])"
How to query MultiIndex index columns values in pandas,result_df.index.get_level_values('A')
testing whether a Numpy array contains a given row,"equal([1, 2], a).all(axis=1)"
Python converting lists into 2D numpy array,"array([[2.0, 18.0, 2.3], [7.0, 29.0, 4.6], [8.0, 44.0, 8.9], [5.0, 33.0, 7.7]])"
Python convert Tuple to Integer,"int(''.join(map(str, x)))"
how do i return a string from a regex match in python,"print(""yo it's a {}"".format(imgtag.group(0)))"