Unnamed: 0 int64 0 378k | id int64 49.9k 73.8M | title stringlengths 15 150 | question stringlengths 37 64.2k | answer stringlengths 37 44.1k | tags stringlengths 5 106 | score int64 -10 5.87k |
|---|---|---|---|---|---|---|
377,300 | 17,702,153 | Numpy, dot products on multidimensional arrays | <p>I have some doubts on the numpy.dot product.</p>
<p>I define a matrix 6x6 like:</p>
<pre><code>C=np.zeros((6,6))
C[0,0], C[1,1], C[2,2] = 129.5, 129.5, 129.5
C[3,3], C[4,4], C[5,5] = 25, 25, 25
C[0,1], C[0,2] = 82, 82
C[1,0], C[1,2] = 82, 82
C[2,0], C[2,1] = 82, 82
</code></pre>
<p>Then I recast it in a 4-rank te... | <p>The issue is that <code>np.dot(a,b)</code> for multidimensional arrays makes the dot product of the last dimension of <code>a</code> with the second-to-last dimension of <code>b</code>:</p>
<pre><code>np.dot(a,b) == np.tensordot(a, b, axes=([-1],[2]))
</code></pre>
<p>As you see, it does not work as a matrix multi... | python|arrays|numpy|matrix | 14 |
377,301 | 18,103,032 | load a float+ string table | <p>I have a table which contains both floats and strings. When I'm trying to load it by <code>np.loadtxt(file.txt)</code>, I got an error like </p>
<pre><code>could not convert string to float: \Omega_b
</code></pre>
<p>How can I fix it. </p> | <p>You can load using the <code>dtype</code> option to create a <a href="http://docs.scipy.org/doc/numpy/user/basics.rec.html" rel="nofollow">structured array</a>:</p>
<pre><code>np.loadtxt(fname, dtype=[('col1_name', '|S10'), ('col2_name', float)])
</code></pre>
<p>Or if you don't want to specify which dtypes it sho... | python|numpy | 3 |
377,302 | 18,061,711 | Converting an algorithm using numpy.irfft to JavaScript | <p>I am trying to convert an algorithm initially written with numpy to JavaScript, and I don't manage to reproduce the results from a reverse FFT.</p>
<p>The original algorithm uses <code>numpy.fft.rfft</code> and <code>numpy.fft.irfft</code> :</p>
<pre><code># Get the amplitude
amplitudes = abs(np.fft.rfft(buf, axis... | <p>To get a real-only output from a full length IFFT, the input has to be complex-conjugate symmetric (real components the same and imaginary components negated in mirror symmetry for the upper or negative other half of frequency inputs).</p>
<p>With complex conjugate input, the forward or inverse FFT computation shou... | javascript|python|numpy|fft|ifft | 3 |
377,303 | 17,950,835 | Pandas: DataFrame filtering using groupby and a function | <p>Using Python 3.3 and Pandas 0.10</p>
<p>I have a DataFrame that is built from concatenating multiple CSV files. First, I filter out all values in the Name column that contain a certain string. The result looks something like this (shortened for brevity sakes, actually there are more columns):</p>
<pre><code>Name ... | <p>Instead of length <code>len</code>, I think you want to consider the number of unique values of Name in each group. Use <code>nunique()</code>, and check out this neat recipe for filtering groups.</p>
<pre><code>df[df.groupby('ID').Name.transform(lambda x: x.nunique() == 1).astype('bool')]
</code></pre>
<p>If you ... | python|python-3.x|pandas | 5 |
377,304 | 18,203,915 | Pandas read_clipboard broken in pandas 0.12? | <p>Since I updated pandas from version 0.11 to 0.12, read_clipboard doesn't seem to work anymore:</p>
<pre><code>import pandas as pd
df = pd.read_clipboard()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipyt... | <p>Its a bug in the string presented to py3; I'll fix it in master, but you can do this local edit.</p>
<p>in <code>C:\python33\Lib\site-packages\pandas\io\clipboard.py</code></p>
<p>after <code>text = clipboard_get()</code></p>
<p>add <code>text = text.decode('UTF-8')</code></p>
<p>apparently the clipboard routine... | python|pandas | 2 |
377,305 | 18,048,646 | Python array to 1-D Vector | <p>Is there a pythonic way to convert a structured array to vector? </p>
<p>For example:</p>
<p>I'm trying to convert an array like:</p>
<pre><code>[(9,), (1,), (1, 12), (9,), (8,)]
</code></pre>
<p>to a vector like:</p>
<pre><code>[9,1,1,12,9,8]
</code></pre> | <pre><code>In [15]: import numpy as np
In [16]: x = np.array([(9,), (1,), (1, 12), (9,), (8,)])
In [17]: np.concatenate(x)
Out[17]: array([ 9, 1, 1, 12, 9, 8])
</code></pre>
<p>Another option is <code>np.hstack(x)</code>, but for this purpose, <code>np.concatenate</code> is faster:</p>
<pre><code>In [14]: x = [... | python|numpy | 12 |
377,306 | 17,835,302 | How to update matplotlib's imshow() window interactively? | <p>I'm working on some computer vision algorithm and I'd like to show how a numpy array changes in each step.</p>
<p>What works now is that if I have a simple <code>imshow( array )</code> at the end of my code, the window displays and shows the final image.</p>
<p>However what I'd like to do is to update and display ... | <p>You don't need to call <code>imshow</code> all the time. It is much faster to use the object's <code>set_data</code> method:</p>
<pre><code>myobj = imshow(first_image)
for pixel in pixels:
addpixel(pixel)
myobj.set_data(segmentedimg)
draw()
</code></pre>
<p>The <code>draw()</code> should make sure that... | python|numpy|matplotlib|spyder | 52 |
377,307 | 4,152,457 | parameters for low pass fir filter using scipy | <p>I am trying to write a simple low pass filter using scipy, but I need help defining the parameters.</p>
<p>I have 3.5 million records in the time series data that needs to be filtered, and the data is sampled at 1000 hz.</p>
<p>I am using signal.firwin and signal.lfilter from the scipy library.</p>
<p>The paramet... | <p>Cutoff is normalized to the Nyquist frequency, which is half the sampling rate. So with FS = 1000 and FC = 0.05, you want cutoff = 0.05/500 = 1e-4. </p>
<pre><code>from scipy import signal
FS = 1000.0 # sampling rate
FC = 0.05/(0.5*FS) # cu... | numpy|signal-processing|scipy|scientific-computing|matplotlib | 27 |
377,308 | 4,823,223 | Numpy.eig and the percentage of variance in PCA | <p><a href="https://stackoverflow.com/questions/4801259/whats-wrong-with-my-pca">Picking up from where we left...</a></p>
<p>So I can use linalg.eig or linalg.svd to compute the PCA. Each one returns different Principal Components/Eigenvectors and Eigenvalues when they're fed the same data (I'm currently using the Iri... | <p>Taking <a href="https://stackoverflow.com/questions/4801259/whats-wrong-with-my-pca/4803141#4803141">Doug's answer to your previous question</a> and implementing the following two functions, I get the output shown below:</p>
<pre><code>def pca_eig(orig_data):
data = array(orig_data)
data = (data - data.mean... | python|math|numpy|pca | 4 |
377,309 | 8,916,302 | selecting across multiple columns with pandas | <p>I have a dataframe <code>df</code> in pandas that was built using <code>pandas.read_table</code> from a csv file. The dataframe has several columns and it is indexed by one of the columns (which is unique, in that each row has a unique value for that column used for indexing.) </p>
<p>How can I select rows of my da... | <p>I encourage you to pose these questions on the <a href="http://groups.google.com/group/pystatsmodels" rel="noreferrer">mailing list</a>, but in any case, it's still a very much low level affair working with the underlying NumPy arrays. For example, to select rows where the value in any column exceed, say, 1.5 in thi... | python|pandas | 49 |
377,310 | 8,957,175 | DataFrame to Panel indexed by nonunique column with Pandas | <p>The following code should do what I want but it takes 10gb of ram by the time it is 20% done with the loop. </p>
<pre><code># In [4]: type(pd)
# Out[4]: pandas.sparse.frame.SparseDataFrame
memid = unique(pd.Member)
pan = {}
for mem in memid:
pan[mem] = pd[pd.Member==mem]
goal = pandas.Panel(pan)
</code></pre> | <p>I created a GitHub issue here. </p>
<p><a href="https://github.com/wesm/pandas/issues/663" rel="nofollow">https://github.com/wesm/pandas/issues/663</a></p>
<p>I'm pretty sure I identified a circular reference between NumPy ndarray views causing a memory leak. Just committed a fix:</p>
<p><a href="https://github.c... | python|dataframe|panels|pandas | 2 |
377,311 | 8,940,802 | How to integrate SQLAlchemy and a subclassed Numpy.ndarray smoothly and in a pythonic way? | <p>I would like to store NumPy arrays with annotations (like <code>name</code>) via SQLAlchemy within a relational database. To do so, </p>
<ul>
<li>I separate the NumPy array from its data via a data transfer object (<code>DTONumpy</code> as part of <code>MyNumpy</code>).</li>
<li>NumPy objects are collected with <co... | <p>Using the <code>ListView</code>-answer from <a href="https://stackoverflow.com/questions/8984692/how-can-i-change-in-python-the-return-input-type-of-a-list-that-is-implemented-a/" title="Stackoverflow Question 8984692">that</a> question, I came up with the following solution:</p>
<p>First, modify <code>Container</c... | python|numpy|sqlalchemy | 6 |
377,312 | 8,991,709 | Why were pandas merges in python faster than data.table merges in R in 2012? | <p>I recently came across the <a href="http://pandas.sourceforge.net/" rel="noreferrer">pandas</a> library for python, which according to <a href="http://wesmckinney.com/blog/some-pandas-database-join-merge-benchmarks-vs-r-basemerge/" rel="noreferrer">this benchmark</a> performs very fast in-memory merges. It's even f... | <p>The reason pandas is faster is because I came up with a better algorithm, which is implemented very carefully using <a href="https://github.com/attractivechaos/klib" rel="noreferrer">a fast hash table implementation - klib</a> and in C/<a href="http://cython.org/" rel="noreferrer">Cython</a> to avoid the Python inte... | python|r|join|data.table|pandas | 191 |
377,313 | 55,458,987 | ValueError from tensorflow estimator RNNClassifier with gcloud ml-engine job | <p>I am working on the task.py file for submitting a gcloud MLEngine job. Previously I was using tensorflow.estimator.DNNClassifier successfully to submit jobs with my data (which consists solely of 8 columns of sequential numerical data for cryptocurrency prices & volume; no categorical).</p>
<p>I have now switch... | <p>As @Ben7 pointed out <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/estimator/RNNClassifier#__init__" rel="nofollow noreferrer">sequence_feature_columns</a> accepts columns like <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/feature_column/sequence_numeric_column" rel="nofollow norefe... | tensorflow|lstm|gcloud|recurrent-neural-network|tensorflow-estimator | 1 |
377,314 | 55,365,495 | Plotting data binned in a pandas dataframe in a scatterplot | <p>I've got a large amount of astronomical data that I need to plot in a scatterplot. I've binned the data according to distance, and I want to plot 4 scatterplots, side by side.</p>
<p>For the purposes of asking this question, I've constructed a MWE based, obviously with different data, on what I've got so far:</p>
... | <p>What if you grouped the dataframe by <code>binned</code> and then plotted each group?</p>
<p>For example:</p>
<pre><code>fig=plt.figure()
fig.subplots_adjust(hspace=0)
fig.subplots_adjust(wspace=0)
gridsize = 1,4
for i, (name, frame) in enumerate(df.groupby('binned')):
ax = plt.subplot2grid(gridsize, (0,i))... | pandas|dataframe|matplotlib|plot|binning | 1 |
377,315 | 55,348,940 | Getting the filters values from CNN layers | <p>I have the following model (for example)</p>
<pre><code>input_img = Input(shape=(224,224,1)) # size of the input image
x = Conv2D(64, (3, 3), strides=(1, 1), activation='relu', padding='same')(input_img)
</code></pre>
<p>I have several layers of such in my autoencoder model. I am particularly interested in the fil... | <p>At the moment your code is calling the <code>layers</code> function on a layer definition itself. </p>
<p>The model first needs to be compiled and then you can use the <code>layers</code> function on the model to retrieve the weights of the specific layer.</p>
<p>In your case:</p>
<pre><code>weights = model.layer... | python|tensorflow|conv-neural-network|keras-layer|autoencoder | 0 |
377,316 | 55,246,739 | How do I set the x-coordinate in a swarmplot in seaborn? | <p>Trying to do a swarmplot with 3 different vectors in seaborn. I'd like to have each vector at a different x-coordinate and with a different colour. </p>
<p>Unfortunately all the tutorials have the data in some format I can't really find an explanation / manual for... This is what I've got so far:</p>
<pre><code>#!... | <p>try:</p>
<pre><code>df2 = df.melt()
colors = ["orange", "green", "red"]
sns.swarmplot(data=df2, x = 'variable', y='value', palette =colors)
plt.show()
</code></pre> | pandas|seaborn|swarmplot | 1 |
377,317 | 55,223,935 | Compare two Dateframes | <p>Problem:
I have 2 Dataframes:</p>
<pre><code>Name B Worker B
A4 True A4 True
A5 True AND A6 False
A6 True C4 False
A7 False C7 True
</code></pre>
<p>I want to give out the "Name" where Df1.B == True and Df2.B == False </p> | <p>Check with <code>isin</code> </p>
<pre><code>df1.loc[(df1.B)&(~df1.name.isin(df2.Worker)),'name']
</code></pre>
<p>Update </p>
<pre><code>df1.loc[(df1.B)&(~df2.B),'name']
</code></pre> | python|pandas|dataframe | 1 |
377,318 | 55,461,931 | How to merge multiple parquet files in Glue | <p>I have Glue job which is writing parquet files in S3 every 6 seconds and S3 is having folder for that hour. At the end of the hour I want to merge all the files in that hour partition then put it in the same location. I don't want to use the Athena tables because job becomes slow. I am trying using Python Shell. But... | <p>Depending on how big your Parquet files are, and what the target size is – here's an idea to do this without Glue:</p>
<ol>
<li>Set up an hourly Cloudwatch cron rule to look in the directory of the previous file to invoke a Lambda function.</li>
<li>Open each Parquet file, and write them to a new parquet file.</li>... | pandas|boto3|aws-glue|pyarrow | 0 |
377,319 | 55,197,355 | Using a Loop to extract CSV data into an object | <p>My problem is quite difficult to explain and I'm unsure if it's even possible to do what I'm asking, but I will try my best to explain. </p>
<p>Basically, I have a CSV file with data, and I want to extract specific cells and set them as a value in an object. Each row in the CSV contains information about an individ... | <p>This will give you a list of of your Option objects:</p>
<pre><code>options = df.apply(lambda x: Option(x[1], x[2], x[3], x[4]), axis=1)
options_list = options.values.tolist()
</code></pre> | python|pandas|loops|csv | 1 |
377,320 | 55,357,754 | How to groupby a column in dataframe which contains a column containing list of tuples | <p>I am trying to group my dataframe by values in one of the columns, 'category'. Although, one of the other columns 'prob' contains a list of tuples on each row. When I try to group-by 'category', the 'prob' column disappears. </p>
<p>My current df:</p>
<pre><code> category other: prob:
one ... | <p>You can aggregate data by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a> with <code>join</code> for string column and flatten data for tuples - added 3 solutions, <code>sum</code> use only if small data a... | python|pandas | 4 |
377,321 | 55,251,319 | Tensorflow initialization gives all ones | <p>tensorflow 1.12.0</p>
<p>In the code snipped below, it seems that wrapped_rv_val and seq_rv_val should be equivalent, but they are not. Instead, seq_rv_val is correctly initialized to the randomly generated init_val array, but wrapped_rv_val is set to all ones. What's going on here?</p>
<pre><code>import numpy as ... | <p>In fact, <code>seq_rv_val</code> and <code>wrapped_rv_val</code> both will be correctly initialized to the randomly generated <code>init_val array</code> when you do the following.</p>
<pre><code># change
wrapped_rv = tf.nn.softmax(tf.get_variable('wrapped_rv', initializer=init_val))
# to
wrapped_rv = tf.nn.softmax... | python|tensorflow | 1 |
377,322 | 55,517,871 | How to preprocess strings in Keras models Lambda layer? | <p>I have the problem that the value passed on to the Lambda layer (at compile time) is a placeholder generated by keras (without values). When the model is compiled, the .eval () method throws the error:<br></p>
<blockquote>
<p>You must feed a value for placeholder tensor 'input_1' with dtype
string and shape [?,... | <p>Okay I finally solved it that way:</p>
<pre class="lang-py prettyprint-override"><code>def text_preprocess(x):
b = tf.strings.unicode_decode(x,'UTF-8')
b = b.to_tensor(default_value=0)
#do things with decoded string
one_hot = K.one_hot(b,one_hot_size)
return one_hot
...
</code></pre> | python|tensorflow|keras|deep-learning | 0 |
377,323 | 55,299,510 | CPU usage and time until training starts increasing on each model.fit() in Keras | <p>I created an LSTM with Keras API. Now I am facing an issue while I try to test different values in it (for learning rate f.e.). Each time I change my values and define the model new somehow the model takes longer and longer until training start the CPU usage in waiting time is at 100%. Am I doing something wrong so ... | <p>Thanks to @Fedor Petrov and @desertnaut.</p>
<p>They discussed in the comments of another answer that I have to call the function <code>clear_session</code>:</p>
<pre><code>from keras.backend import clear_session
def create():
# do all the model stuff
# evaluate the model
clear_session()
return
<... | python|tensorflow|keras | 4 |
377,324 | 55,264,229 | Print file name within generator of during Pandas Concat pd.concat | <p>I'm loading thousands of files that is supposed to have the same structure through pd.concat using a generator from the list of files in a given directory. </p>
<p>Is there anyway I can print f within this generator for debugging purpose? I'd like to know which file causes the failure. Thank you all in advance!</p>... | <p>You can use a <code>try..except</code> to properly handle loading the file and printing the potential error. Here's an example:</p>
<pre><code>files = glob.glob(input_dir + "/*.csv")
def load_file(f):
"""Loads a csv file into a dataframe"""
try:
# Load the file if there is no problem
return p... | python|python-3.x|pandas | 2 |
377,325 | 55,463,536 | Select rows from a DataFrame using .loc and multiple conditions and then show the row corresponding to the min/max of one column | <p>I know how to select data using .loc and multiple conditions, like so: </p>
<pre><code>df.loc[(df['A'] == True)&(df['B'] == 'Tuesday')]
</code></pre>
<p>But from the result of this I can't figure out how to show the entire row corresponding to the min (or max) taken on one other column of numbers, 'C'. How d... | <p>Use this:</p>
<pre><code>df2 = df.loc[(df['A'] == True)&(df['B'] == 'Tuesday')]
df2.loc[df2.C == df2.C.min(), :]
</code></pre> | python|pandas|dataframe | 3 |
377,326 | 55,494,824 | Replacing Duplicate Strings in Pandas Dataframe | <p>I have a dataframe df</p>
<pre><code>Name Reagent
0 Experiment1 water
1 Experiment1 oil
2 Experiment1 water
3 Experiment1 milk
4 Experiment1 water
5 Experiment1 tea
6 Experiment1 water
7 Experiment1 coffee
8 Experiment2 water
9 Experiment2 coffee
</code></pre>
<p>I want to replace du... | <p>Solution: append all values with the <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> as a counter (and replace <code>0</code> values with empty strings to ignore each first dupe):</p>
<pre><code... | pandas|dataframe | 3 |
377,327 | 55,481,140 | tensorflow.python.framework.errors_impl.ResourceExhaustedError | <p>I'm using an object detection module for classifying images. My specs are as follows:</p>
<ul>
<li>OS: Ubuntu 18.04 LTS</li>
<li>Python: 3.6.7</li>
<li>VirtualEnv: Version: 16.4.3</li>
<li>Pip3 version inside virtualenv: 19.0.3</li>
<li>TensorFlow Version: 1.13.1</li>
<li>Protoc Version: 3.0.0-9</li>
</ul>
<p>I'm wo... | <p>You can try the following fixes:<br>
1. Reducing the image dimension in case you are using very high image resolution<br>
2. Try reducing the batch size<br>
3. Check if any other process is using up your memory</p>
<p>Could you also please share your config file</p> | tensorflow|object-detection|object-detection-api | 3 |
377,328 | 55,267,201 | Interpreting results of tensorflow benchmark tool | <p>Tensorflow have few benchmark tools:</p>
<p>For <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/tools/benchmark" rel="nofollow noreferrer">.pb model</a> and for <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/tools/benchmark" rel="nofollow noreferrer">.tflite m... | <p>After digging in the code a bit I've found the following (All times are in microseconds):</p>
<ul>
<li><code>count</code>: number of actual runs</li>
<li><code>first</code>: time the first iteration took</li>
<li><code>curr</code>: time the last iteration took</li>
<li><code>min</code>: minimum time an iteration to... | tensorflow|benchmarking|tensorflow-lite | 6 |
377,329 | 55,394,339 | "Request payload size exceeds the limit" in google cloud json prediction request | <p>I am trying to serve a prediction using google cloud ml engine. I generated my model using <a href="https://github.com/lengstrom/fast-style-transfer" rel="nofollow noreferrer">fast-style-transfer</a> and saved it on my google cloud ml engine's models section. For input it use float32 and so I had to convert my image... | <p>This is a hard limit for the Cloud Machine Learning Engine API. There's a <a href="https://issuetracker.google.com/issues/123314535" rel="nofollow noreferrer">feature request</a> to increase this limit. You could post a comment there asking for an update. Moreover, you could try <a href="https://stackoverflow.com/a/... | python-2.7|tensorflow|google-cloud-ml | 2 |
377,330 | 55,547,287 | how to get last column of pandas series | <p>I am trying to count frequencies of an array.
I've read this <a href="https://stackoverflow.com/questions/40144769/how-to-select-the-last-column-of-dataframe">post</a>, I am using DataFrame and get a series.</p>
<pre><code>>>> a = np.array([1, 1, 5, 0, 1, 2, 2, 0, 1, 4])
>>> df = pd.DataFrame(a, c... | <p>Since <code>pandas.Series</code> is a </p>
<blockquote>
<p>One-dimensional ndarray with axis labels</p>
</blockquote>
<p>If you want to get just the frequencies column, i.e. the values of
your series, use:</p>
<pre><code>b.tolist()
</code></pre>
<p>or, alternatively:</p>
<pre><code>b.to_dict()
</code></pre>
... | python|pandas | 2 |
377,331 | 55,434,653 | Batch Normalization doesn't have gradient in tensorflow 2.0? | <p>I am trying to make a simple GANs to generate digits from the MNIST dataset. However when I get to training(which is custom) I get this annoying warning that I suspect is the cause of not training like I'm used to.</p>
<p>Keep in mind this is all in tensorflow 2.0 using it's default eager execution.</p>
<p>GET THE... | <p>The problem is here:</p>
<pre><code>gradients_of_generator = gen_tape.gradient(gen_loss, generator.variables)
</code></pre>
<p>You should only be getting gradients for the <em>trainable</em> variables. So you should change it to </p>
<pre><code>gradients_of_generator = gen_tape.gradient(gen_loss, generator.traina... | python-3.x|tensorflow|batch-normalization|tensorflow2.0 | 10 |
377,332 | 55,274,628 | Install Tensorflow gpu on a remote pc without sudo | <p>I don't have <strong>sudo</strong> access to the remote pc where <strong>cuda</strong> is already installed. Now, I have to install <strong>tensorflow-gpu</strong> on that system. Please give me the step by step guide to install it without sudo. </p>
<p>Operating System : Ubuntu 18.04</p> | <p>I had to do this before. Basically, I installed miniconda (you can also use anaconda, same thing and installation works without sudo), and installed everything using conda.</p>
<p>Create my environment and activate it:</p>
<pre><code>conda create --name myenv python=3.6.8
conda actiavate myenv
</code></pre>
<p>In... | tensorflow|ubuntu-18.04 | 3 |
377,333 | 55,474,457 | How can I create a pandas dataframe column for each part-of-speech tag? | <p>I have a dataset that consists of tokenized, POS-tagged phrases as one column of a dataframe: </p>
<p><a href="https://i.stack.imgur.com/3TvQU.png" rel="nofollow noreferrer">Current Dataframe</a></p>
<p>I want to create a new column in the dataframe, consisting only of the proper nouns in the previous column:</p>
... | <p>You can use the apply method, which as the name suggests will apply the given function to every row of the dataframe or series. This will return a series, which you can add as a new column to your dataframe</p>
<pre><code>df['Proper Nouns'] = df['POS_Description'].apply(
lambda row: [i[0] for i in row if i[1] =... | python|pandas|nltk|pos-tagger | 1 |
377,334 | 55,475,655 | ModuleNotFoundError: No module named 'nets' | <p>Hi guys I'm having an error when I'm trying to run the training using this command:</p>
<pre><code>> `python train.py --logtostderr --train_dir=training/
> --pipeline_config_path=training/ssd_mobilenet_v1_coco.config`
</code></pre>
<blockquote>
<p><code>Traceback (most recent call last): File "train.py", l... | <p>The <code>nets</code> module is in <code>slim</code> folder, you need to add the <code>slim</code> library to <code>PYTHONPATH</code>:</p>
<pre><code># From tensorflow/models/research/
export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
</code></pre> | tensorflow|object-detection-api | 0 |
377,335 | 55,385,927 | joining two dataframes and extending the contents of one of them | <pre><code>df1 = pd.DataFrame([1,2,3],columns=['x'])
df2 = pd.DataFrame([[100,200,300]],columns=['y','w','z'])
</code></pre>
<p>How can I join both dataframes by extending <code>df2</code> to match the rows of <code>df1</code>?</p>
<p>This is what I'm trying to achieve</p>
<pre><code>x y w z
1 100 200 300
2... | <p>You can use join as @Vaishali mentions of your index of your dataframes are the default range index. Where the index of your second dataframe, df2, matches the first index of df1. However, creating a temporary key and doing a merge to create a cartesian product is a little more robust.</p>
<pre><code>df1.assign(... | python|pandas | 3 |
377,336 | 55,174,890 | one Column value based add value of corresponding column in new column | <p>I have 2 two data frames df1 and df2 , in df2 i have 4 columns . i want if df2 column1 value is 0 ,code should add corresponding 3 column values in df1 with column name col2_0 ,col3_0, and col4_0(Note: this process also need to do for value -1,-2,-3,-4,-5), with if else can be done this problem but i am looking for ... | <p>I'll use an initially empty df1 with some extra rows for this example:</p>
<pre><code>df2 = pd.DataFrame({'#timestamp':[-5,-4,-3,-2,-1,0],
'grid_U1': [413.714,413.797,413.926,414.037,414.066,414.064],
'grid_U2': [415.796,415.909,416.117,416.093,416.163,416.183],
... | python-3.x|pandas|pandas-groupby | 1 |
377,337 | 55,447,630 | Python - Pandas Groupby and filter | <p>I have this as a csv working in pandas- first ten rows:</p>
A simplified df as follows:
<pre><code> permno price mv yearmonth
1752 10057 18.1250 7.898875e+04 198301
4732 10137 23.7500 1.130191e+06 198301
6144 10153 9.7500 1.226550e+05 198302
7869 10225 45.8... | <p>I think you may want to use cut or qcut to get your desired results. Cut will create evenly spaced ranges while qcut will create an even number of items per bin. Qcut is more consistent with quantiles.</p>
<p>Here's my code:</p>
<pre><code>#Recreate your dataset
df = pd.DataFrame(
{
'permno':[10057, 10... | python|pandas|dataframe|group-by | 0 |
377,338 | 55,459,114 | Merging Two Columns in DataFrame With Variable Column Names | <p>Editing my original post to hopefully simplify my question... I'm merging multiple DataFrames into one, SomeData.DataFrame, which gives me the following: </p>
<pre><code> Key 2019-02-17 2019-02-24_x 2019-02-24_y 2019-03-03
0 A 80 NaN NaN 80 ... | <p>Edited answer to updated question:</p>
<pre><code>df = df.set_index('Key')
df.groupby(df.columns.str.split('_').str[0], axis=1).sum()
</code></pre>
<p>Output:</p>
<pre><code> 2019-02-17 2019-02-24 2019-03-03
Key
A 80.0 0.0 80.0
B ... | python|pandas|dataframe | 0 |
377,339 | 55,156,019 | Split key value string in python and move it in a df column | <p>Here's the column that I have, I want to split into key - value and store in a new column in pandas df.</p>
<pre><code>{"FontStyle"=>"Gill Sans Standard", "FontSize"=>"Medium (3mm)"}
{"Font Style"=>"Gill Sans Standard","Font Size"=>"Medium (3mm)"}
{"Font Style":"Script","Font Size":"Medium (3mm)"}
{"Fon... | <p>This is by far not the most efficient code but this would do the work.</p>
<pre><code>import pandas as pd
import ast
text = '''{"FontStyle"=>"Gill Sans Standard", "FontSize"=>"Medium (3mm)"}
{"Font Style"=>"Gill Sans Standard","Font Size"=>"Medium (3mm)"}
{"Font Style"=>"Script","Font Size"=>"Med... | python|regex|pandas|split | 2 |
377,340 | 55,353,624 | improve speed of extracting information from pandas columns | <p>I have a dataframe with around 200,000 datapoints and a column which looks like this (example for 1 datapoint):</p>
<pre><code>'{"id":342,"name":"Web","slug":"technology/web","position":15,"parent_id":16,"color":6526716,"urls":{"web":{"discover":"http://www.kickstarter.com/discover/categories/technology/web"}}}'
</... | <p>Instead of manipulating a DataFrame directly, try using simple data types and create a dataframe in one go. Another solution other than jezrael's:</p>
<pre><code>import json
cat, slug = [], []
for row in df.category:
d = json.loads(row)
cat.append(d['cat'])
slug.append(d['slug'])
df = pd.DataFrame({'... | python|pandas|dictionary | 1 |
377,341 | 55,523,474 | How to apply np.ceil to a structured numpy array | <p>I'm trying to use the np.ceil function on a structrued numpy array, but all I get is the error message:</p>
<pre class="lang-py prettyprint-override"><code>TypeError: ufunc 'ceil' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''saf... | <p>Here's a dirty solution based on viewing the array without its structure, taking the ceiling, and then converting it back to a structured array.</p>
<pre><code># sample array
arr = np.array([(1.4,2.3), (3.2,4.1)], dtype = [("x", "<f8"), ("y", "<f8")])
# remove struct and take the ceiling
arr1 = np.ceil(arr.vi... | python|numpy|ceil|structured-array | 0 |
377,342 | 55,513,199 | How to deal with unicode values dict in a column | <p>I have a column ('discount') in a df which every value is in its format:</p>
<pre><code>{u'customer': u'xdawd', u'end': None, u'coupon': {u'object': u'coupon', u'name': u'Black Friday', u'percent_off': None, u'created': 213213, u'times_redeemed': 10, u'amount_off': 2500, u'currency': u'gbp', u'object': u'discount',... | <p>With a <code>lambda function</code> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer"><code>Series.apply</code></a>:</p>
<pre><code>df['discount'].apply(lambda x: x['coupon'].get('percent_off') or x['coupon'].get('amount_off'))
</code></pre>
... | python|pandas|unicode|apply | 2 |
377,343 | 55,350,221 | multi indexing with sort by values - Pandas | <p>I am trying to return the <code>max</code> value based off two <code>Columns</code> in a <code>pandas</code> <code>df</code>. I want to groupby and sort these values so all are displayed from <code>max</code> to <code>min</code>.</p>
<p>Here is my attempt:</p>
<pre><code>import pandas as pd
d = ({
'Day' : ['M... | <pre><code>df = pd.DataFrame({
'Day': ['Mon', 'Mon', 'Mon', 'Mon', 'Wed', 'Wed', 'Wed', 'Wed', 'Sat', 'Sat', 'Sat', 'Sat'],
'Object': ['X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y'],
'Value': [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
})
df = df.sort_values(['Day', 'Value'], ascending=[1, 0])
df = d... | python|pandas|group-by|duplicates | 3 |
377,344 | 55,258,435 | How to fill values in a pandas Series in positions between specific "start" and "stop" markers? | <p>I have a DataFrame that is a follows:</p>
<pre><code>df[16820:16830]
data0 start_stop
16820 1 0
16821 1 1
16822 1 0
16823 1 0
16824 1 0
16825 1 -1
16826 0 0
16827 0 0
16828 1 ... | <p>This should work</p>
<pre><code>df['valid'] = df.start_stop.cumsum()
</code></pre>
<p>Then</p>
<pre><code>df['valid'] = df['valid'].apply(lambda x: True if x==1 else False)
df
start_stop valid
0 0 False
1 1 True
2 0 True
3 0 True
4 0 True
5 ... | python|pandas | 6 |
377,345 | 55,322,358 | Python Numpy arrays, Vlookup like function | <p>I would like to ask for your help. The problem in steps.
1. Import two excel files into Python Data frames - so far no problem
2. Transferring the data frames into numpy arrays.
3. Create a VLOOKUP function in python, with the arrays. Both arrays have a key in the first column, which is unique and can be used for ma... | <p>If same length, use pd.merge, it acts like vlookup:</p>
<pre><code>newdf = s.merge(r, on ='same_key')
</code></pre>
<p>newdf will have all the columns from both data frames. You can now access the individual columns you need to update:</p>
<pre><code>newdf['wrongcolumn'] = newdf['rightcolumn']
</code></pre> | python|numpy|vlookup | 0 |
377,346 | 55,153,394 | Merge remaining part of split array | <p>I have framed the following code to split the array into 4 parts and obtain first part separately. Now, I need to obtain the other remaining parts as joined separate array.</p>
<pre><code>test = [(0,1,2),(9,0,1),(0,1,3),(0,1,8)]
print(test)
test_np = np.array_split(test,4)
np2 = test_np[2]
</code></pre>
<p>Then I ... | <p>In your case, 'test' is a list of tuples, so you dont need numpy:</p>
<pre><code>import numpy as np
test = [(0,1,2),(9,0,1),(0,1,3),(0,1,8)]
t_0 = test[:1]
t_1 = test[1]
new_test= t_0+test[2:]
print(new_test)
# as np.array:
np_test=np.array(test)
</code></pre>
<p>If you have a numpy array in the first place:</... | python|arrays|numpy | 1 |
377,347 | 55,142,337 | KeyError when parsing CSV file | <pre><code>mtu,dap
06.01.2015 00:00 - 06.01.2015 01:00,36.90
</code></pre>
<p>I am trying to work the comma delimited data from the picture above into pandas for further analysis with the following bit of code:</p>
<pre><code>import pandas as pd
DAP = pd.read_csv('xx.csv',
index_col = 'mtu',
sep = ',',
... | <p>This is what I spent my day on, will defo give you a good review if you can help out. I feel like a noob but gotto start somewhere. Thanks for your help anyways! </p>
<pre><code>af = act_freq['actual_freq']
datetime = act_freq['datetime']
act_freq = pd.read_csv('xx.csv',
sep = ',',
... | pandas|csv|parsing|keyerror | 0 |
377,348 | 55,227,825 | Create a TensorFlow Dataset for a CNN from a local dataset | <p>I have a big dataset of B/W images with two classes where the name of the directory is the name of the class:</p>
<ul>
<li>the directory <code>SELECTION</code> contains all images with label = selection;</li>
<li>the directory <code>NEUTRAL</code> contains all images with label = neutral.</li>
</ul>
<p>I need to l... | <p>Your issue is that path_ds should be the image paths as strings, but you try to convert them to a list of tensors. </p>
<p>So to get the tensors you only need:</p>
<pre><code>image_ds = all_image_paths.map(load_and_decode_image, num_parallel_calls=AUTOTUNE)
</code></pre> | python|tensorflow|dataset|load|local | 0 |
377,349 | 55,493,358 | Is it possible to assign an operation to the same variable, which is used in operation? | <p>I have an operation in tensorflow which looks like follows:</p>
<p><code>x = tf.where(tf.is_nan(x), tf.zeros_like(x), x)</code></p>
<p>Is this possible, as the operation changes the new variable x continuously, while simultaneously using it for code execution?</p> | <p>Yes, it is possible to reuse variable names in Python, regardless of whether TensorFlow is used or not. (The previous tensor associated with <code>x</code> still exists, but cannot be accessed in code via <code>x</code> anymore, as it has been assigned a new value. The <code>x</code> to the left of <code>=</code> is... | python|tensorflow | 0 |
377,350 | 55,307,233 | Adding name of weekday in pandas plot? | <p>here is my code:</p>
<pre><code>df["Created"] = pd.to_datetime(df["Created"])
df.groupby(df.Created.dt.weekday).size().plot(linewidth = 0.4, x_compat=True)
</code></pre>
<p>I would like to show the name of the day on the graph and also by which day the week starts in pandas?</p>
<p><a href="https... | <p>Try dt.day_name instead of weekday</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.day_name.html#pandas-series-dt-day-name" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.day_name.html#pandas-series-dt-day-name</a></p... | python|pandas | 0 |
377,351 | 55,287,338 | Extract dataframes from python dictionary | <p>I have a python dictionary containing 3 dataframes and nothing else. I need to call each dataframe by dataframe name without using d['']; for example, with the dataframe loopdata1, I need to call it without doing d['loopdata1']. Here's the dictionary with the 3 dataframes loopdata1, loopdata2, and loopdata3:</p>
<p... | <p>you could append incoming dataframes together instead of adding them to a dict.<br>
<code>first = True
for dfname in lst:
if first = True:
main_df = pd.read_excel(dfname + '.xlsx')
first = False
else:
appending_df = pd.read_excel(dfname + '.xlsx')
... | python|pandas|dataframe|dictionary|for-loop | 0 |
377,352 | 55,546,832 | multi task learning using estimates as features | <p>I have multi task network that has 3 classification heads <code>[A, B, C]</code>.
I want use output of head <code>A</code> as input to the first dense layers of <code>B and C</code>.</p>
<p>Does something special should be done for back propagation as I think that the gradients from <code>B and C</code> shouldn't f... | <p>you can try:</p>
<pre><code>A_layer = tf.keras.layers.Dense(5)(x)
A_head= tf.keras.layers.Dense(5)(A_layer)
A_logic = tf.keras.layers.Dense(1)(A_head)
A_loss = tf.losses.sigmoid_cross_entropy(A_y,A_logic)
B_layer = tf.keras.layers.Dense(5)(tf.stop_gradient(A_logic))
B_head= tf.keras.layers.Dense(5)(B_layer)
B_logi... | tensorflow|keras|neural-network | 0 |
377,353 | 55,552,107 | How to extract first element of a tuple, which is a column in a dataframe in Python? | <p>I have a dataframe as follows,</p>
<pre><code>id text senti_score
1 text A (0.5,1)
2 text B (0.4,0.7)
3 Nan None
4 text c (0.2,0.4)
Expected output,
id text senti_score new_Sco... | <p>Just use pandas <code>str</code> accessor + <code>.get</code></p>
<pre><code>df['senti_score'].str[0]
</code></pre>
<p>or</p>
<pre><code>df['senti_score'].str.get(0)
</code></pre> | python|pandas | 4 |
377,354 | 55,299,674 | Getting the list of dates given a string in python | <p>I have a string in python which is</p>
<pre><code>date="200601"
</code></pre>
<p>which represents in <code>2006 January</code></p>
<p>How do I get the list of dates in that particular month in the '<code>yyyy-mm-dd</code>' format</p>
<p>and also how do I iterate over <code>200601</code> to <code>201903</code> ie... | <p>To get all the <code>dates</code> in the <code>month</code> of that <code>year</code> in the format of <code>yyyy-mm-dd</code>:</p>
<pre><code>date = "200601"
import datetime, calendar
num_days = calendar.monthrange(int(date[:-2]), int(date[4:]))[1]
print([datetime.date(int(date[:-2]), int(date[4:]), day).strftime... | python|pandas|datetime | 1 |
377,355 | 55,339,923 | Column names of xlsx file are not retained in the converted csvs | <p>I am fetching data from a multisheet xlsx file and storing data in separate csv files. The first rows of all the sheets in xslx are stored in the first csv, the 2nd rows of all the sheets are stored in the 2nd csv, and, so on. For that I wrote the following code which works:</p>
<pre><code>xls = xlrd.open_workbook(... | <p>You have to explicitely write the column names when you use a <code>csv.writer</code>. It is enough to use the column names from the last sheet:</p>
<pre><code>writer = csv.writer(open('/home/hp/products/' + 'prod['+str(i)+'].csv', 'w'))
writer.writerow(prod.columns.tolist())
writer.writerows(rows)
</code></pre> | python|pandas|csv|dataframe|xlsx | 2 |
377,356 | 55,438,811 | OSError: [WinError 193] %1 is not a valid Win32 application Unable to Get Python to Import Libraries | <p>I have tried for 2 days to install Python 64-bit on my 64-bit Windows
10 PC. However, I tried Python, Anaconda, one user/ all users,
installation in C: Root/ Program Files/ etc. But I am unable to get
around this error. After online research it is some issue related to
Python not finding the 64-bit DLLs, but I could... | <p>I had the same issue.
I wasn't using Anaconda, just the latest distribution. But re-installing Python in a different location ( I had it on C:/Python37) fixed the issue.</p>
<p>Not sure why, but I tried on the predefined location for the installer and in C:/Program Files/Python37, and both worked for me.</p> | python|tensorflow|windows-10|anaconda|importerror | 0 |
377,357 | 55,189,818 | Getting unique values from pandas column of 2d array cells | <p>I have a pandas DataFrame where each cell in a column is a 2d array of items.</p>
<p>EX: Observation 1 has column <code>items</code> with values <code>['Baseball', 'Glove','Snack']</code></p>
<p>When I use <code>.unique</code> on the individual cells, each cell gets analyzed based on the whole arrays value, not in... | <p>I would use <code>chain</code> method of <code>itertools</code> together with <code>set</code>s as to solve the problem as follows.</p>
<pre><code># you have a dataframe called data with the column items.
from itertools import chain
unique_lists_in_items = data.items.unique().tolist()
set_of_items = set(chain(*uni... | python|pandas | 0 |
377,358 | 55,207,756 | RuntimeWarning: Invalid value encountered in less xa[xa < 0] = -1 (Geopandas) | <h3>Problem</h3>
<p>I'm trying to plot crime data in each district using <strong>geopandas</strong>. I have merged <code>shapefile</code> data and crime data:</p>
<pre><code>merged = merged[['geometry','Extortion']]
merged.head()
</code></pre>
<p><a href="https://i.stack.imgur.com/MILS3.jpg" rel="nofollow noreferrer... | <p>I got this same error and on examination it was caused by polygons in my shapefile not being represented in the data, so it just required replacement of the NANs which were created on the merge, eg</p>
<pre><code>merged['Extortion']=merged['Extortion'].fillna(0)
</code></pre> | python|maps|geopandas | 1 |
377,359 | 9,792,925 | how to speed up enumerate for numpy array / how to enumerate over numpy array efficiently? | <p>I need to generate a lot of random numbers. I've tried using <code>random.random</code> but this function is quite slow. Therefore I switched to <code>numpy.random.random</code> which is way faster! So far so good. The generated random numbers are actually used to calculate some thing (based on the number). I theref... | <p>To take full advantage of numpy's speed, you want to create <a href="http://docs.scipy.org/doc/numpy/reference/ufuncs.html" rel="nofollow noreferrer">ufuncs</a> whenever possible. Applying <code>vectorize</code> to a function as <a href="https://stackoverflow.com/a/9793070/577088">mgibsonbr</a> suggests is one way t... | python|numpy | 6 |
377,360 | 10,181,151 | trying to get reasonable values from scipy powerlaw fit | <p>I'm trying to fit some data from a simulation code I've been running in order to figure out a power law dependence. When I plot a linear fit, the data does not fit very well. </p>
<p>Here's the python script I'm using to fit the data:</p>
<pre><code>#!/usr/bin/env python
from scipy import optimize
import numpy
xd... | <p>It is much better to first take the logarithm, then use <code>leastsquare</code> to fit to this linear equation, which will give you a much better fit. There is a great example in the <a href="http://www.scipy.org/Cookbook/FittingData">scipy cookbook</a>, which I've adapted below to fit your code.</p>
<p>The best f... | python|numpy|scipy|curve-fitting|least-squares | 8 |
377,361 | 7,160,162 | Left Matrix Division and Numpy Solve | <p>I am trying to convert code that contains the \ operator from Matlab (Octave) to Python. Sample code</p>
<pre class="lang-matlab prettyprint-override"><code>B = [2;4]
b = [4;4]
B \ b
</code></pre>
<p>This works and produces 1.2 as an answer. Using this web page</p>
<p><a href="http://mathesaurus.sourceforge.net/matl... | <p>From <a href="http://www.mathworks.com/help/techdoc/ref/mldivide.html" rel="noreferrer">MathWorks documentation</a> for left matrix division:</p>
<blockquote>
<p>If A is an m-by-n matrix with m ~= n and B is a column vector with m
components, or a matrix with several such columns, then X = A\B is the
solution... | python|matlab|numpy|octave|linear-algebra | 20 |
377,362 | 56,793,012 | Explanation of an implementation of the categorical_crossentropy | <p>The formula for the categorical cross-entropy is the following. </p>
<p><a href="https://i.stack.imgur.com/arjPt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/arjPt.png" alt="enter image description here"></a></p>
<p>What should the output of the last layer be? Should it be the probabilities o... | <blockquote>
<p>What should the output of the last layer be? Should it be the probabilities of classes from a softmax layer?</p>
</blockquote>
<p>It can be either the output of the softmax layer or the raw <a href="https://en.wikipedia.org/wiki/Logit" rel="nofollow noreferrer">logits</a> (input to the softmax layer)... | tensorflow|keras | 3 |
377,363 | 56,530,706 | How to change strings in dataframe to date time values? | <p>I have a column in a pandas dataframe of strings representing dates in the form</p>
<pre><code> Year-day hour:minute:second.microsecond
</code></pre>
<p>Except the day is written as a single number from 0-364. For example, the date<code>2019-040 04:00:00:000000</code> represents 4 am on february 9, 2019. How do I ... | <p>You can use <code>datetime</code> and <code>strptime</code> to achieve this. The <code>%j</code> <a href="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow noreferrer">directive</a> allows you to enter the zero-padded day number of the year:</p>
<pre class="lang-py pretty... | python|pandas | 2 |
377,364 | 56,605,403 | Getting value from dataframe based on Series with column name | <p>I have a DataFrame with date indexes and column names.</p>
<pre><code>df1 =
date col1 col2 col3
20190101 1 2 3
20190102 6 5 4
20190103 -7 -9 -8
20190104 4 9 8
</code></pre>
<p>and then I have Series with a subset of the indexes and a column name with the name of the c... | <p>In your initial df, just use <code>df.max(1)</code>. Then, filter out all values that are negative.</p>
<pre><code>s = df.max(1)
s[s>0]
</code></pre>
<p>returns</p>
<pre><code>date
20190101 3
20190102 6
20190104 9
dtype: int64
</code></pre>
<hr>
<p>But if you really want to use your <code>max_col</c... | python|pandas|dataframe | 0 |
377,365 | 56,801,681 | How to create chunking of numpy.linespace() for large scale data | <p>I'm getting a memory error because the resulting data is too large since I am using a size of over billions.</p>
<p>What approach may I be using for chunking of data?</p> | <p>If what you want is store all the resulting data, you can store first the chunked data to h5py. for reference <a href="http://docs.h5py.org/en/stable/" rel="nofollow noreferrer">http://docs.h5py.org/en/stable/</a>. Please elaborate your question</p>
<p>Try to create first a list of chunked size of your linspace tot... | python-3.x|numpy | 1 |
377,366 | 56,452,840 | French Character Turn Into Question Marks; Pandas | <p>I have a csv file which contains french characters/accents including: É, ê, è etc, referring to some french city and street names. I have tried several encoding options on the read_csv and to_csv functions in Pandas including:</p>
<pre><code> df=pd.read_csv(FilePath, encoding='latin-1' )
</code></pre>
<p>also:</p>... | <p>This should work</p>
<pre><code>df = pd.read_excel(FilePath, encoding='latin1')
</code></pre> | python|pandas|encoding|character-encoding | 1 |
377,367 | 56,699,048 | How to get the filename of a sample from a DataLoader? | <p>I need to write a file with the result of the data test of a Convolutional Neural Network that I trained. The data include speech data collection. The file format needs to be "file name, prediction", but I am having a hard time to extract the file name. I load the data like this:</p>
<pre class="lang-py prettyprint... | <p>Well, it depends on how your <code>Dataset</code> is implemented. For instance, in the <code>torchvision.datasets.MNIST(...)</code> case, you cannot retrieve the filename simply because there is no such thing as the filename of a single sample (MNIST samples are <a href="https://github.com/pytorch/vision/blob/master... | python|machine-learning|pytorch|torchvision | 8 |
377,368 | 56,763,226 | Finding the mean on multiple fields | <p>I am trying to figure out a way to code in python on something specific. I am working with a csv data set that runs with the columns; age, sex, bmi, charges, smoker, number of children. My question being, is there a way to find the mean of BMI where the sex is equal to male or female? </p>
<p>I understand that usin... | <p>I have found a way to group that gives me mean and counts on multiple fields:</p>
<pre><code>df.groupby(["sex"]).agg(["mean", "count"])
</code></pre> | python|pandas|pandas-groupby | 0 |
377,369 | 56,854,774 | Remove Duplicates and Filter Dataframe | <p>I'm working on a simulator that has a marketplace where providers put offers and consumers bid. The concept is rather simple.</p>
<p>Based on consumers and providers offers and preferences, I create a dataframe sorted by the Euclidean distance between the consumer preference and the provider offer to maximize the c... | <p>So I solved my issue by creating a new dataframe, iterating through each row, adding to the new df, and deduplicating at each step:</p>
<pre><code>df = pd.DataFrame()
for idx, row in offers.iterrows():
df = df.append(row)
df = df.drop_duplicates(subset=['consumerId'], keep='first')
df = ... | python|pandas|dataframe | 0 |
377,370 | 56,721,487 | Drop row keep similiar value column data | <p>Based on this question <a href="https://stackoverflow.com/questions/56519823/drop-row-based-on-two-columns-conditions">Drop row based on two columns conditions</a>, otherwise, I want to eliminate the different value of row data.</p>
<p>I have <code>dataframe</code> looks like this:</p>
<pre><code>df
Data1 Data2 ... | <p>You can use <code>groupby</code>:</p>
<pre><code>df[df.groupby('Data1')['Data3'].transform('nunique').eq(1)]
</code></pre>
<p>Or <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer"><code>duplicated()</code></a>:</p>
<pre><code>df[df.dupli... | python|pandas|row | 2 |
377,371 | 56,612,609 | Pandas accumulate data for linear regression | <p>I try to adjust my data so total_gross per day is accumulated. E.g.</p>
<pre><code>`Created` `total_gross` `total_gross_accumulated`
Day 1 100 100
Day 2 100 200
Day 3 100 300
Day 4 100 400
</code></pre>
<p>Any idea, how I have to change my code to have <... | <p><em>List comprehension is the most pythonic way to do this.</em></p>
<p><strong>SHORT answer:</strong></p>
<p>This should give you the new column that you want:</p>
<pre><code>n = event_data.shape[0]
# skip line 0 and start by accumulating from 1 until the end
total_gross_accumulated =[event_data['total_gross'][... | pandas|matplotlib|machine-learning|linear-regression | 2 |
377,372 | 56,803,686 | How to extract adjacent rows? | <p>I have the code below which extract all the rows and columns which contains the string opened.</p>
<pre><code>opened = door[door.Text4.str.contains('opened')]
</code></pre>
<p>In addition to the above i also need to extract the next row.</p>
<pre><code> A Text4 C D
5 foo opened 0 0
6 bar ... | <p>You can select the adjacent row containing <code>'opened'</code> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shift.html" rel="nofollow noreferrer"><code>shift(1)</code></a>, which select the adjacent line. To select both the one containing <code>'opened'</code> and the a... | pandas | 3 |
377,373 | 56,798,250 | Pandas Dataframe to nested data structure | <p>I have a data frame with this structure:</p>
<pre><code>>>> df
ID Class Type
0 1 Math Calculus
1 1 Math Algebra
2 1 Science Physics
3 1 History American
4 2 Math Factorization
5 2 History European
6 2 Science Chemistry
7 ... | <p>IIUC you can try to play from this:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
txt="""0 1 Math Calculus
1 1 Math Algebra
2 1 Science Physics
3 1 History American
4 2 Math Factorization
5 2 History European
6 2 Science ... | python|pandas | 1 |
377,374 | 56,468,112 | Pandas dataframe slicing and manipulation | <p>I have dataframe <code>df1</code> as follows</p>
<pre><code>+------+----------+-----+
| Date | Location | Key |
+------+----------+-----+
| | a | 1 |
| | a | 2 |
| | b | 3 |
| | b | 3 |
| | b | 3 |
| | c | 4 |
| | c | ... | <p>You can try:</p>
<pre><code># obviously we will group by Location
groups = df1.groupby('Location')
# we record the changes and mark the unchanged with nan
df1['changes'] = groups.Key.diff().replace({0:np.nan})
# average the changes by location
# ignore all the nan's (unchanges)
groups.changes.mean()
</code></pre>... | python|pandas|vectorization | 0 |
377,375 | 56,589,371 | Problem with callback error during Dash app implementation | <p>I am trying to set up a simple Dash app that returns a value from a dataframe used as a "look-up table"; a screenshot of a sample test table is included here<a href="https://i.stack.imgur.com/bag5l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bag5l.png" alt="enter image description here"></a></... | <p>You did not mention the specific error, but I think I can see the problem. Your callback is outputing (<code>Output</code>) to the dropdown component's <code>options</code> prop. It sounds like you would want to output to something else, like a <code>div</code> or <code>p</code> component. You have a <code>display-v... | python|pandas|plotly-dash | 1 |
377,376 | 56,535,640 | In Python/Pandas, Check if a comma separated string contains any value in a list | <p>I have a column in pandas dataframe that looks like this:</p>
<pre><code>Code
----
ABC,DEF,XYZ
ABC,XYZ
...
...
CBA,FED,ABC
</code></pre>
<p>I'm trying to check if this series of comma separated string contains any string in my below list:</p>
<p>["UVW","XYZ"]</p>
<p>I know we can check single value like "XYZ" in... | <p>Use <code>pd.Series.str.contains</code> with <code>regex=True</code>:</p>
<p>Given <code>Series</code>, <code>s</code> and target list <code>l</code>:</p>
<pre><code>s
0 ABC,DEF,XYZ
1 ABC,XYZ
2 CBA,FED,ABC
l = ["UVW","XYZ"]
s.str.contains('|'.join(l))
</code></pre>
<p>Output:</p>
<pre><code>0 ... | python|pandas | 0 |
377,377 | 56,760,725 | pandas dataframe - ungroup concatenated column | <p>I am trying to ungroup a concatenated column in a dataframe. In particular, I am trying to convert</p>
<pre><code> a b c
i0 1 a k1;k2
i1 2 b k3
i2 3 c k4;k5;k6
i3 4 d k7
</code></pre>
<p>into</p>
<pre><code> a b c
i0 1 a k1
i0 1 a k2
i1 2 b k3
i2 3 c k4
i2 ... | <p>Here's an answer that is not in the linked (unnest) question:</p>
<pre><code>(df.reset_index()
.set_index(['index','a','b'])
.c.str
.split(';',expand=True)
.stack()
.reset_index(level=-1,drop=True)
.reset_index(level=(1,2))
)
</code></pre>
<p>Output:</p>
<pre><code> a b 0
index ... | pandas | 0 |
377,378 | 56,865,344 | How do I calculate the matthews correlation coefficient in tensorflow | <p>So I made a model with tensorflow keras and it seems to work ok. However, my supervisor said it would be useful to calculate the Matthews correlation coefficient, as well as the accuracy and loss it already calculates. </p>
<p>my model is very similar to the code in the tutorial here (<a href="https://www.tensorf... | <p>There is nothing out of the box but we can calculate it from the formula in a custom metric.</p>
<p>The basic classification link you supplied is for a multi-class categorisation problem whereas the Matthews Correlation Coefficient is specifically for <strong>binary</strong> classification problems.</p>
<p>Assumin... | python-2.7|tensorflow|machine-learning|tf.keras | 9 |
377,379 | 56,695,125 | How do I compute one hot encoding using tf.one_hot? | <p>I'm trying to build a one hot encoding of y_train of <strong>mnist</strong> data-set using <strong>tensorflow</strong>. I couldn't understand how to do it?</p>
<pre><code># unique values 0 - 9
y_train = array([5, 0, 4, ..., 5, 6, 8], dtype=uint8)
</code></pre>
<p>In <code>keras</code> we'll do something like</p>
... | <p>I'm not familiar with Tensorflow but after some tests, this is what I've found:</p>
<p><code>tf.one_hot()</code> takes an <code>indices</code> and a <code>depth</code>. The <code>indices</code> are the values to actually convert to a one-hot encoding. <code>depth</code> refers to the maximum value to utilize.</p>
... | python|tensorflow | 4 |
377,380 | 56,793,367 | How to train tiny yolov2 with tensorflow? | <p>I really don't know much about machine learning. I just downloaded tensorflow sharp plugin for unity and tried it with a pre-trained yolov2 model. Now, I want to train my own model to detect a certain kind of object.</p>
<p>I'm really feel like an alien. What should I do? Do I have to learn 'tensorflow' ? What "tra... | <p>Ok. For newbies like me, here is what you have to do: </p>
<p>YoloV2 algorithm written in Darknet. Darknet is an open source neural network framework written in C and CUDA. If you want to use YoloV2 with unity tensorflowsharp plugin, you need a Tensorflow implementation of YoloV2. </p>
<p>And <a href="https://git... | tensorflow|yolo|tensorflowsharp | 1 |
377,381 | 56,598,749 | Input shape in keras (This loss expects targets to have the same shape as the output) | <p>this is my first time using keras, I'm trying to follow a tutorial I've found online and fit my own data to it. I have a matrix and binary labels.</p>
<pre><code>> str(d_train)
num [1:1062, 1:180] -0.04748 0.04607 -0.05429 -0.0126 -0.00219 ...
> str(trainlabels)
num [1:1062, 1:2] 0 0 0 0 0 0 1 0 0 0 ...
</c... | <p>I am not an R expert, but here:</p>
<pre><code>layer_dense(units = 3, activation = "softmax")
</code></pre>
<p>You are telling Keras that the output of your network has three classes. Your labels have shape <code>(1062, 2)</code> which suggest it has two classes, hence there is an inconsistency.</p>
<p>You could ... | r|tensorflow|keras|neural-network | 17 |
377,382 | 56,727,860 | How to fix the fetch argument error in implementing Bayesian Neural Network with tenssorflow | <pre><code>placeholder_X = tf.placeholder(tf.float32, shape = [None, 19])
placeholder_y = tf.placeholder(tf.float32, shape = [None,1])
#Build an iterator over training batches
#training_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train))
training_dataset = tf.data.Dataset.from_tensor_slices((placeholder_X,... | <p>The exception arises because you use same name f1 as assignment, we need to change name f1 at left side. </p>
<pre><code> test_value, precision_value, recall_value, fpr_value, tpr_value,f1 = sess.run([test_accuracy, precision, recall, fpr, tpr,f1],feed_dict={handle: test_string})
</code></pre>
<p>change the lin... | tensorflow | 0 |
377,383 | 56,623,173 | How can I train a neural network with weights constrained to specific values? | <p>I am trying to train a network with weights that can only have certain values. However, the way that I am doing this takes a very long time, e.g. 5h per epoch for a 3-layered fully connected network on MNIST. Is there a faster way to do this?</p>
<p>I am using tf.keras for building my network. I added a custom tf.c... | <p>From your description it seems, that some part of the clipping op gets executed on CPU which requires RAM-VRAM communication which is <em>extremely</em> slow.</p>
<p>However, if you are trying to do the traditional NN quantization, there is actually a whole TF module built for this purpose, you may want to check it... | tensorflow | 0 |
377,384 | 56,767,246 | How to wrap tf.cond function with keras.layers.Lambda? | <p>I'm trying to define a custom layer in keras,but I can't find a way to warp tf.cond with layers.Lambda function</p>
<pre class="lang-py prettyprint-override"><code> matches = tf.cond(
tf.greater(N, 0),
lambda: match_boxes(
anchors, groundtruth_boxes,
po... | <p>Since the body of your true function is very big, you could create a custom layer like this:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
class CustomLayer(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super(CustomLayer, self).__init__()
self.pred = kwargs.get('pre... | python|tensorflow|keras | 1 |
377,385 | 56,855,877 | Create interactive plot by IPywidgets in Jupyter notebook | <p>I am trying to create an interactive bar plot.
I have the following dataframe:</p>
<p>CustID| Age |Gender|Smoking_history |Alcohol_history</p>
<hr>
<p>1 |18-24| M | Non-smoker | <21 units per week</p>
<p>2 |43-48| F | Non-smoker | <21 units per week</p>
<p>3 ... | <p>I believe you just need to add connected=True inside of init_notebook_mode: <a href="https://plot.ly/python/offline/" rel="nofollow noreferrer">plotly offline docs</a></p>
<pre><code>init_notebook_mode(connected=True)
</code></pre> | python|pandas|jupyter-notebook|plotly|ipywidgets | 0 |
377,386 | 56,625,762 | Issues with custom scorer | <p>I am doing some online lessons in machine learning, and we use the following scoring function in our DNN models for regression:</p>
<pre><code> def r_squared(y_true, y_pred):
# 1 - ((y_i - y_hat_i)^2 / (y_i - y_sum)^2)
numerator = tf.reduce_sum(tf.square(tf.subtract(y_true, y_pred)))
den... | <p>The problem is mixing the usage of TensorFlow/Keras and scikit-learn. A Keras metric needs to be implemented using <code>keras.backend</code> functions, but scikit-learn functions are not symbolic and have to be implemented using numpy.</p>
<p>Fortunately scikit-learn already has an implementation of the R^2 score ... | python|tensorflow|keras|scikit-learn|deep-learning | 1 |
377,387 | 56,464,356 | What is the equivalent in Tensorflow 2.0 of tf.contrib.framework.nest.flatten_dict_items()? | <p>I'm upgrading TF1 code to TF2 with the tf_upgrade_v2, and I found this message:</p>
<pre><code>tf.contrib.framework.nest.flatten_dict_items(dict)
AttributeError: module 'tensorflow' has no attribute 'contrib'
</code></pre>
<p>How I should update the code? I didn't find a solution.</p> | <p>This one is a little odd (hard to find) because it's not exported in the same way as the core functionality.</p>
<p>cs95 is correct in his comment in as much that it lives in <code>tensorflow.python.util.nest</code> but one cannot simply do:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as ... | python|tensorflow|tensorflow2.0 | 1 |
377,388 | 56,822,357 | How to shortern numpy code used for extraction | <p>I am writing 29 lines of extraction codes for my data extraction. Is there anyway I can shorten my code? </p>
<pre><code>import numpy as np
from numpy.lib.recfunctions import append_fields
import matplotlib.pyplot as plt
data_y = np.genfromtxt('data/housing-and-development-board-resale-price-index-1q2009-100-quart... | <pre><code>year_data = {year: data_y[data_y['year']==year] for year in np.unique(data_y['year'])}
</code></pre> | python|python-3.x|numpy | 1 |
377,389 | 56,734,378 | Difference between weighted accuracy metric of Keras and Scikit-learn | <h3>Intro</h3>
<p>Hej everyone, </p>
<p>I am working on my diploma thesis and I face a binary classification problem with imbalanced class contribution. I have around 10 times more negative ("0") labels as positive ("1") labels. For that reason I considered not only observing accuracy and ROC-AUC, but also weighted/ ... | <p>I repeated your exact toy example and actually found that <code>sklearn</code> and <code>keras</code> do give the same results. I repeated the experiment 5 times to ensure it wasn't by chance and indeed the results were identical each time. For one of the runs for example:</p>
<pre><code>sklearn_accuracy=0.831
skle... | python|tensorflow|keras|deep-learning | 0 |
377,390 | 56,790,402 | Unsatisfiable error while installing tensorflow-gpu in Anaconda | <p>I have installed Anaconda Python 3.7 in Ubuntu 18.04 and then executed the commands:</p>
<pre><code>conda update --all
conda install cudnn
</code></pre>
<p>Now when I try to install tensorflow-gpu using the command <code>conda install tensorflow-gpu</code>, I get Unsatisfiable error like this:</p>
<blockquote>
... | <p>You can install Tensorflow GPU using the below code:</p>
<ol>
<li><p>Create a New Virtual Environment</p>
<p><code>conda create -n tensorflow_gpu pip python=3.6</code></p></li>
<li><p>Activate the Virtual Environment</p>
<p><code>activate tensorflow_gpu</code></p></li>
<li><p>Install CUDA Toolkit using </p>
<p><... | python|tensorflow|anaconda | 0 |
377,391 | 56,571,746 | I need some help for a keras image classifier project | <p>I've been doing this imager and it does not compile. The document of training if it works well but the document to predict the image does not.</p>
<p>It consists of an image classifier based on these videos.</p>
<p><a href="https://www.youtube.com/watch?v=EAqb20_4Rdg&t=450s" rel="nofollow noreferrer">https://w... | <p>You are mixing <code>keras</code> and <code>tf.keras</code> by training your model using <code>tf.keras</code> and then loading it in <code>keras</code>. This won't work because both frameworks are not compatible in that way.</p>
<p>Choose one implementation and use it completely, do not mix them.</p> | python|image|tensorflow|keras|classification | 1 |
377,392 | 56,863,821 | For loops to iterate through two lists in an sql query, one of these lists is made up of smaller lists | <p>I have large databases for which I am using an sql query in python to write the data to csv files. In the sql database each row is a series of spatial information for a finger ID. I can parametize the query to get the information and write the files I need for each finger. However, the problem arises in creating a f... | <p>The problem is here:</p>
<blockquote>
<p>However for each FINGER value it is iterating over the entire INDEX list</p>
</blockquote>
<p>And it is caused by this loops:</p>
<pre><code>for Y in FINGER:
for X in INDEX:
# whatever
</code></pre>
<p>In this case <code>whatever</code> will be executed for ... | python|pandas|python-2.7|sqlite | 0 |
377,393 | 56,813,078 | Fill column with conditional mode of another column | <p>Given the below list, I'd like to fill in the 'Color Guess' column with the mode of the 'Color' column conditional on 'Type' and 'Size' and ignoring NULL, #N/A, etc.</p>
<p>For example, what's the most common color for SMALL CATS, what's the most common color for MEDIUM DOGS, etc.</p>
<blockquote>
<pre><code>Type ... | <p>As BarMar already stated in the comments, we can use <code>pd.Series.mode</code> here from the linked answer. Only trick here is, that we have to use <code>groupby.transform</code>, since we want the data back in the same shape as your dataframe:</p>
<pre><code>df['Color Guess'] = df.groupby(['Type', 'Size'])['Colo... | python|pandas | 5 |
377,394 | 56,860,202 | Converting numpy64 objects to Pandas datetime | <p>Question is pretty self-explanatory. I am finding that <code>pd.to_datetime</code> isn't changing anything about the object type and using <code>pd.Timestampe()</code>directly is bombing out.</p>
<p>Before this is marked a duplicate of <a href="https://stackoverflow.com/questions/13703720/converting-between-datetim... | <p>The method you mentioned <code>pandas.to_datetime()</code> will work on scalars, Series and whole DataFrame if you need, so:</p>
<pre><code>dataFrame['column_date_converted'] = pd.to_datetime(dataFrame['column_to_convert'])
</code></pre> | python|pandas|numpy | 1 |
377,395 | 56,474,361 | Eigen decomposition of two square matrix in python | <p>In matlab we have option to find eigen decomposition of two matrix, no matter there product is symmetric or non symmetric such as</p>
<pre><code>A = [1 3; 4 9];
B = [4 7; 9 16];
[Vec,Val]=eig(A,B)
</code></pre>
<p>Vectors are</p>
<pre><code>`[-1,-1;0.54,0.85]`
</code></pre>
<p>and value are</p>
<pre><code>[-3... | <p>You can use <a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.linalg.eig.html" rel="nofollow noreferrer">scipy.linalg.eig</a>: </p>
<pre><code>from scipy import linalg
linalg.eig(A, B)
</code></pre>
<p>where <code>A = [[1,3],[4,9]]</code> and <code>B = [[4,7], [9,16]]</code> are your two m... | python|numpy|eigenvalue|eigenvector | 1 |
377,396 | 56,607,794 | tf.set_random_seed doesn't seem to set the seed correctly | <p>I encountered a problem that <code>tf.set_random_seed</code> is unable to generate a repeatable value when programming using Tensorflow on python. To be specific, </p>
<pre><code>import tensorflow as tf
sd = 1
tf.set_random_seed(seed = sd)
tf.reset_default_graph()
sess = tf.InteractiveSession()
print(sess.run(tf.r... | <p><a href="https://www.tensorflow.org/api_docs/python/tf/random/set_random_seed" rel="nofollow noreferrer">According to the docs</a>, there are two types of seeds you can set when defining graph operations:</p>
<ol>
<li>The graph-level seed, which is set by <code>tf.set_random_seed</code>, and </li>
<li>operation-lev... | python|tensorflow|random | 2 |
377,397 | 56,571,609 | Downsample numpy array while preserving distribution | <p>I'm trying to write a function that can randomly sample a <code>numpy.ndarray</code> that has floating point numbers while preserving the distribution of the numbers in the array. I have this function for now:</p>
<pre><code>import random
from collections import Counter
def sample(A, N):
population = np.zeros(... | <pre><code>In [67]: a = np.array([1.94, 5.68, 2.77, 7.39, 2.51])
In [68]: np.zeros(sum(a))
---------------------------------------------------------------------------
TypeError ... | python|python-3.x|numpy|random|probability | 1 |
377,398 | 56,675,101 | Python pandas: Setting index value of dataframe to another dataframe as a column using multiple column conditions | <p>I have two dataframes: <code>data_df</code> and <code>geo_dimension_df</code>. </p>
<p>I would like to take the index of <code>geo_dimension_df</code>, which I renamed to <code>id</code>, and make it a column on <code>data_df</code> called <code>geo_id</code>.</p>
<p>I'll be inserting both of these dataframes as t... | <p>First, because the index is not a proper column, make it a column so that it can be used in a later <code>merge</code>:</p>
<pre><code>geo_dimension_df['geo_id'] = geo_dimension_df.index
</code></pre>
<p>Next, join <code>data_df</code> and <code>geo_dimension_df</code></p>
<pre><code>data_df = pd.merge(data_df,
... | python|python-3.x|pandas | 1 |
377,399 | 56,712,422 | How to generate every combination of a given pattern in numpy array? | <p>I have a constraint variable based on which I need to generate every combination possible in a numpy array.</p>
<pre><code> length = 12
x >= 4 , x <= 7
Solution:
array([[0,0,0,0,0,0,0,0,1,1,1,1],
[0,0,0,1,1,1,1,1,1,0,0,0],
..... <every possible combination>
])
## I tried the be... | <p>I don't know any special function but test(...), below, runs in 149us on my machine. If you use the result a lot save it and copy from it as required.</p>
<pre><code>def n_ones_in_len( n_ones, length ):
""" Returns a diagonal with n ones offset by one column in each row. """
n_rows = length - n_ones + 1
... | python|python-3.x|numpy | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.