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
15,300
57,120,680
Deep copy of tensor in tensorflow python
<p>In some of my code, I have created a neural network using tensorflow and have access to a tensor representing that network's output. I want to make a copy of this tensor so that even if I train the neural network more, I can access the original value of the tensor.</p> <p>Following other answers and tensorflow docu...
<p>You can use a named <a href="https://www.tensorflow.org/api_docs/python/tf/assign" rel="nofollow noreferrer"><code>tf.assign</code></a> operation and then run only that operation via <a href="https://www.tensorflow.org/api_docs/python/tf/Graph#get_operation_by_name" rel="nofollow noreferrer"><code>Graph.get_operatio...
python|tensorflow|machine-learning|deep-learning
1
15,301
50,808,455
pandas how to get the date of n-day before monthend
<p>Suppose I have a dataframe, which the first column is the stock trading date. I represent the date with number for convenience here.</p> <pre><code>data = pd.DataFrame({'date': [1,2,3,1,2,3,4,1,2,3], 'value': range(1, 11)}) </code></pre> <p>I have another dataframe which contain the date of mo...
<p>I am using the <code>cumsum</code> with <code>groupby</code> </p> <pre><code>df1=data.groupby(data.date.eq(1).cumsum()).tail(1) df1 Out[208]: date value 2 3 3 6 4 7 9 3 10 df2=data.loc[df1.index-1] df2 Out[213]: date value 1 2 2 5 3 6 8 2 9 </code></pr...
python-3.x|pandas
1
15,302
66,710,190
Plotting multiple model costs
<p>I have created 3 models: sequential, conv and mix. I know how to plot each one by itself</p> <pre class="lang-py prettyprint-override"><code># Plots the training and validation loss over the number of epochs. plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model Loss') plt.ylabel('...
<p>You should use <code>history1.history</code>. history1 is the name of your variable and history is the name of its attribute.</p> <p>From the model.fit keras documentation:</p> <blockquote> <p>Returns: A History object. Its History.history attribute is a record of training loss values and metrics values at successiv...
python|tensorflow
0
15,303
66,395,670
tf.keras(tf2) problem: can't run custom gradient layers, OperatorNotAllowedInGraphError. May caused by tf.Keras API
<p>I've arranged my code on <a href="https://github.com/xiqxin1/dann-tf.keras-test" rel="nofollow noreferrer">github</a>(with avaiable dataset).</p> <p>The problem is that I want to implement an unsupervised domain adversarial training network (DANN) <a href="https://arxiv.org/abs/1505.07818" rel="nofollow noreferrer">...
<p>Now, I fixed the problem.</p> <p>Remove:</p> <p>from tensorflow.python.keras.engine.base_layer import Layer</p> <p>To</p> <p>from tensorflow.python.keras.layers import Layer</p> <p>But another error ocurrs:</p> <pre><code>InternalError: Recorded operation 'GradientReversalOperator' returned too few gradients. Expect...
deep-learning|tensorflow2.0|keras-layer|tf.keras|generative-adversarial-network
-1
15,304
57,528,350
Can You Consistently Keep Track of Column Labels Using Sklearn's Transformer API?
<p>This seems like a very important issue for this library, and so far I don't see a decisive answer, although it seems like for the most part, the answer is 'No.'</p> <p>Right now, any method that uses the <code>transformer</code> api in <code>sklearn</code> returns a <code>numpy</code> array as its results. Usually...
<p>Yes, you are right that there isn't a complete support for tracking the feature_names in <code>sklearn</code> as of now. Initially, it was decide to keep it as generic at the level of <code>numpy</code> array. Latest progress on the feature names addition to sklearn estimators can be tracked <a href="https://github....
python|pandas|scikit-learn
52
15,305
57,685,689
ENet sementic segmentation model is not working for smaller images
<p>I am trying to segment road and non-road part using ENet deep learning model. I uses this github link: <a href="https://github.com/kwotsin/TensorFlow-ENet" rel="nofollow noreferrer">https://github.com/kwotsin/TensorFlow-ENet</a> which has original image size of 340X480 and it's working fine for images of 340X480 or ...
<p>You can try this model. Its written in tf.keras</p> <pre><code> import tensorflow as tf from tensorflow.keras.layers import * from tensorflow.keras.models import Model print('Tensorflow', tf.__version__) def initial_block(inp): inp1 = inp conv = Conv2D(filters=13, kernel_size=3,...
python|tensorflow|deep-learning
0
15,306
72,908,352
Curve does not fit with the Histogram for Customize Function
<p>I am trying to fit a curve to a histogram, but the resulting curve is flat even though the histogram was not. How can I fit the curve correctly?</p> <p>My current code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit import pandas as pd import scipy.optimiz...
<p>You are getting bad results because the function you are using to fit the histogram doesn't look like the shape of the histogram at all. By using a simple second order interpolation function, the results are a lot better (though you might say not ideal):</p> <pre class="lang-py prettyprint-override"><code>def func(x...
python|numpy|matplotlib|scipy|curve-fitting
0
15,307
70,380,116
how to segregate monthly average data based on station wise using pandas?
<p>I have 30 years of data that has been collected from 385 stations. I would like to calculate the monthly average of all years according to individual stations and export it into a CSV file. I am very new to coding I don't know how to execute this. please help someone to sort out my issues .herewith I have enclosed t...
<p>I am assuming that your existing code works as intended and that you do not want to write the code for each of the 385 stations. This can be achieved in a simple for loop iterating over the station names:</p> <pre><code>for station in data[&quot;station_id&quot;].unique(): # selective column only ap= data[...
python|pandas
0
15,308
51,287,109
Simultaneous training and testing in Tensorflow
<p>I am trying to perform training and testing of a neural network in Tensorflow in the same script, same graph, same session. I read that it is possible, however when I look at the accuracy/loss results from the training and testing ops, it seems as if both ops are just a continuation of the training process somehow. ...
<p>The metrics in tf.metrics are stateful; they create variables to accumulate partial results in, so you shouldn't expect them to auto-reset. Instead use the metrics in <code>tf.contrib.metrics</code> or <code>tf.keras.metrics</code> and session.run the ops to reset them accordingly.</p>
python|tensorflow|neural-network|training-data
1
15,309
70,747,752
How to use GPU in Docker to retrain an object detection model?
<p>I've been following <a href="https://coral.ai/docs/edgetpu/retrain-detection/#set-up-the-docker-container" rel="nofollow noreferrer">this</a> tutorial from google coral on retraining an object detection model in docker, and it explicitly states that this is for CPU training only, which is very slow.</p> <p>Is there ...
<p>Answering myself to close the question as I see no way to do it on a comment, solution was a comment from sebastian-sz:</p> <p>&quot;tensorflow/tensorflow:1.15.5 is cpu only image, you should use tensorflow/tensorflow:1.15.5-gpu to use CUDA. – sebastian-sz Jan 21 at 14:36&quot;</p> <p>Thank you for your help.</p>
docker|tensorflow|ubuntu|google-coral
1
15,310
70,750,798
TensorFlow Lite model not working in Android (Java) but works on Python
<p><strong>Background</strong></p> <p>I successfully converted my YOLOV5 model from YOLOV5.pt to YOLOV5-fp16.tflite and was able to run it on python(refer to the <a href="https://drive.google.com/file/d/1xYB9O0IshZVlLJKSo3upcorJ1OGqK03v/view?usp=sharing" rel="nofollow noreferrer">test video on Google Drive</a>). I used...
<p>Your model output has shape [1, 6300, 6] not [1, 10, 4]. You will need to know what is the output of your model means and adjust the code correctly.</p>
java|android|android-studio|tensorflow-lite|yolov5
0
15,311
71,016,845
BiLSTM forward() - RuntimeError: shape '[-1, 38]' is invalid for input of size 1
<p>Goal: implement bidirectionality in LSTM.</p> <p>I'm new to Deep Learning and chose <code>pytorch-lightening</code> for minimal coding. Progress has been made, thanks to responses from prior posts.</p> <hr /> <p><code>forward()</code> now needs to facilitate <code>nn.LSTM(... bidirectional=True)</code>.</p> <p>I'm b...
<p>My problem was 2 things.</p> <p>One, I had to run <code>classifier()</code> before calculating <code>cross_entropy()</code>.</p> <p>Secondly, I had to pass <code>X</code>, <code>final_hidden_layer.flatten()</code>.</p> <pre class="lang-py prettyprint-override"><code>X = final_hidden_state # Push through lin...
python|pytorch|pytorch-lightning|bilstm
0
15,312
37,166,268
tflearn / tensorflow does not learn xor
<p>Following code was written to learn the XOR function, but about half of the time the network does not learn and the loss after each epoch stays the same.</p> <pre><code>train_f = [[0, 0], [0, 1], [1, 0], [1, 1]] train_c = [[0], [1], [1], [0]] test_f = train_f test_c = train_c import tensorflow as tf import tflearn...
<p>The network with <code>relu</code>s (as it is written in the code snippet) is expected to often fail to train. The reason for that is that if the input to relu is less than zero, the output is zero, and therefore the gradient going back is also zero.</p> <p>Since you have two layers, each having only two relu units...
python|machine-learning|tensorflow|deep-learning
10
15,313
42,061,854
Variable length input in Tensorflow
<p>The shape of input is <code>[batch_size, maxstep, 50, 50]</code>. And I want to use a certain cnn at each step to make it become <code>[batch_size, maxstep, 5 * 5 * 32]</code>. At first glance, I think I should use <code>while_loop</code>.</p> <p>But it is difficult to build this graph, the "maxstep" and "batch_siz...
<p>With <a href="https://stackoverflow.com/users/6824418/allen-lavoie">AllenLavoie</a>'s help, I finally solved this problem.</p> <p>First I pad the input's shape <code>[batch_size, variable_step_len, 50, 50]</code> into <code>[batch_size, max_step_len, 50, 50]</code>, and then reshape it into <code>[batch_size*max_st...
tensorflow
0
15,314
7,760,658
PyArg_ParseTuple SegFaults in CApi
<p>I am writing a code, trying to get used to the C API of NumPy arrays. </p> <pre><code>#include &lt;Python.h&gt; #include "numpy/arrayobject.h" #include &lt;stdio.h&gt; #include &lt;stdbool.h&gt; static char doc[] = "Document"; static PyArrayObject * trace(PyObject *self, PyObject *args){ PyArrayObject *...
<p>From <a href="http://docs.python.org/c-api/arg.html" rel="nofollow noreferrer">the docs</a>:</p> <blockquote> <p><code>O</code> (object) [PyObject *]<br /> Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. <strong>The object’s referen...
python|numpy|python-c-api
1
15,315
37,757,555
Sum numpy array values based on labels in a separate array
<p>I have arrays similar to the following:</p> <pre><code>a=[["tennis","tennis","golf","federer","cricket"], ["federer","nadal","woods","sausage","federer"], ["sausage","lion","prawn","prawn","sausage"]] </code></pre> <p>I then have a matrix of the following weights</p> <pre><code>w=[[1,3,3,4,5], [2,3,2,3,4...
<p>See <a href="https://stackoverflow.com/a/37757740/2607571">piRSquared answer</a> for numpy arrays.</p> <p>This is a pure python approach:</p> <pre><code>for i in range(4): if a[i].count(a[i][0]) == len(a[i]): res = [a[1][0], "", ""] else: res = [x[0] for x in sorted(zip(a[i], w[i]), key=lam...
python|numpy
3
15,316
37,725,195
Pandas - Replace values based on index
<p>If I create a dataframe like so:</p> <pre><code>import pandas as pd, numpy as np df = pd.DataFrame(np.random.randint(0,100,size=(100, 2)), columns=list('AB')) </code></pre> <p>How would I change the entry in column A to be the number 16 from row 0 -15, for example? In other words, how do I replace cells based purel...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="noreferrer"><code>loc</code></a>:</p> <pre><code>df.loc[0:15,'A'] = 16 print (df) A B 0 16 45 1 16 5 2 16 97 3 16 58 4 16 26 5 16 87 6 16 51 7 16 17 8 16 39 9 16 73 10 16 94 11 ...
python|numpy|pandas|replace|dataframe
79
15,317
37,647,564
Performance of single segment operation vs multiple operations on segments
<p>Since currently there is no easy way to profile TensorFlow operations (<a href="https://stackoverflow.com/questions/34293714/tensorflow-can-i-measure-the-execution-time-of-individual-operations">Can I measure the execution time of individual operations with TensorFlow?</a>), can anyone help me understand the benefit...
<p>I've updated the SO question you link to with some information about CPU inference profiling tools we've recently released at: <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/tools/benchmark" rel="nofollow">https://github.com/tensorflow/tensorflow/tree/master/tensorflow/tools/benchmark</a></...
python|tensorflow
0
15,318
37,982,170
Pandas reindex and fill missing values: "Index must be monotonic"
<p>In answering <a href="https://stackoverflow.com/questions/37981678/how-to-align-indexes-of-many-dataframes-and-fill-in-respective-missing-values-in">this stackoverflow question</a>, I found some interesting behavior when using a fill method while reindexing a dataframe.</p> <p>This <a href="https://github.com/pydat...
<p>It seems that this needs to be done on the columns as well.</p> <pre><code>In[76]: frame = DataFrame(np.arange(9).reshape((3, 3)), index=['a', 'c', 'd'],columns=['Ohio', 'Texas', 'California']) In[77]: frame.reindex(index=['a','b','c','d'],method='ffill',columns=states) ---&gt; ValueError: index must be monotonic ...
python|pandas|reindex
3
15,319
37,713,642
Reading a JSON in python and converting it to dataframe
<p>Suppose I have a JSON file as follows,</p> <pre><code>{u'level': u'INFO', u'message': {"method":"someMethod","params":{"frameId":"9.6","loaderId":"3.2","requestId":"4.6"}} u'timestamp': 654789L} </code></pre> <p>For parsing this into dataframe, for the first level, I am able to do <code>data[1]['level']</code>, <...
<p>You can use <code>pandas.read_json</code> this will automatically read the file into a DataFrame. </p> <pre><code>import pandas as pd data = pd.read_json('test.json') </code></pre> <p>but the data you show in the question is not in valid JSON format. For the correct format please see this <a href="http://www.w3sc...
python|json|pandas
0
15,320
31,274,136
How do I make a list
<p>So I want to generate a population (N) of individuals with a genome of length (genomelength), where their genome consists of '0s', '1s' and '?s' I use the code below and it works how I need I to work:</p> <pre><code>import random import numpy as np def generate_individual(genomelength): individual = '' fo...
<p>You can use <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">list comprehension</a> -</p> <pre><code>lst = [generate_individual(10) for _ in range(N)] #You will need to define N before (or use a constant) print lst </code></pre> <p>You do not need to create a list of empty strin...
python|arrays|list|python-2.7|numpy
4
15,321
31,619,880
Is it possible to install python libraries such as Numpy, Scipy, Pandas and Matplotlib and statsmodels into Eclipse
<p>I'm trying to add these libraries into Eclipse.(Numpy, Scipy, Pandas and Matplotlib and statsmodels) I've already installed python 2.7. If so, can someone tell me how?</p>
<p>Open the windows command prompt or cmd (not the python prompt) In the cmd run the command:</p> <pre><code> pip install numpy pip install pandas pip install matplotlib pip install scipy </code></pre> <p>Once installed, they are available in eclipse</p>
python|eclipse|numpy|pandas|scipy
1
15,322
64,185,685
Extract row data from dictionary if dataframes based on filter on a column value
<p>The dictionary dict_set has dataframes as the value for their keys.</p> <p>I'm trying to extract data from a dictionary of dataframes based on a filter on 'A' column in the dataframe based on the value in column.</p> <pre><code>dict_set={} dict_set['a']=pd.DataFrame({'A':[1,2,3],'B':[1,2,3]}) dict_set['b']=pd.DataFr...
<p>Try this:</p> <pre><code>pd.concat([df.query(&quot;A == 1&quot;) for df in dict_set.values()], keys=dict_set.keys())\ .reset_index(level=0)\ .rename(columns={'level_0':'x'}) </code></pre> <p>Output:</p> <pre><code> x A B 0 a 1 1 0 b 1 1 </code></pre> <p><em><strong>Details:</strong></em></p> <p>Let's g...
python|pandas|dataframe|dictionary|concatenation
0
15,323
49,040,742
pandas dropna not working as expected on finding mean
<p>When I run the code below I get the error:</p> <p>TypeError: 'NoneType' object has no attribute '<strong>getitem</strong>'</p> <pre><code> import pyarrow import pandas import pyarrow.parquet as pq df = pq.read_table("file.parquet").to_pandas() df = df.iloc[1:,:] df = df.dropna (how="any", ...
<p>This will work, also if you the NA in your df is NaN (np.nan), this will not affect your getting the mean of the column, only if your NA is 'NA', which is string</p> <pre><code>(df.apply(pd.to_numeric,errors ='coerce',axis=1)).describe() Out[9]: _c0 _c1 _c2 count 3.0 0.0 2.000000 mean 2.0 Na...
python|pandas
1
15,324
58,715,093
setup.py doesn't find tensorflow==2.0 dependency (found tensorflow==2.0.0b0)
<p>I have a package that has a <code>setup.py</code> configuration with the <code>tensorflow==2.0</code> dependency. I install it with <code>python setup.py develop</code>.</p> <p>It used to be the <code>tensorflow==2.0.0b0</code> version and it worked fine. I just tried to upgrade to the officially released version (...
<p>The version is named <a href="https://pypi.org/project/tensorflow/#history" rel="nofollow noreferrer">2.0.0</a> so try</p> <pre><code>tensorflow==2.0.0 </code></pre>
tensorflow|setuptools|setup.py|tensorflow2.0
1
15,325
70,313,860
Multiple if conditions on pandas dataframe with different thresholds
<p>I have a dataframe with several parameters:</p> <pre><code>par1 par2 par3 par4 par5 1.122208 1.054132 1.133250 1.114845 1.183850 1.076445 1.128663 0.998518 1.081816 1.006934 1.077058 1.561871 1.045255 1.120456 1.768667 0.904869 1.183985 0.938095 0.927841 1.201934 0.876596 ...
<p>Using Kelvin Ducray's sample data, we can take the solution a step further, to avoid the for-loop/apply, and use Pandas' vectorized operations, which should be faster:</p> <pre class="lang-py prettyprint-override"><code>thresholds = pd.Series(thresholds) # compare df with thresholds # sum accross the booleans # che...
python|pandas
4
15,326
70,330,054
TypeError: pandas._libs.tslibs.period.PeriodMixin.__new__(PeriodArray)
<p>I am getting the following error when trying to unpickle an ARIMA model I had made.</p> <pre><code>Traceback (most recent call last): File &quot;app.py&quot;, line 42, in &lt;module&gt; loaded_model = joblib.load('./models/arima2.model') File &quot;/Users/sparshbohra/Desktop/adsl/cb/server/cb_analytics_venv/...
<p>I faced the same problem and i didn't find solution so i used pickel package to solve this problem</p> <pre class="lang-py prettyprint-override"><code># Import pickle Package import pickle # Save the Modle to file in the current working directory Pkl_Filename = &quot;Pickle_RL_Model.pkl&quot; with open(Pkl_Filen...
python|pandas|pickle|statsmodels|arima
0
15,327
70,281,985
Why is np.shape not showing all dimensions?
<p>I have a pandas column storing a np array in each row. The df looks like this:</p> <pre><code>0 [38, 324, -21] 1 [41, 325, -19] 2 [41, 325, -19] 3 [42, 326, -20] 4 [42, 326, -19] </code></pre> <p>I want to convert this column into a np array so I can use it as training data for a model. I convert it t...
<p>You can take a look at what df.c.values actually is by seeing what the output is:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame() df['c'] = [np.random.randint(0, 10, 3) for i in range(5)] </code></pre> <pre><code>In [2]: df Out[2]: c 0 [-80, 4, -84] 1 [88, 32, 85] 2 [-11, 71, 37]...
python|pandas|numpy
2
15,328
56,309,793
getting ValueError: Outputs of true_fn and false_fn must have the same type: int32, float32 while using tf.histogram_fixed_width_bins
<p>Hope someone can help me with this or point me some hint/ideas I can fix this error.</p> <p>I am trying to create a custom layer in SeqtoSeq model.I need to call the histogram in part of my code. however, when it touches this line of the code it raises an error:</p> <pre><code>ValueError: Outputs of true_fn and fa...
<p><code>K.in_train_phase</code> requires that <code>self.rev_entropy(x, self.beta,self.batch)</code> and <code>x</code> must have the same type in this case. But <code>tf.histogram_fixed_width_bins</code> returns <code>int32</code> when your <code>x</code> is <code>float32</code>. So you need to change type.</p> <pr...
tensorflow|keras|deep-learning|lstm|stat
1
15,329
55,904,116
Pandas dataframe filtering after groupby with irregular time series
<p>I have a DataFrame with a time series indexed by a timestamp, like this:</p> <pre><code>timestamp A B 2018-11-12 14:03:53 9.45 501.0 2018-11-12 14:03:58 73.8 108.0 2018-11-12 14:04:09 4.25 215.0 2018-11-12 14:04:19 62.39 551.0 2018-11-12 14:04:29 15.98 113.0 </code></pr...
<p>Try using <code>.dt.floor</code>:</p> <pre><code>df.groupby(df['timestamp'].dt.floor('30Min')).apply(custom_agg) </code></pre>
python|pandas|dataframe|pandas-groupby
2
15,330
55,827,957
Converting a single row into two
<p>I have this daily stats churned out from a system which outputs total sales and units sold per region group. For my analysis, I want to breakdown the entries into regions instead of region group. I'm trying to look for a way to split each row into per region with the respective measures. </p> <p>I have historical p...
<p>Well, first of all, when you're doing DS researches try to find the most appropriate way in your personal case. There's nothing bad in using all Excel functionality to solve your issue, scripting, etc.</p> <p>However, if you really-really want to use pandas, then what I would do in your case - just .append() and th...
python|pandas
0
15,331
44,009,609
Kaggle TypeError: slice indices must be integers or None or have an __index__ method
<p>I am trying to plot a seaborn histogram on a <a href="http://www.kaggle.com" rel="noreferrer">Kaggle</a> notebook in this way:</p> <pre><code> sns.distplot(myseries, bins=50, kde=True) </code></pre> <p>but I get this error:</p> <pre><code>TypeError: slice indices must be integers or None or have an __index__ meth...
<p>As @ryankdwyer pointed out, it was an <a href="https://github.com/mwaskom/seaborn/issues/1092" rel="noreferrer">issue</a> in the underlying <code>statsmodels</code> implementation which is no longer existent in the <code>0.8.0</code> release.</p> <p>Since kaggle won't allow you to access the internet from any kerne...
python|pandas|jupyter|seaborn|kaggle
6
15,332
69,305,313
Why is gpu device used not consistent with log info?
<p>My machine have 4 GPUs, and when I run the code, at the beginning I already set:</p> <pre><code>import os os.environ[&quot;CUDA_VISIBLE_DEVICES&quot;] = &quot;1&quot; </code></pre> <p>Through nvidia-smi command I can see that gpu 1 is actually used. However, the tensorflow log on the terminal shows that gpu 0 is use...
<ol> <li><p>the <code>CUDA_VISIBLE_DEVICES</code> environment variable <em>remaps</em> whichever devices you select so that with respect to your CUDA process, those devices (in your list) appear to CUDA as if they started at zero. So when you do:</p> <pre><code>os.environ[&quot;CUDA_VISIBLE_DEVICES&quot;] = &quot;1&qu...
tensorflow|cuda|gpu|tensorflow2.0
1
15,333
69,585,858
Installing pandas with dockerfile for ARM/V7 architecture gets stuck
<p>I want to build a Docker Image based on a Python 3.8 Image and then install some requirements including Pandas on a ARM/V7 platform. But when it comes to install the pip requirements the process gets stuck.</p> <p>Is there any way to use a different base image or change something else in the Docker file to run panda...
<p>I guess it takes time for compiling... Just use precompiled packages from <a href="https://piwheels.org/" rel="nofollow noreferrer">https://piwheels.org/</a></p> <pre><code>RUN pip install --index-url=https://www.piwheels.org/simple --no-cache-dir -r requirements.txt </code></pre>
pandas|docker|pip|arm
1
15,334
69,349,441
"No such file or directory exist", but it obviously does
<p>I'm trying to import multiple excel files to a DataFrame but I get the error: FileNotFoundError: [Errno 2] No such file or directory: 'test1.xlsx'</p> <p>The code:</p> <pre><code>path=os.getcwd() files = os.listdir(path+&quot;/testimport&quot;) df = pd.DataFrame() for f in files: data = pd.read_excel(f, ...
<p>You should provide the full path (including the directory names) for the input files. Currently, you are only providing the file names. So, the read line should be something like below:</p> <pre class="lang-py prettyprint-override"><code>data = pd.read_excel(os.path.join(path, &quot;testimport&quot;, f), sheet_name ...
python|pandas|import-from-excel
2
15,335
69,544,825
Convert GroupBy object to Dataframe (pandas)
<p>I am working with a large dataset which I've stored in a pandas dataframe. All of my methods I've written to operate on this dataset work on dataframes, but some of them don't work on GroupBy objects.</p> <p>I've come to a point in my code where I would like to group all data by author name (which I was able to achi...
<p>Not exactly sure I understand, so if this isn't what you are looking for, please comment.</p> <p>Creating a dataframe:</p> <pre><code>df = pd.DataFrame({'author':['gatsby', 'king', 'michener', 'michener','king','king', 'tolkein', 'gatsby'], 'b':range(13,21)}) author b 0 gatsby 13 1 king 14 2 miche...
python|pandas|dataframe|pandas-groupby
0
15,336
69,389,393
How to find four points from the binary image?
<p>I have an image like following, I want to find four coordinate (corners) from this image.</p> <p>I have tried with below code:</p> <pre><code># dilate thresholded image - merges top/bottom kernel = np.ones((3,3), np.uint8) dilated = cv2.dilate(img, kernel, iterations=3) # Finding contours for the thresholded image ...
<p>I have found your points by putting a regression line threw each of your sides and taking their interception points.</p> <p>First I import stuff and find the contour points with open cv.</p> <pre><code>import numpy as np import cv2 import matplotlib.pyplot as plt from scipy.stats import linregress from sympy import ...
python|numpy|opencv
4
15,337
54,031,195
how to append a dataframe to an existing dataframe inside a loop
<p>I made a simple DataFrame named <code>middle_dataframe</code> in python which looks like this and only has one row of data: <a href="https://i.stack.imgur.com/bLfnt.png" rel="nofollow noreferrer">display of the existing dataframe</a> And I want to append a new dataframe generated each time in a loop to this existing...
<p>The <code>DataFrame.append</code> method <em>returns</em> the result of the append, rather than appending in-place (<a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html" rel="nofollow noreferrer">link to the official docs on <code>append</code></a>). The fix should be to repla...
python|pandas|dataframe|append
0
15,338
54,190,053
InvalidArgumentError (see above for traceback): Tensor must be 4-D with last dim 1, 3, or 4, not [5,100,100,120]
<p>In <a href="https://www.tensorflow.org/api_docs/python/tf/summary/image" rel="nofollow noreferrer">tf.summary.image</a>, max_outputs=3. I want to visualize the output of a convolution layer where max_output is 100. In this case tf.summary.image is not working. Please suggest how can I visualize all feature maps(=100...
<p>Below is the solution to the above problem. The answer is taken from the <a href="https://gist.github.com/panmari/4622b78ce21e44e2d69c" rel="nofollow noreferrer">Reference</a></p> <p>Here, channels = 120; img_size = 100</p> <pre><code>with tf.variable_scope('conv2'): V = tf.slice(conv2, (0, 0, 0, 0), (1, -1, -...
python-3.x|tensorflow|tensorboard
1
15,339
54,178,193
Python - Pandas library returns wrong column values after parsing a CSV file
<ul> <li><strong>SOLVED</strong> Found the solution by myself. Turns out that when you want to retrieve specific columns by their names you should pass the names in the order they appear inside the csv (which is really stupid for a library that is intended to save some parsing time for a developer IMO). Correct me if I...
<p>You can select column by name wise.Just use following line</p> <pre><code>values = parsed_csv[["Column Name","Column Name2"]] </code></pre> <p>Or you select Index wise by </p> <pre><code>cols = [1,2,3,4] values = parsed_csv[parsed_csv.columns[cols]] </code></pre>
python|pandas|csv
0
15,340
66,021,921
How to write the following code more efficiently?
<p>Any efficient way to write the following loop? dataPLprocessed is a time-series data and I want to calculate the score based on rolling 7 days percentile value (see the loop below for more explanation).</p> <pre><code>dataPLprocessed['percentile'] = dataPLprocessed['lineardifference'].rolling('7D').apply(lambda x: x...
<p>One possibility would be to generate the percentiles dynamically, and check for the complement, e.g., <code>x not between 0.05 and 0.95</code>:</p> <pre class="lang-py prettyprint-override"><code>for i in range(len(dataPLprocessed)): x = dataPLprocessed['percentile'][i] for k in range(10): p = round(...
python|pandas|time-series
1
15,341
65,927,793
Still getting SettingWithCopyWarning after using iloc. Where does it come from?
<p>I am getting a the SettingWithCopyWarning message.</p> <blockquote> <p>/usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py:670: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame</p> <p>See the caveats in the documentation: <a href="https://pandas.pydata.org/pandas-...
<p><code>data.rate</code> and <code>data.alert</code> is short for <code>data['rate']</code> and <code>data['alert']</code>, respectively. <code>data['rate']</code> <em>can</em> be copy so doing <code>data['rate'].iloc[i]</code> is still a copy.</p> <p>Change those to be like:</p> <pre><code>data.iloc[i, data.columns.g...
python|pandas
0
15,342
52,879,690
statement based on whether string field starts with number
<p>I have a pandas dataframe with two street address columns. I would like to check the value in each column to see if it starts with a number. Then I want to create a third column that returns the field value that starts with a number. </p> <p>Consider the following df:</p> <pre><code>df = pd.DataFrame({"A":["123 Fa...
<p>You need to use the <code>.str</code> method to slice each cell value as a string rather than slicing the column as a whole.</p> <p>Then to handle the case where neither column value starts with a digit, you need to add this additional condition.</p> <p>Here's an example:</p> <pre><code>a_is_digit = df.A.str[0].s...
python|python-3.x|pandas|if-statement
3
15,343
52,689,010
pandas - how to extract top three rows from the dataframe provided
<p>My pandas Data frame df could produce result as below:</p> <pre><code>grouped = df[(df['X'] == 'venture') &amp; (df['company_code'].isin(['TDS','XYZ','UVW']))].groupby(['company_code','sector'])['X_sector'].count() </code></pre> <p>The output of this is as follows:</p> <pre><code>company_code sector ...
<p>You will have to chain a groupby here. Consider this example:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(111) names = [ 'Robert Baratheon', 'Jon Snow', 'Daenerys Targaryen', 'Theon Greyjoy', 'Tyrion Lannister' ] df = pd.DataFrame({ 'season': np.random.randint(1, ...
python|pandas|pandas-groupby
4
15,344
58,453,829
Replace text of a URLwith Python
<p>How can i replace the text of a URL for another? Like this</p> <p>CODE:</p> <pre><code>current_url = dfurl.replace("v01", "depot") print(current_url) </code></pre> <p><a href="https://i.stack.imgur.com/sLFkU.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>dfurl is apparently an object and not a string, so you just need to cast it like so</p> <pre class="lang-py prettyprint-override"><code>current_url = str(dfurl).replace("v01", "depot") </code></pre>
python|pandas|url
0
15,345
69,289,975
Pandas dataframe: change string values based on condition with regex
<p>I have a dataframe with numbers represented as strings. I need to remove the parentheses, if they exist, and add a negative sign. For example, (30) should become -30.</p> <p>Positive numbers should not change.</p> <pre><code>df = pd.DataFrame({'a':['19','(30)','(1000)'], 'b':['(202)','200', '100']...
<p>You can do with <code>replace</code></p> <pre><code>out = df.replace({'\((.*)\)':'-\\1'},regex=True).astype(int) Out[280]: a b c 0 19 -202 101 1 -30 200 -30 2 -1000 100 40 </code></pre>
python-3.x|regex|pandas
2
15,346
69,151,553
Grpcio fails installation for Tensorflow 2.5 on arm64 Apple Silicon
<p>I'm following the instructions here: <a href="https://developer.apple.com/metal/tensorflow-plugin/" rel="nofollow noreferrer">https://developer.apple.com/metal/tensorflow-plugin/</a> and having issues installing grpcio. When I try <code>python -m pip install tensorflow-macos</code> I get:</p> <pre><code> AssertionE...
<p>What helped me was:</p> <pre><code>GRPC_PYTHON_BUILD_SYSTEM_OPENSSL=1 GRPC_PYTHON_BUILD_SYSTEM_ZLIB=1 python -m pip install tensorflow-macos </code></pre>
python|tensorflow|apple-m1|grpcio
3
15,347
69,284,311
Replace text in dataframe column if it appears in subsequent columns
<p>I have a list with thousands of rows and am trying to learn vectorised methods to speed up processing. I am wondering if the following is possible.</p> <p>In the following table I want to remove the text in the &quot;TextToRemove&quot; column from the text in the &quot;Full Name&quot; column. So for row 0 the expect...
<p>You can use <code>apply</code>:</p> <pre><code>df[&quot;full_name&quot;] = df.apply(lambda x: x[&quot;full_name&quot;].replace(x[&quot;text_to_remove&quot;], &quot;&quot;), axis=1) # 525 µs ± 14.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) </code></pre> <p>Or using <code>numpy</code> (which is faster)...
python|pandas|vectorization
3
15,348
60,907,862
Multiple ImageDataGenerator
<p>I'm trying to generate two parameters from ImageDataGenerator for input to my model.fit_generator() but that don't work, I don't now if is the best way to do that.</p> <p>My structure is:</p> <p><a href="https://i.stack.imgur.com/NA1sn.png" rel="nofollow noreferrer">enter image description here</a></p> <pre><code...
<p>As evident from the logs your error is caused during validation <strong>data_gen_valid</strong> should be constructed the same way as <strong>data_gen_train</strong> . </p> <p>So if your training data has been the concatenation of two generators so should be your validation data.</p>
python|tensorflow
0
15,349
60,805,094
Make every row same length and fill in missing data with ""
<p>I am very new to Pandas. I have some json that I am trying to convert to csv rows with Pandas:</p> <pre><code>import numpy as np import pandas as pd import json data = json.dumps({ "symbol": "AAPL", "financials": [{ "date": "2019-09-28", #"Revenue": "2.60174e+11", "EPS": "11.97", }, {...
<h3>Updated answer</h3> <p>Given the new requirements, you'll have to do a bit of data transformation to get what you need. The following gives the desired output.</p> <pre class="lang-py prettyprint-override"><code>df = pandas.DataFrame.from_dict(data["financials"]) symbol = list(data)[0] first_column = [data[symbo...
python|json|pandas
2
15,350
71,748,346
Keras model prediction after tensorflow federated learning
<p>I am working with TensorFlow Federated framework and designed a keras model for a binary classification problem. I defined the iterative process with <code>tff.learning.build_federated_averaging_process</code> and broadcasted the model with <code>state, metrics = iterative_process.next(state, train_data)</code></p> ...
<p>We might need to step back a think about how the system models federated computation to understand what is meant by &quot;server model&quot; at one points in time. The <code>SERVER</code> and <code>CLIENTS</code> concepts exist in a different layer of abstraction that the python runtime the script is executing in. M...
python|tensorflow|keras|tensorflow-federated
1
15,351
71,559,454
Reading from CSV, converting to JSON and storing in MongoDB
<p>I am trying to read a CSV file in Pandas, convert each row in to a JSON object and append them to a dict and then store in MongoDB.</p> <p>Here is my code</p> <pre><code>data = pd.DataFrame(pd.read_csv('data/airports_test.csv')) for i in data.index: json = data.apply(lambda x: x.to_json(), axis=1) json_dict...
<p>You can skip processing the individual rows of the DataFrame via:</p> <pre class="lang-py prettyprint-override"><code>import json import pandas data = pandas.DataFrame(pandas.read_csv('test2.csv')) data = data.to_dict(orient=&quot;records&quot;) collection.insert_many(data) </code></pre> <p>As an aside, I think I wo...
python|json|pandas|mongodb|csv
0
15,352
42,532,061
tensorflow: run model evaluation over multiple checkpoints
<p>In my current project I train a model and save checkpoints every 100 iteration steps. The checkpoint files are all saved to the same directory (model.ckpt-100, model.ckpt-200 , model.ckpt-300 etc). And after that I would like to evalute the model based on validation data for all the saved checkpoints, not just the l...
<h2>Fastest solution:</h2> <p><code>tensor2tensor</code> has a module <code>utils</code> with a script <a href="https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/avg_checkpoints.py" rel="nofollow noreferrer"><code>avg_checkpoints.py</code></a> that saves the averaged weights in a new checkpoin...
python|tensorflow
3
15,353
69,924,941
Store the result in new columns, named based on another variable (Pandas)
<p>I have a dataframe. What I need is to calculate the difference between the variables <code>A</code> and <code>B</code>, and store the result in the new columns based on the variable <code>df['Value']</code>. If the <code>Value == 1</code>, then the result is stored in column named <code>Diff_1</code>, if the <code>V...
<p>You can use:</p> <pre><code>df.join(df.set_index(['ID', 'Value']) .eval('A-B') .unstack(level=1).add_prefix('Diff_') .reset_index(drop=True) ) </code></pre> <p>output:</p> <pre><code> ID Value A B Diff_1 Diff_2 Diff_3 Diff_4 0 1 1 56.0 49.0 7.0 ...
python|pandas
3
15,354
69,784,114
Delete row from a column that is unnamed or blank using pandas
<p>I have a dataframe, df, where I would like to delete a row from a column that is unnamed or blank using pandas. I would like to delete the row that contains 'id'</p> <p><strong>Data</strong></p> <pre><code> a b c date 21 22 23 id aa 2 3 4 bb 1 2 3 cc 5 5 5 </code>...
<p>Use <code>dropna</code>:</p> <pre><code>&gt;&gt;&gt; df.dropna(how='all', axis=0) a b c date 21.0 22.0 23.0 aa 2.0 3.0 4.0 bb 1.0 2.0 3.0 cc 5.0 5.0 5.0 </code></pre> <p><strong>Update</strong></p> <p>If the first column is not an index but a real column with an empty name...
python|pandas|numpy
2
15,355
43,277,810
Pandas dataframe: how to summarize columns containing value
<p>Here is my dataframe:</p> <pre><code>df= pd.DataFrame( {"mat" : ['A' ,'A', 'A', 'A', 'B'], "ppl" : ['P', 'P', 'P', '', 'P'], "ia1" : ['', 'X', 'X', '', 'X'], "ia2" : ['X', '', '', 'X', 'X']}, index = [1, 2, 3, 4, 5]) </code></pre> <p>I want to select unique values on the two first columns. I do:</p> <pre>...
<p>Solutions with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.aggregate.html" rel="nofollow noreferrer"><code>aggregate</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unique.html" rel="nofollow noreferrer"><code>unique</code></a...
python|pandas|dataframe
1
15,356
43,384,374
Pandas data pull - messy strings to float
<p>I am new to Pandas and I am just starting to take in the versatility of the package. While working with a small practice csv file, I pulled the following data in:</p> <pre><code>Rank Corporation Sector Headquarters Revenue (thousand PLN) Profit (thousand PLN) Employees 1.ÿ PKN Orlen SA oil and gas P?...
<p>I would use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><strong><code>converters</code></strong></a> parameter.</p> <p>pass this to your <code>pd.read_csv</code> call</p> <pre><code>def space_float(x): return float(x.replace(' ', '')) conv...
python|csv|pandas
0
15,357
43,259,284
Append smaller numpy.ndarray into a bigger numpy.ndarray
<p><strong>Edit:</strong> I guess the actual problem here is that i am appending to a certain dimension in the list, which result inconsistent shape. The length of the zero'th axis would not be the same for each dimension.. </p> <p>So what I actually want to do is </p> <pre><code>&gt;&gt;&gt; a = np.asarray([np.emp...
<p>I think this is what you meant to do.</p> <pre><code>&gt;&gt;&gt; compl = np.asarray([np.empty((1,3,3)) for i in range (4)]) &gt;&gt;&gt; print(compl.shape) (4, 1, 3, 3) &gt;&gt;&gt; compl = np.append(compl,np.random.randint(5,size=(1,3,3))) </code></pre> <p>Here you need to append it to the whole array <code>comp...
python|arrays|numpy
1
15,358
72,469,481
Update one dataframe from another with qualifiers
<p>I'm trying to replicate SQL <code>UPDATE</code>-type functionality in <code>pandas</code>. I've seen other solutions suggesting using <code>pandas</code> <code>update</code> method or <code>merge</code> and dropping columns.</p> <p>Example dataframes:</p> <pre><code>df1 = pd.DataFrame([[1,False, None], [1,True, None...
<p>You can create temporary columns using merge. Then, user np.where similar to =If() function in excel. Next, remove the temporary columns.</p> <pre><code>import pandas as pd import numpy as np df1 = pd.DataFrame([[1,False, None], [1,True, None], [1, False, 'UpdateMe'], [2,True, None]], columns=['id', 'value1', 'valu...
pandas
1
15,359
72,218,493
How to speed up pandas script perfomance
<p>I have two dataframes(first - about 30K rows, second - about 60M rows) and I need to compare home addresses between them and choose the best match:</p> <pre><code>df1 = pd.DataFrame(data={ 'ID': [1, 2], 'address': ['14985 Jesses Trl Kenai AK', '589 Silver Rock Trl Castle Rock CO']}) df2 = pd.DataFrame(data={ 'ID': ...
<p>You may want to consider using the <a href="https://developers.google.com/maps/documentation/geocoding/overview" rel="nofollow noreferrer">Google <code>geocoding</code> API</a>, per the accepted answer to <a href="https://stackoverflow.com/questions/31806695/when-to-use-which-fuzz-function-to-compare-2-strings">this...
pandas|performance
0
15,360
62,594,562
How to exclude starting point from linspace function under numpy in python?
<p>I want to exclude starting point from a array in python using numpy. How I can execute? For example I want to exclude 0, but want to continue from the very next real number(i.e want to run from greater than 0) following code <code>x=np.linspace(0,2,10)</code></p>
<p>Kind of an old question but I thought I'll share my solution to the problem.</p> <p>Assuming you want to get an array</p> <pre><code>[0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.] </code></pre> <p>you can make use of the endpoint option in np.linspace() and reverse the direction:</p> <pre><code>x = np.linspace(2,...
python-3.x|numpy|linspace
4
15,361
62,741,093
How to create a time chart display in python pandas
<p>I have the following information dataframe that logs quiz attempts in a given alloted period and also how long each takes. Each student is given a 25 minute period to complete a test and they can complete as many as they want.</p> <p>my data is:</p> <pre><code># Import pandas library import pandas as pd import nump...
<h2>Assumptions:</h2> <p>Let me know if I misunderstood something (for example, if you only want to include the first attempt)</p> <ul> <li>There is a row for each combination of Name, Day, AllottedPeriod, and AttemptNo.</li> </ul> <p>Time ranges are grouped by 5 minutes.</p> <ul> <li><code>05 == 1</code> if test was a...
python|pandas|matplotlib|seaborn
1
15,362
73,803,409
prevent pandas.combine from converting dtypes
<p><strong>Undesired behavior</strong>: <code>pandas.combine</code> turns ints to floats.</p> <p><strong>Description</strong>: My DataFrame contains a list of filenames (index) and some metadata about each:</p> <pre class="lang-py prettyprint-override"><code> pags rating tms glk name ...
<p>Unless I missed something, you do not have to cast <em>.astype() for every column</em>, only once for the whole dataframe, like this:</p> <pre class="lang-py prettyprint-override"><code>df = ( df.combine(upd, lambda old, new: new.fillna(old), overwrite=False)[df.columns] .fillna(0) .astype(int, errors=&q...
python|pandas|dataframe
0
15,363
73,836,439
How to split a row at every nth column and stack it below in pandas
<p>So I have this single column dataframe with sorted values</p> <pre><code>Gene Symbol AAAS ABCC8 ABCD4 ABL1 ACAA1 ACADM ACADS ACD ACO2 ACOX1 ACP5 ACSL4 ACTB ACTG1 ADA ADA2 ADAM17 ADAMTS13 ADAMTS3 ADAR ADCY1 ADCY2 ADCY3 ADCY4 ADCY5 ADCY6 ADCY7 ADCY8 ADCY9 ADIPOQ </code></pre> <p>and I want to rearrange this in 10 row ...
<p>Try this... if #rows are multiple of 10</p> <pre><code>np.array(df[&quot;Gene Symbol&quot;]).reshape(10,int(df.shape[0]/10)) </code></pre> <p>else, try this... where will first make dataframe multiple of 10 then split as required;</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({&quot;Gene Sy...
python|pandas|dataframe
1
15,364
73,642,105
Storing outputs from input parameters into the rows of a panda data frame
<p>I have a list containing values that I want to perform mathematical operations on with different input parameters that are also stored in a list. For each value in the list, I want to store the results from performing the operation - with each distinct input parameter - row-by-row, where each row corresponds to the ...
<p>The intent is unclear, but does this do what you want?</p> <pre><code>param = [1, 2] vals = [1, 2, 3] df = pd.DataFrame(columns=[&quot;Events&quot;, &quot;Electrons&quot;, &quot;Photons&quot;], index=range(len(param))) for i, p in enumerate(param): df.iloc[i, :] = np.array(vals) + p df: Events Electrons Pho...
python|pandas
1
15,365
71,146,172
Plot dataframe using markers based on another dataframe
<p>I am trying to plot <code>df2</code> as a regular continuous plot but using the values from <code>df1</code> to select markers.</p> <pre><code>DATAdict = { 'A': [ &quot;foo&quot;, &quot;miau&quot;, &quot;ciao&quot; ], 'B': [ &quot;miau&quot;, &quot;haha&quot;, &quot;ciao&quot;], } df1 ...
<p>The simplest way is to use <a href="https://seaborn.pydata.org/generated/seaborn.scatterplot.html" rel="nofollow noreferrer"><code>sns.scatterplot</code></a> with the <code>style</code> param:</p> <blockquote> <p><code>style</code> : vector or key in data</p> <p>Grouping variable that will produce points with differ...
python|pandas|dataframe|matplotlib
2
15,366
71,116,576
How to replace values in netcdf file with Nan?
<p>I'm using a NASA GISS netcdf file with gridded monthly temperature values. According to the <a href="https://psl.noaa.gov/data/gridded/data.gistemp.html" rel="nofollow noreferrer">readme file</a> &quot;Missing data is flagged with a value of 9999.f&quot; I am trying to plot the data but keep getting blank maps. I th...
<p><code>netCDF4</code> creates <a href="https://numpy.org/doc/stable/reference/maskedarray.html" rel="nofollow noreferrer">masked arrays</a>, and automatically masks the value 9999.0. In your code, this means the result of <code>air = data2.variables['air'][:]</code> is a masked array. So I suspect the problem is tha...
python|pandas|numpy|netcdf|matplotlib-basemap
0
15,367
52,046,347
Unravel 1D list back to 3D array
<p>Basically, is there a way to transform a 1D list that has been "flattened" through the <code>numpy.ravel()</code> function back to it's original 3D form ? I know the dimensions, and one might ask why I just don't use the original 3D array in the first place, instead of converting it - but there reasons for that.</p>...
<p>Just reshape it back to the original shape?</p> <pre><code>raveled = np.ravel(arr) new_arr = raveled.reshape(*arr.shape) </code></pre>
python|arrays|numpy
4
15,368
52,304,023
Create pandas column from matching words in other columns
<p>I have a dataframe with several substance columns, like this:</p> <pre><code>import random values = ['oil', 'gas', 'water'] modifier = ['dirty', 'crude', 'fuel'] wordzip = [modifier, values] data = [[wordzip[0][random.randint(0,2)] + ' ' + wordzip[1][random.randint(0,2)] for c in wordzip[0]] for i in range(7)] p...
<p>Let's use <code>stack</code> + <code>extract</code>:</p> <pre><code>df['D'] = df.stack().str.extract(r'(.* oil)').groupby(level=0).first()[0] df A B C D 0 dirty gas crude oil dirty water crude oil 1 dirty water fuel gas dirty gas NaN 2 dirty water ...
python|pandas
4
15,369
52,337,953
Indexing with ndarray in the same way as using tuples
<p>I'd like to index my <code>2d-array</code> using a <code>1d-array</code> of size two in the same way a tuple or basic indexing would be used. I have the indices as <code>np.ndarrays</code> for convenience when it comes to manipulations, but currently I'm converting them back and forth to tuples.</p> <pre><code>a = ...
<p>Pass <code>ix</code> as a tuple for indexing, not an array/list, since the latter will specify a selection of rows, rather than a single cell.</p> <p>So either <code>a[tuple(ix)]</code> or <code>a[(*ix,)]</code> will work.</p>
python|numpy|indexing
1
15,370
60,630,605
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb4 in position 4: invalid start byte
<p>I exported a csv file from Microsoft Excel. It showed properly in Jupyter notebook with pandas and numpy as below:</p> <pre><code>import pandas as pd pd1 = pd.read_csv('test1.csv', encoding='utf-8') </code></pre> <p>There were no error messages the first time, but I just opened the csv file then just saved as a ne...
<p>When you save as, there will be a selection of the encoding format</p> <p><a href="https://i.stack.imgur.com/n8Qut.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n8Qut.png" alt="How to select"></a></p> <p>Try to save as and see if it works.</p>
python|pandas|utf-8|character-encoding
1
15,371
72,501,910
How to create a graph of function in matplotlib?
<p>I am trying to create a graph of cost function in matplotlib.</p> <p>Cost function looks like this: <a href="https://i.stack.imgur.com/SpnOz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SpnOz.png" alt="image" /></a></p> <p>and the graph should look like this: <a href="https://i.stack.imgur.com/...
<p>Use numpy or numpy-like code to make it much easier to write numerical code.</p> <p>Also, I write <code>1e-6</code> here to make sure I use the correct coefficient given by your equation.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np xs = np.linspace(1, 10, 100) ys = 1e-6*(xs**3) - 0.003*(x...
python|pandas|matplotlib
1
15,372
72,670,963
Pandas DataFrame: Replace all values that have a comma with a dot
<blockquote> <p>I have a latitude column written with commas and dots. And I want to convert this column to float but there are some cells written with commas making this not possible, so I have to replace the commas with the points. But when I trying this function below it was not possible to replace with points. I be...
<p>Are you assigning the result of the replace function back to the column you want to change?</p> <p>Like:</p> <pre><code>data[&quot;LAT&quot;] = data[&quot;LAT&quot;].str.replace(',', '.') </code></pre> <p>or</p> <pre><code>data[&quot;LAT&quot;].str.replace(',', '.', inplace=True) </code></pre> <p>If you are doing so...
python|pandas|dataframe|replace
1
15,373
59,868,639
Forward Propagate values while taking averages
<p>I'm trying to figure out how to forward propagate values in Python Pandas in the following way: Basically, let's say I have a Pandas Series (each element is a time t):</p> <pre><code>[5, 2, 3, 3, 4, 9, 2, 3, 1, 9, 2, 7, 5, 7, 9, 2, 3, 1] </code></pre> <p>I'd like each element to be lasting 4 time periods, meaning:...
<p>Is this what you are after?</p> <pre><code>s = pd.Series([5, 2, 3, 3, 4, 9, 2, 3, 1, 9, 2, 7, 5, 7, 9, 2, 3, 1]) s.rolling(4, min_periods=1).mean() 0 5.000000 1 3.500000 2 3.333333 3 3.250000 4 3.000000 5 4.750000 6 4.500000 7 4.500000 8 3.750000 9 3.750000 10 3.750000 11...
python|pandas|math
0
15,374
59,818,048
Numpy shape is same, mean returns different shapes
<p>I have the following snippet.</p> <pre><code>values = [[0.1, 0.7, 0.5], [0.6, 0.3, 0.2], [0.2, 0.8, 0.77]] A = np.array(values).reshape(3,3) print A.shape print np.mean(A, axis=1) B = np.mat(np.random.rand(3, 3)); print B.shape print np.mean(B, axis=1) </code></pre> <p>Output of print statements:</p> <pre><code>...
<p>As explained in the documentation for <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html" rel="nofollow noreferrer"><code>numpy.matrix</code></a>,</p> <blockquote> <p>A matrix is a specialized 2-D array that retains its 2-D nature through operations</p> </blockquote> <p>Additionally,...
python|arrays|numpy
3
15,375
59,895,729
How to parse xml from requests?
<p>I looked at a few other answers but couldn't find a solution which worked for me.</p> <p>Here's my complete code, which you can run without any API key:</p> <pre><code>import requests r = requests.get('http://api.worldbank.org/v2/country/GBR/indicator/NY.GDP.MKTP.KD.ZG') </code></pre> <p>If I print <code>r.text<...
<p>How about the following:</p> <p>Decode the response:</p> <pre><code>decoded_response = response.content.decode('utf-8') </code></pre> <p>Convert to json:</p> <pre><code>response_json = json.loads(json.dumps(xmltodict.parse(decoded))) </code></pre> <p>Read into DataFrame:</p> <pre><code>pd.read_json(response_js...
python|xml|pandas|python-requests
6
15,376
59,518,986
Combining 2 groupby outputs with lambda using pandas python
<p>Table(df):</p> <pre><code> customer_id Order_date 1 2015-01-16 1 2015-01-19 2 2014-12-21 2 2015-01-10 1 2015-01-10 3 2018-01-18 3 2017-03-04 4 2019-11-05 4 2010-01-01 3 2019-02-03 ...
<p>You can use the same named aggregation with <code>.loc[]</code> after the groupby:</p> <pre><code>(df.groupby('customer_id').agg(No_transactions=('Order_date','nunique'), Most_recent_order_date = ('Order_date', 'max')) .loc[lambda x: x['No_transactions']&gt;=3]) </code></pre> <p>Or query:</p...
python|pandas|merge|group-by
2
15,377
32,487,246
Pandas dataframe that consists of only grouped by rows with a counter higher than X
<p>I want to show count the number of groups I have in one column and then only show those groups that have more than a specific number.</p> <p>Consider this example:</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'ColA': 'A A A B B C C C C D E E F F F F F F F G G H'.split(), 'ColB': '1 ...
<p>The problem with your last query: </p> <pre><code>print df.loc[df.groupby(['ColA']).agg(['count']) &gt; 2] </code></pre> <p>Is that df.loc[] is expecting a series of 22 boolean objects. Instead, it is getting a series of 8 objects: </p> <pre><code>&gt;&gt;&gt; df.groupby(['ColA']).agg(['count']) &gt; 2 Co...
python|pandas
2
15,378
40,406,130
Dataframe not printing properly
<p>I downloaded a dataframe to csv, made some changes and then tried to call is again . for some reasons the date column is all mixed up.</p> <p>can some one please help and tell me why I am getting this message. before saving as csv my df looked like this:</p> <pre><code>aapl = web.DataReader("AAPL", "yahoo", start,...
<p>I would suggest you to use HDF store instead of CSV - it's much faster, it preserves your dtypes, you can conditionally select subsets of your data sets, it supports fast compression, etc.</p> <pre><code>import pandas_datareader.data as web stocklist = ['AAPL','BBRY','LULU','AMZN'] p = web.DataReader(stocklist, 'y...
python|python-2.7|pandas|dataframe
1
15,379
61,774,526
Add multiple tensors inplace in PyTorch
<p>I can add two tensors <code>x</code> and <code>y</code> inplace like this</p> <pre><code>x = x.add(y) </code></pre> <p>Is there a way of doing the same with three or more tensors given all tensors have same dimensions?</p>
<pre class="lang-py prettyprint-override"><code>result = torch.sum(torch.stack([x, y, ...]), dim=0) </code></pre> <p>Without stack:</p> <pre class="lang-py prettyprint-override"><code>from functools import reduce result = reduce(torch.add, [x, y, ...]) </code></pre> <p><strong>EDIT</strong></p> <p>As @LudvigH pointed ...
pytorch|tensor
6
15,380
61,689,611
How to loop through a certain column to create multiple plots python
<p>Let's say I have the following data frame:</p> <pre><code>test = pd.DataFrame({'X': [1,2,3,4,5,6,7,8,9,10], 'Y': [1,2,3,4,5,6,7,8,9,10], 'Season': [1,2,3,2,1,3,2,1,3,2]}) test X Y Season 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 2 4 5 5 1 5 6 6 3 6 7 7 2 7 8 8 1 8 9 ...
<p>if you want seaborn regplots, try <a href="https://seaborn.pydata.org/generated/seaborn.lmplot.html" rel="nofollow noreferrer"><code>lmplot</code></a>:</p> <pre><code>import seaborn as sns sns.lmplot(data=test, x='X', y='Y',row='Season') </code></pre>
python|pandas|for-loop|plot|seaborn
3
15,381
61,640,605
Dataframe.replace() does not replace vlaues in all columns
<p>I'm havin a dataframe with json values in it that could look like this (only an example. The keys, values and the amount of data in the json can vary)</p> <pre><code>df = pd.DataFrame({'A':[{'0':0.0,'7':0.0,'19':0.0}], 'B':[{'0':1,'7':0,'19':0}]}) </code></pre> <p>I want to replace the occurrenc...
<p>try:</p> <pre><code>pip install --upgrade pandas </code></pre>
python|regex|pandas|replace
-1
15,382
58,168,084
List Comprehension & Speed Optimization
<p>I have a pandas dataframe, within the dataframe I have two series/columns that I wish to combine into a new series/column. I already have a for loop that does what I need but I'd rather it be in a list comprehension but I cannot figure it out. Also my code takes a considerable amount of time to execute. I read that...
<p>The way to do this using list comprehension:</p> <pre><code>my_list = [x if x in set(df['agent_final']) else y for (x,y) in zip(list(df['lead_owner']), list(df['agent_final']))] </code></pre> <p>It's pretty hard to say why your code is running slow, unless I know what the size of your data is. </p> <p>One way to ...
python|pandas
2
15,383
36,896,402
pandas groupby sequential transformations
<p>I have a <code>pd.DataFrame</code> that I want to utilize <code>groupby</code> and transform several times.</p> <h3>Setup</h3> <pre><code>import pandas as pd import numpy as np np.random.seed(314) dti = pd.date_range('2013-01-31', '2015-12-31', freq='M') quarter = pd.Series(dti[::3], index=dti[::3], name='quarter...
<p>This just occurred to me</p> <h3>Solution</h3> <p>use the <code>apply</code> method on the <code>groupby</code> object. where the function I want to apply is:</p> <pre><code>seq_transform = lambda x: x.cumprod().shift().fillna(method='bfill') </code></pre> <p>then run</p> <pre><code>df.groupby(level=1).apply(se...
python|pandas
0
15,384
36,696,541
H2O and Pandas SparseDataFrame
<p>In the Python API for the machine learning library H2O, what is the correct way to convert a sparse Pandas DataFrame object to an H2OFrame object?</p>
<p>The <a href="http://h2o-release.s3.amazonaws.com/h2o/master/3141/docs-website/h2o-py/docs/frame.html" rel="nofollow noreferrer">recommended way</a> appears to be to save your data as an SVMLight file, then use:</p> <pre><code>yourFrame = h2o.import_file(path="/path/to/test.svmlight") </code></pre> <p>See also this...
python|pandas|h2o
1
15,385
36,777,572
turning dictionary of of dictionary into dataframe with one row, one column of tuples
<p>I have a dictionary named test like so:</p> <pre><code>dct = {} test = {'A': 1, '-A': 1, '-C': 1} dct['key1'] = test </code></pre> <p>I want a df with one row with one column that looks like:</p> <pre><code>(A,1), (-A,1), (-C,1) </code></pre> <p>I've tried so many ways to iteritems() through the keys,value of dc...
<p>If you really want to get rid of the brackets, you first need to convert the list to a string and then strip off the head and tail brackets:</p> <pre><code>&gt;&gt;&gt; pd.DataFrame({'key1': [str([(k, v) for k, v in test.iteritems()])[1:-1]]}) key1 0 ('A', 1), ('-A', 1), ('-C', 1) </co...
python|dictionary|pandas
1
15,386
28,303,972
transform column with categorical data into one column for each category
<p>I have a DataFrame looking like that:</p> <pre><code>df index id timestamp cat value 0 8066 101 2012-03-01 09:00:29 A 1 1 8067 101 2012-03-01 09:01:15 B 0 2 8068 101 2012-03-01 09:40:18 C 1 3 8069 102 2012-03-01 09:40:18 C 0 </code></pre> <...
<p>Here is the one-liner that will achieve that you want. Assuming that your dataframe is named df</p> <pre><code>df_new = df.join(pd.get_dummies(df.cat).drop(['index', 'cat'], axis=1) </code></pre>
python|pandas
1
15,387
34,892,320
Why is this loop runs gradually slowly?
<p>The flowing code is a simple python loop.</p> <pre><code>def getBestWeightsByRandomGradientAscent(featureDatasList, classTypes, maxCycles=1): """ :param featureDatasList: :param classTypes: :param maxCycles: the loop time :return: """ import random featureDatas = np.array(featureDat...
<p>Consider using <code>xrange</code> instead of <code>range</code>. It may be memory or the GC. You can profile your code with something like <a href="http://www.vrplumber.com/programming/runsnakerun/" rel="nofollow">http://www.vrplumber.com/programming/runsnakerun/</a> </p>
python|numpy
0
15,388
35,098,258
How to subtract timedelta from Timestamp, support negative returns
<p>I have a dataframe containing two columns : <code>timestamp</code> and <code>arrival_time</code>, of <code>Timestamp</code> and <code>timedelta</code> types: </p> <pre><code> timestamp arrival_time 0 2015-01-28 05:30:47 0 days 05:30:33.000000000 1 2015-01-28 05:31:50 0 days 05:31:00.000000000 2 201...
<p><strong>EDITED per comments</strong> If I'm reading this right, you basically want to know what the time difference is relative to start of the day in each timestamp. I set up a test case here and provided another snippet of code. Let me know if we're on the same page now.</p> <pre><code>In [123]: test_df Out[123...
python|datetime|pandas
1
15,389
67,472,361
Using PyTorch's autograd efficiently with tensors by calculating the Jacobian
<p>In my previous <a href="https://stackoverflow.com/questions/67320792/how-to-use-pytorchs-autograd-efficiently-with-tensors/67334809#67334809">question</a> I found how to use PyTorch's autograd with tensors:</p> <pre><code>import torch from torch.autograd import grad import torch.nn as nn import torch.optim as optim ...
<p>OK, results first:</p> <p>The performance (My laptop has an RTX-2070 and PyTorch is using it):</p> <pre><code># Method 1: Use the jacobian function CPU times: user 34.6 s, sys: 165 ms, total: 34.7 s Wall time: 5.8 s # Method 2: Sample with appropriate vectors CPU times: user 1.11 ms, sys: 0 ns, total: 1.11 ms Wall ...
python|pytorch
4
15,390
67,512,529
Accessing Github data in Jupyter Books
<p>Getting a tokenising error when I try to access a csv file in Jupyter Books. Had a look at some responses but none seem to help. Any help would be appreciated. Thanks.</p> <pre><code>url = &quot;https://github.com/Kallikrates/bde_at2/blob/3875fd9b03b02b2772129acf2d8d83619971b2eb/2016Census_G01_NSW_LGA.csv&quot; inse...
<p>two options:</p> <p><strong>1st:</strong> read as html</p> <pre><code>url = &quot;https://github.com/Kallikrates/bde_at2/blob/3875fd9b03b02b2772129acf2d8d83619971b2eb/2016Census_G01_NSW_LGA.csv&quot; insert_df = pd.read_html(url) insert_df[0].head(2) </code></pre> <p><strong>2nd read as raw</strong>, observe the URL...
python|pandas|csv|github
1
15,391
67,457,439
How to scrape a table with multiple headers?
<p><a href="https://i.stack.imgur.com/ovo96.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ovo96.png" alt="Table" /></a></p> <p>I am trying to scrape a table and display it in pycharm, but scraping it gives me &quot;keyerror&quot;.</p> <pre><code>import pandas as pd pd.set_option('display.max_column...
<p>Your columns mapper doesn't match the column names, try with</p> <pre class="lang-py prettyprint-override"><code>table_headers = {'Unnamed: 2_level_0' : 'Firepower', 'Unnamed: 3_level_0' : 'Anti-air', 'Unnamed: 2_level_1': 'Firepower', 'Unnamed: 3_level_1': 'Anti-ai...
python|python-3.x|pandas|dataframe
1
15,392
67,249,220
Does tf.function in tensorflow optimize run time?
<p>I read that using <code>tf. function</code> can optimize run time by creating a graph and <code>lazy evaluation</code>. Following is a sample code of doing matrix multiplication:</p> <pre><code>import tensorflow as tf def random_sample(x1,x2): return tf.matmul(x1,x2) @tf.function def random_sample_optimized(x1...
<p>The <code>tf.function</code> will usually run faster for complex calculations. Quoting the following lines from the book - 'Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow' along with the example:</p> <blockquote> <p>A TF Function will usually run much faster than the original Python function, esp...
tensorflow|keras|deep-learning|neural-network|tensorflow2.0
3
15,393
67,521,624
Comparing timestamps in dataframe columns with pandas
<p>Lets say I have a dataframe like this</p> <p>df1:</p> <pre><code> datetime1 datetime2 0 2021-05-09 19:52:14 2021-05-09 20:52:14 1 2021-05-09 19:52:14 2021-05-09 21:52:14 2 NaN NaN 3 2021-05-09 16:30:14 NaN 4 ...
<p>You could start by replacing all <code>NaN</code> values in the <code>datetime2</code> column with <code>datetime.now</code> value. Thus it would make it easier to compare <code>datetime1</code> to now if <code>datetime1</code> is <code>NaN</code>.</p> <p>You can do it with :</p> <pre class="lang-py prettyprint-over...
python|python-3.x|pandas|dataframe|compare
1
15,394
67,348,899
scraping a table from website using pandas and saving to csv file
<p>Iam new to python, I scraping a table from website using pandas and saving it as a csv file and running the code in a loop every 60 seconds. I want the file name to be different or numbered every time the loop runs. I have tried the below</p> <pre><code>import pandas as pd import time starttime = time.time() i=1 whi...
<p>The <code>i=+1</code> doesn't do anything, it just assigns <code>+1</code> to <code>i</code>. Alson, you can use <code>str.format</code> to format the filename. For example:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import time starttime = time.time() i = 1 while True: url = &quot;...
pandas|dataframe|web-scraping|export-to-csv
1
15,395
67,494,673
Cumsum a column's values for last 12 months for each row pandas
<p>I have a dataset like this for each ID;</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Months</th> <th>ID</th> <th>AnnualSalaryChange</th> </tr> </thead> <tbody> <tr> <td>2020-12-01</td> <td>1</td> <td>0</td> </tr> <tr> <td>2020-11-01</td> <td>1</td> <td>1</td> </tr> <tr> <td>2020-10-01...
<p>Assuming this <code>df</code>:</p> <pre class="lang-none prettyprint-override"><code> Months ID AnnualSalaryChange 0 2020-12-01 1 0 1 2020-11-01 1 1 2 2020-10-01 1 0 3 2020-09-01 1 0 4 2020-08-01 1 ...
python|pandas|dataframe
2
15,396
67,319,606
How to sort datetime index dataframe
<p>I have a datetime index dataframe which contains data for every hour between 2019 and 2020 and which I import from a CSV file as follow in order to keep only the columns I want, with easier names (names are changed for work reasons):</p> <pre><code>file = 'data.csv' df = pd.read_csv(file,sep=&quot;;&quot;, header=0,...
<p>The point here is to make sure date/time is imported correctly to datetime datatype. A string like <code>'01/01/2019 00:00'</code> will be parsed by default as <code>mm/dd/YYYY HH:MM</code>, see <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html#pandas-to-datetime" rel="nofol...
python|pandas|datetime|indexing
1
15,397
67,368,093
Find optimal unique neighbour pairs based on closest distance
<p><strong>General problem</strong></p> <p>First let's explain the problem more generally. I have a collection of points with x,y coordinates and want to find the optimal unique neighbour pairs such that the distance between the neighbours in all pairs is minimised, but points cannot be used in more than one pair.</p> ...
<p>This can be formulated as a mixed integer linear programming problem.</p> <p>In python you can model and solve such problems using <a href="https://www.cvxpy.org/" rel="noreferrer">cvxpy</a>.</p> <pre class="lang-py prettyprint-override"><code>def connect_point_cloud(points): ''' Given a set of points comput...
python|numpy|scipy|pairing|neighbours
7
15,398
34,808,974
Find the eigenvalues of a subset of Dataframe in Python
<p>I have a matrix in the form of DataFrame </p> <pre><code> df= 6M 1Y 2Y 4Y 5Y 10Y 30Y 6M n/a n/a n/a n/a n/a n/a n/a 1Y n/a 1 0.9465095 0.869504 0.8124711 0.64687 0.5089244 2Y n/a 0...
<p>IIUC you could convert your columns to numeric with <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.to_numeric.html" rel="nofollow"><code>pd.to_numeric</code></a>and replace non-numeric with <code>NaN</code> then using <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generat...
python|pandas|dataframe|eigenvalue
3
15,399
34,433,886
Iterating over date range between two pandas dataframes for category count
<p>I have two pandas dataframe(df1 and df2):</p> <p>df1 has 12 columns, where a1, a2, ..., a9 are empty columns. Below is a sample for df1:</p> <pre><code>Stock Start_Date End_Date a1 a2 a3 a4 .... a9 A 09-12-2015 20:04 10-12-2015 23:04 B 09-12-2015 10:04 09-12-2015 20:14 ...
<p>You can try this solution, where I remove empty columns of <code>df1</code>, but it works with them too:</p> <pre><code>#merge dataframes by Stock, select datetimes between start and end df = df1.merge(df2,on='Stock', how='left') df = df[(df.date_time &gt;= df.Start_Date) &amp; (df.date_time &lt;= df.End_Date)] #re...
python|python-2.7|pandas
1