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 |
|---|---|---|---|---|---|---|
20,300 | 56,265,563 | While removing html text from column, object of type 'float' has no len() error is occuring | <p>I am using an amazon dataset to do sentiment analysis. Dataset content is <br>
<a href="https://i.stack.imgur.com/qcKZp.png" rel="nofollow noreferrer">https://i.stack.imgur.com/qcKZp.png</a></p>
<p>dataset con be found on:
<a href="https://www.kaggle.com/PromptCloudHQ/amazon-reviews-unlocked-mobile-phones" rel="nof... | <p>Check for <code>NaN</code> with <code>df[df['Reviews'].isnull()]</code>, if you find any try to <code>dropna</code> first</p> | pandas|nlp|data-science|natural-language-processing | 1 |
20,301 | 55,660,781 | Define matrix : 'A' is not defined | <p>I wrote this function in python that given a value and I would have a square matrix with random values.
But executing the procedure gives me the following error:
<code>A' is not defined</code></p>
<p>How do I do that?</p>
<pre><code>import numpy as np
import scipy.stats as spstats
import scipy.linalg as la
import ... | <p>There are some general errors with the formatting of your code, e.g. the first return statement is out of scope of the <code>generaMatrice</code> function.
Having said that, you can just do</p>
<pre><code>A=np.random.randint(1,100,(n,n))
AI=np.linalg.inv(A)
</code></pre>
<p>and get rid of your <code>generaMatrice<... | python|numpy | 0 |
20,302 | 55,756,718 | HTML dropdown list not returning Python module in Flask route | <p>I have two scripts that end in dataframes loaded into my <code>app.py</code>. The dropdown lists in my first HTML page are the column names of both dataframes. When clicking submit, I'm trying to route the selections to a third module <code>regrplot</code> in <code>app.py</code>. This module would use the selection ... | <p>I haven't tested, but try these fixes:</p>
<p>Option 1: The forms need to be set to POST in order to use the "request.form" method, otherwise use the "request.args" method instead (GET). This is why I believe you have the error where "y1" isn't defined because the "request.method == 'POST'" condition is False, thu... | html|python-3.x|pandas|flask | 0 |
20,303 | 55,680,165 | Create binary column in pandas dataframe based on priority | <p>I have a pandas dataframe that looks something like this:</p>
<pre><code>Item Status
123 B
123 BW
123 W
123 NF
456 W
456 BW
789 W
789 NF
000 NF
</code></pre>
<p>And I need to create a new column <code>Value</code> which will be either 1 or 0 depending on the values in the <c... | <p>Taking your original dataframe as input <code>df</code> dataframe, the following code will produce your desired output:</p>
<pre><code>#dictionary assigning order of priority to status values
priority_map = {'B':1,'BW':2,'W':3,'NF':4}
#new temporary column that converts Status values to order of priority values
df... | python|python-3.x|pandas|dataframe | 2 |
20,304 | 55,935,073 | Iterate over dataframe rows and assign to list based on variable in list? | <p>I have a Dataframe which is this -> <a href="https://drive.google.com/file/d/1qcQRwmFIkTJHPaknXjV1vNlDScw1Fxf6/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1qcQRwmFIkTJHPaknXjV1vNlDScw1Fxf6/view?usp=sharing</a></p>
<pre><code> Kyphosis Age Number Start prob_Age prob_Number prob_... | <p>First, <code>list</code> is a built-in function in python, so you shouldn't really use it as variable name. Second, although you're changing vars A, S, N in each iteration (well not really changing because in each iteration you're assigning them same values), you're not changing the values of any of the lists. So to... | python-3.x|pandas|list|dataframe | 1 |
20,305 | 65,023,360 | How to extract the specific data from the unorganized excel file without columns) | <p>I reached my limit and My hair is getting thinner.
I really need your help.</p>
<p><strong>1. Try</strong></p>
<p>I'd like to extract the data line including the specific words "<strong>Super Banana</strong>" from <code>*.xlsx</code> in one folder.</p>
<p>Here is the file pic.
[1]: <a href="https://i.stack... | <p>use the proper file path.
Example :
<code>df = pd.read_excel('C:\\Users\\file.xlsx').fillna(value = 0)</code></p> | python|pandas|glob | 0 |
20,306 | 64,634,468 | Why the neural network is not learning? | <p>I am training a neural network with a simple dataset. I have tried different combinations of parameters, optimizers, learning rates ... but even after 20 epochs the network is still not learning anything.</p>
<p>I wonder where in the following code lies the problem?</p>
<pre><code>from tensorflow.keras.models import... | <p>You have used wrong loss function, change this line</p>
<pre><code>model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
</code></pre>
<p>to, for example,</p>
<pre><code>model.compile(optimizer=opt, loss='mse', metrics=['accuracy'])
</code></pre>
<p>Categorical cross-entropy needs a one... | python|tensorflow|keras|neural-network | 2 |
20,307 | 39,607,540 | Count the number of Occurrence of Values based on another column | <p>I have a question regarding creating pandas dataframe according to the sum of other column.</p>
<p>For example, I have this dataframe</p>
<pre><code> Country | Accident
England Car
England Car
England Car
USA Car
USA Bike
USA Plane... | <p><strong><em>Option 1</em></strong><br>
Use <code>value_counts</code></p>
<pre><code>df.Country.value_counts().reset_index(name='Sum of Accidents')
</code></pre>
<p><a href="https://i.stack.imgur.com/G0Gii.png" rel="noreferrer"><img src="https://i.stack.imgur.com/G0Gii.png" alt="enter image description here"></a></... | python|pandas | 8 |
20,308 | 39,789,503 | Filling dataframe columns based on ranges described in other columns | <p>I have a very interesting problem here, I have a dataset like,</p>
<pre><code> id, start, end
1234 200 400
1235 300 500
1236 100 900
1236 200 1200
1236 300 1400
</code></pre>
<p><strong>Main Objective</strong> : I want to count the number of concurrent session... | <p>In Pandas you could also do this:
<code>df[(df.start <= t)&(df.end >= t)].groupby("id").count()['start'].reset_index()</code> </p>
<p>where t is your desired time. Just rename the final column accordingly. But I don't know if this can be ported over the pyspark.@Khris</p> | python|pandas|dataframe|pyspark-sql | 0 |
20,309 | 39,435,341 | How to calculate AUC with tensorflow? | <p>I've built a binary classifier using Tensorflow and now I would like to evaluate the classifier using AUC and accuracy. </p>
<p>As far as accuracy is concerned, I can easily do like this:</p>
<pre><code>X = tf.placeholder('float', [None, n_input])
y = tf.placeholder('float', [None, n_classes])
pred = mlp(X, weight... | <p>I've found the same issue on <a href="https://github.com/tensorflow/tensorflow/issues/3971">github</a>. At the moment, it seems that you also need to run <code>sess.run(tf.initialize_local_variables())</code> in order to make <code>tf.contrib.metrics.streaming_auc()</code> work. They're working on it.</p>
<p>Here y... | tensorflow|python-3.5|roc|auc | 12 |
20,310 | 44,162,585 | Filtering and comparing dates with Pandas | <p>I would like to know how to filter different dates at all the different time levels, i.e. find dates by year, month, day, hour, minute and/or day. For example, how do I find all dates that happened in 2014 or 2014 in the month of January or only 2nd January 2014 or ...down to the second?</p>
<p>So I have my date an... | <p>You can filter your dataframe via boolean indexing like so:</p>
<pre><code>df.loc[df['timeStamp'].dt.year == 2014]
df.loc[df['timeStamp'].dt.month == 5]
df.loc[df['timeStamp'].dt.second == 4]
df.loc[df['timeStamp'] == '2014-01-02']
df.loc[pd.to_datetime(df['timeStamp'].dt.date) == '2014-01-02']
</code></pre>
<p>..... | pandas|datetime | 13 |
20,311 | 44,058,046 | python3: numpy works, but numpy.integrate doesn't | <p>I'm using <code>numpy</code> for mathematical projects in <code>python3</code>. Today, I wanted to use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html" rel="nofollow noreferrer"><code>numpy.integrate.quad</code></a>, but you can see the errors and further attemps below. <code>... | <pre><code>from scipy.integrate import quad
</code></pre>
<p>numpy doesn't have an <code>integrate</code> <em>package</em>; those are in the <code>scipy</code> part of the delivery.</p> | python|numpy|python-import | 1 |
20,312 | 69,339,143 | Getting pytorch backward's RuntimeError: Trying to backward through the graph a second time... when slicing a tensor | <p>Upon running the code snippet (PyTorch 1.7.1; Python 3.8),</p>
<pre><code>import numpy as np
import torch
def batch_matrix(vector_pairs, factor=2):
baselen = len(vector_pairs[0]) // factor
split_batch = []
for j in range(factor):
for i in range(factor):
start_j = j * baselen
... | <p>After backpropagation, the leaf nodes' gradients are stored in their <code>Tensor.grad</code> attributes. The gradients of non-leaf nodes (i.e. the intermediate results to which the error refers) are freed by default, as PyTorch assumes you won't need them. In your example, your leaf nodes are those in <code>vector_... | python|deep-learning|pytorch|autograd | 1 |
20,313 | 54,113,208 | Tensorflow GPU / CUDA installation on Ubuntu | <p>I have set up a Ubuntu 18.04 and tried to make Tensorflow 2.2 GPU work (I have an Nvidia/CUDA graphic card) with Python.
Even after reading the documentation <a href="https://www.tensorflow.org/install/gpu#linux_setup" rel="nofollow noreferrer">https://www.tensorflow.org/install/gpu#linux_setup</a>, it failed (see b... | <p>Well, I was facing the same problem. The first thing to do is to look up, which Tensorflow version is required. In your case <code>Tensorflow 2.2</code>. requires <code>CUDA 10.1</code>. The correct cuDNN version is also important. In your case it would be <code>cuDNN 7.4</code>. An additional point is the installed... | python|linux|tensorflow | 1 |
20,314 | 54,226,034 | pandas.isin broken for all caps? | <p>I found the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="nofollow noreferrer">isin</a> function for pandas, but it looks like all caps doesn't show?</p>
<pre><code>import pandas as pd
df = pd.read_json('{"Technology Group":{"0":"Cloud","1":"Cloud","2":"Cloud","3":... | <p>This might be due to spaces. The <a href="https://www.programiz.com/python-programming/methods/string/strip" rel="nofollow noreferrer">strip()</a> removes characters from both left and right based on the argument (a string specifying the set of characters to be removed). </p>
<pre><code>import pandas as pd
df = pd.... | python|pandas|dataframe | 1 |
20,315 | 38,151,646 | Pandas to MatPlotLib with Dollar Signs | <p>Given the following data frame:</p>
<pre><code>import pandas as pd
df=pd.DataFrame({'A':['$0-$20','$20+']})
df
A
0 0−20
1 $20+
</code></pre>
<p>I'd like to create a bar chart in MatPlotLib but I can't seem to get the dollar signs to show up correctly. </p>
<p>Here's what I have:</p>
<pre><code>import mat... | <p>To specify the xticklabels, pass <code>tick_label=x</code> to <code>plt.bar</code>. </p>
<p>Matplotlib parses labels using a subset of the <a href="http://matplotlib.org/users/mathtext.html#mathtext-tutorial" rel="nofollow noreferrer">TeX markup
language</a>. Dollar
signs indicate the beginning (and end) of math mo... | python-3.x|pandas|matplotlib|axis-labels|dollar-sign | 2 |
20,316 | 38,375,942 | tf_version_script giving syntaxerror | <p>The version of linux I am using is ubuntu 14.04. I wanted to know my tensorflow version, so I ran a script given in the tensorflow directory <code>tf_version_script.lds</code> with the command <code>ld tf_version_script.lds</code> and it gave this error-</p>
<pre><code>ld:/home/me/tensorflow/tensorflow/tf_version_s... | <p>In >jupyter notebook</p>
<pre><code> import tensorflow as tf
import keras as ks
print("TensorFlow version : ")
print(tf.__version__)
print("Keras version : ")
print(ks.__version__)
or
print("TensorFlow version : " + tf.__version__)
print("Keras version : " + ks.__version__)
</code></pre>
<p>Out >Out... | linux|tensorflow|ld | 1 |
20,317 | 38,351,736 | pandas: to_csv with a numeric range of named columns? | <p>Is it possible through pd.to_csv to provide a numeric range to the columns argument, even if the headers are labeled with strings?</p>
<p>Sample dataframe:</p>
<pre><code> January February March April May June July August September
0 67 43 48 58 82 102 118 114 82
1 ... | <p>You can access the names of the columns of the dataframe as a series and then slice that, eg:</p>
<pre><code>df.to_csv('filename.csv', usecols=df.columns[:8])
</code></pre> | python|pandas | 2 |
20,318 | 38,298,385 | How to return the top 10 frequent column values with pandas? | <p>I am playing with a well known crime dataset. It looks like this:</p>
<pre><code>Dates,Category,Descript,DayOfWeek,PdDistrict,Resolution,Address,X,Y,Time
2015-05-13,VANDALISM,"MALICIOUS MISCHIEF, VANDALISM OF VEHICLES",Wednesday,TENDERLOIN,NONE,TURK ST / JONES ST,-122.41241426358101,37.7830037964534,22:30:00
2015-0... | <p>I think this does what you want, firstly construct a logic index with <code>df.Dates == "2011-01-01"</code> to filter rows on date <code>2011-01-01</code> and specify <code>Category</code> at the column index to select only the <code>Category</code> column, thus you get all the Category on <code>2011-01-01</code>. U... | python|python-3.x|csv|pandas | 1 |
20,319 | 38,180,617 | Pandas Merge Bins | <p>I have created a distribution using numpy histogram and digitize functions.</p>
<pre><code>_, bins = np.histogram(x, bins=bins)
arr = np.digitize(x, bins) - 1
x = bins[arr[:]]
</code></pre>
<p>Or possibly: </p>
<pre><code>x = pandas.cut(x, bins=bins)
</code></pre>
<p>However as the distribution is very skewed, e... | <p>As promised, I implemented something in physt, version 0.3.5. You're welcome to use it.</p>
<p>See <a href="http://nbviewer.jupyter.org/github/janpipek/physt/blob/master/doc/Binning2.ipynb#Merging-bins" rel="nofollow">http://nbviewer.jupyter.org/github/janpipek/physt/blob/master/doc/Binning2.ipynb#Merging-bins</a> ... | python|numpy|pandas|dataframe|histogram | 1 |
20,320 | 66,164,134 | Pandas: Grouping cell values by value into individual columns | <p>I have a pandas DataFrame with multiple offset columns:</p>
<pre><code> 0 1 2 3 4 5 6
0 532201 577834 577837 839786 1003273 NaN NaN
1 577834 577837 649835 839786 1003273 NaN NaN
2 577834 577837 649835 839786 1003273 NaN ... | <p>You can work with dummies. <code>stack</code>, create dummies and use <code>max</code> to create indicators of existence anywhere across the row.</p>
<pre><code>df1 = pd.get_dummies(df.stack().astype('int64')).max(level=0)
532201 577834 577837 649835 649839 649845 839785 839786 1003273
0 1... | python|pandas|dataframe|numpy | 2 |
20,321 | 66,338,814 | Measuring the width of several points in a mask image based on another mask image | <p>I have these two mask images:</p>
<p>Image1</p>
<p><a href="https://i.stack.imgur.com/wbQAL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wbQAL.png" alt="enter image description here" /></a></p>
<p>Image2</p>
<p><a href="https://i.stack.imgur.com/8T7RB.png" rel="nofollow noreferrer"><img src="ht... | <p>Here is one way to do that in Python/OpenCV. Basically, get the angle of the rotated rectangle and unrotate the image. Then crop it. Then count the number of non-zero pixels for each row in the cropped image.</p>
<p>Input:</p>
<p><a href="https://i.stack.imgur.com/Tgl8M.png" rel="nofollow noreferrer"><img src="https... | python|image|numpy|opencv|mask | 1 |
20,322 | 66,094,469 | Is there a way to have NumPy arrays calculate 0 * inf = 0 rather than 0 * inf = NaN? | <p>I am using NumPy arrays to represent functions and probability distributions. I would like the arrays to obey the convention (common in probability) that <code>0 * inf</code> yields <code>0</code>.</p>
<p>I would like</p>
<ul>
<li><code>array([1., inf]) @ array([1., 0.])</code> to yield <code>1.0</code></li>
<li><co... | <p>I think your best bet is to choose some big number (e.g. <code>1e100</code>) and use that to represent infinity.</p>
<p>Then you can do your computations (beware of <code>RuntimeWarning: overflow encountered</code> to make sure your big number doesn't go back to <code>inf</code>), and if necessary convert anything a... | python|arrays|numpy|nan | 0 |
20,323 | 66,330,263 | A given column is not a column of the dataframe Pandas | <p>I have the following splitting function:</p>
<pre><code>from typing import Tuple
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split
def split_dataframe(
df: pd.DataFrame,
target_feature: str,
split_ratio: int = 0.2
) -> Tuple[pd... | <p>I mage a mistake in <code>pipe.fit_transform(X_train, y_train)</code>, i changed it to <code>preprocessor.fit_transform(X_train, y_train)</code> and it worked</p> | python|pandas | 0 |
20,324 | 52,552,264 | Checking if the last Time of CSV is current time or not using Pandas Python3 | <p>I have tried the following to convert the time to Indian time for testing. But got many errors. See what I tried til now: </p>
<pre><code>>>> df = pd.read_csv("Real.csv",encoding='utf-16',index_col=0)
>>> df.tail(1).index
Index(['2018.09.27 16:43:00'], dtype='object', name='Time')
>>> df... | <p>Try using the following:</p>
<pre><code>>>> df = pd.read_csv("Real.csv",encoding='utf-16',index_col=0)
>>> pd.to_datetime(df.index[-1]).to_pydatetime() == datetime.now().replace(tzinfo=None,microsecond=0,second=0)+ timedelta(hours=-2,minutes=-30)
True
</code></pre>
<p>It worked for me.</p> | python|python-3.x|pandas|csv|datetime | 1 |
20,325 | 46,457,357 | Increment a column value based on a combination of columns | <p>I have a dataset that looks like this:</p>
<pre><code>OwnerID GroupID AssignmentID ... <few more columns> [Need this column]
1 10 100 1
1 10 100 1
1 10 200 ... | <pre><code>df.assign(
result=df.groupby(
['OwnerID', 'GroupID']
).AssignmentID.transform(lambda x: x.factorize()[0]) + 1
)
OwnerID GroupID AssignmentID Result result
0 1 10 100 1 1
1 1 10 100 1 1
2 1 10 ... | python|pandas | 2 |
20,326 | 46,533,417 | Error message: 'TypeError: cannot concatenate a non-NDFrame object' while trying to append date value to a empty dataframe | <p>I am trying to create a panda series with Timestamp values. But i am getting below error. While trying to append timestamp value to empty dataframe.</p>
<pre><code>x = pd.Series()
dfx = {k: v for k, v in df.groupby('month')}
for k in dfx:
x.append(dfx[k].iloc[0,0])
</code></pre>
<p>value of df:</p>
<pre><code... | <p>Solved the issue using following code.</p>
<pre><code> x= df.groupby(['year', 'month']).Date.head(1)
</code></pre> | python|pandas|dataframe | 1 |
20,327 | 46,184,684 | Converting Binary Numpy Array into Unsigned Integer | <p>I have a long 2D matrix of Numpy array object whose dimension is n x 12. Here is the first 10 rows of this matrix:</p>
<pre><code>b = ([[0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0],
[0, ... | <p>We could slice out the first <code>4</code> columns and last <code>8</code> columns and use <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.packbits.html" rel="nofollow noreferrer"><code>np.packbits</code></a> separately on those. Then, scale the first slice to account for them being the m... | python|numpy | 4 |
20,328 | 58,366,121 | Python Pandas sorting of the middle column when using [groupby] | <p>I am using python pandas and would like to sort the output by the middle column of the below tables(i have shown the output I am getting and the desired output that i want to get)</p>
<p>I am using the groupby function within pandas to get the output however it is sorting by count column (see below output table), i... | <p>With the assumption that you do not care about ordering of "Country" column (as you have not specified that in question), here is one way to achieve the count of per country, per year grouping, keeping years in ascending order:</p>
<pre><code>df2 = df.groupby(["Country", "YOB"]).count()
df2 = df2.sort_values(["Coun... | python|pandas | 1 |
20,329 | 44,706,840 | Tensorflow summery merge error : Shape [-1,784] has negative dimensions | <p>I am trying to get summary of a training process of the neural net below.</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets(".\MNIST",one_hot=True)
# Create the model
def tr... | <p>From one comment of the deleted answer, from the original poster:</p>
<blockquote>
<p>I actually build a neural net under <code>with tf.Graph() as g</code>. I removed the interactive session and started session as <code>with tf.Session(g) as sess</code>. It fixed the problem.</p>
</blockquote>
<p>The graph <code... | tensorflow|tensorboard | 3 |
20,330 | 44,641,137 | How to read contents of datasets of a h5py file into a numpy array given a list of keys? | <p>Inputs to my function are a h5py file and a text file. Text file has two columns. First column has some utterance information and second column has the speaker information (for that utterance). The keys of h5py file (created using create_datasets) are the utterances (first column of the file). Each of this datasets ... | <p>Normally when we want to collect a bunch of arrays (of equal size) into 2d array, we first append them to a list, and then create the array from that at the end:</p>
<pre><code>utt2ilist = []
...
if utt in h5f.keys():
utt2ilist.append(h5f[utt][:])
...
utt2iarr = np.array(utt2ilist)
</code></pre>
<p... | python|arrays|numpy|h5py | 0 |
20,331 | 44,807,224 | Python / Pandas - Creating a condensed dataframe of groups | <p>I have a dataframe that looks like this:</p>
<pre><code> group groupError level2_error level3_error level4_error
170 64.22-1-00 0.109667 0.109667 0.109667 0.168453
72 64.22-1-00 0.109667 0.109667 0.109667 0.168453
121 41.20-4-00 4.00153 4.00153 ... | <p>To handle possible input errors (if you aren't 100% that they identical), you can use some form of:</p>
<pre><code>df.groupby('group').agg(lambda x: x.value_counts().index[0])
</code></pre>
<p>which helps catch outliers too. Otherwise as Paul mentioned, <code>drop_duplicates()</code> is perfect.</p>
<p>Edited: Ch... | python|pandas|grouping | 2 |
20,332 | 61,048,798 | Turning JSON to a Data Frame in Python? | <p>I'm trying to transform JSON into a Dataframe. I'm trying to get daily information about stocks and turning it into a dataframe so I can transform it into a graph in order to make analysis.</p>
<pre><code> "Meta Data": {
"1. Information": "Daily Prices (open, high, low, close) and Volumes",
"2. S... | <p>Here is my proposed answer using pandas:</p>
<pre><code>#Your code
response_ibov = requests.get("https://www.alphavantage.co/query?
function=TIME_SERIES_DAILY&symbol=^BVSP&apikey=XXX")
url = "https://www.alphavantage.co/query?
function=TIME_SERIES_DAILY&symbol=^BVSP&apikey=XXX"
r = requests.get(ur... | python|json|pandas|matplotlib | 0 |
20,333 | 60,962,929 | Two equal Keras models after set/get_weights() do not have the same weights according to numpy.array_equal() | <p>By using <code>numpy.array_equal()</code>, the code below shows that even after copying the weights from <code>model_1</code> to <code>model_2</code>, it still points out that both weights are different even though by looking at both weights, they are indeed equal to one another. Why?</p>
<pre><code>import numpy as... | <p><code>get_weights()</code> returns a list of numpy arrays.</p>
<p>When you pass lists of numpy arrays to <code>array_equal</code>, each list is internally converted to a numpy array of <code>object</code> <code>dtype</code>, which you can't simply do equality checks on.</p>
<p>See <a href="https://stackoverflow.co... | python|python-3.x|numpy|keras|neural-network | 2 |
20,334 | 71,771,460 | Removing outliers with Exponential moving avergae using python | <p>I have a crop price dataset I am trying to implement prophet prediction model. but before that I want to replace outliers. I am currently detecting the outliers using 10% and 90% quantile technique. and replacing it with the 10% and 90% value (maximum and minimum value allowed). but now I want to replace those outli... | <p>You need to use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.ewm.html" rel="nofollow noreferrer"><code>ewm</code></a> to compute an <a href="https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average" rel="nofollow noreferrer">exponentially weighted moving operation</a>.</p>
<p... | python|pandas|outliers | 0 |
20,335 | 71,583,732 | How can we extract rows with sequential values in dataframe? | <p>I wanna select only rows with three or more sequential values.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>num1</th>
<th>num2</th>
<th>num3</th>
<th>num4</th>
<th>num5</th>
<th>num6</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</t... | <p>Get differencies per rows by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.diff.html" rel="nofollow noreferrer"><code>DataFrame.diff</code></a>, compare for <code>1</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eq.html" rel="nofo... | python|pandas|dataframe|numpy | 5 |
20,336 | 42,539,370 | Cuda issue in TensorFlow 1.0 tutorial looks like TF can't find CUPTI/lib64? | <p>This question has nothing to do with the warnings SSE AVX etc.. I've included the output for completeness. The issue is the fail on some cuda libs, I think, at the end, the machine has a NVIDA 1070 card and has the Cuda libs that are used earlier in the process but something is missing at the end?
I pip installed re... | <p>Also reference this issue on GitHub: <a href="https://github.com/tensorflow/tensorflow/issues/7975" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/7975</a></p>
<p>You may try the apt-get install that the git-hub issue suggests but that did not do it for me: This did:</p>
<p>The answer wa... | python|tensorflow|tensorboard | 2 |
20,337 | 69,956,656 | How to generate a numpy array with random values that are all different from each other | <p>I've just started to learn about Python libraries and today I got stuck at a numpy exercise.</p>
<p>Let's say I want to generate a 5x5 random array whose values are all different from each other. Further, its values have to range from 0 to 100.</p>
<p>I have already look this up here but found no suitable solution t... | <p>Not sure if this will be ok for all your needs, but it will work for your example:</p>
<pre><code>np.random.choice(np.arange(100, dtype=np.int32), size=(5, 5), replace=False)
</code></pre> | arrays|numpy|random | 5 |
20,338 | 72,160,417 | TensorFlow Datasets load images from Path | <p>I have a dataset like this,</p>
<pre><code>df = pd.read_csv('train.csv')
df.head()
>>>
image label
0 /path/to/img1.jpg 1
1 /path/to/img2.jpg 0
2 /path/to/img3.jpg 0
3 /path/to/img4.jpg 1
4 /path/to/img5.jpg 1
</code></pre>
<p>The first column is the path... | <p>You need to specify the target columns.
It is similar to those questions but the idea is from 6 to 33 pictures recognized.</p>
<p><strong>[ Sample ]:</strong></p>
<pre><code>import tensorflow as tf
import tensorflow_io as tfio
import pandas as pd
import matplotlib.pyplot as plt
""""""... | python|tensorflow | 0 |
20,339 | 72,356,416 | Split One Column to Multiple Columns in Pandas | <p>I want to split one <a href="https://i.stack.imgur.com/c6TsQ.jpg" rel="nofollow noreferrer">current column</a> into 3 columns. In screenshot we see the builder column, which need to be split in 3 more column such as b.name , city and country. So I use str.split() method in python to split the column which give me go... | <p>Your exact input is unclear, but assuming the sample input kindly provided by @ArchAngelPwn, you could use <code>str.split</code> with a regex:</p>
<pre><code>names = ['Builder_Name', 'City_Name', 'Country']
out = (df['Column1']
.str.split(r'\s*[,-]\s*', expand=True) # split on "," or "-" with ... | python|pandas|dataframe | 1 |
20,340 | 72,291,069 | pd.read_excel parses dates automatically and parses it wrong | <p>In <code>pd.read_excel</code> pandas automatically parses the <strong>columns names</strong> as date. And parses it wrong. The date is <code>dd/mm/yy</code> and it parses it as <code>mm/dd/yy</code>.</p>
<p>The column names are date.</p>
<h1>code used</h1>
<pre class="lang-py prettyprint-override"><code>df = pd.read... | <p>Use <code>'%Y-%m-%d'</code> for formatting like you wish.</p>
<p>e.g.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"Date": ["26-12-2007", "27-12-2007", "28-12-2007"]})
df["Date"] = pd.to_datetime(df["Date"]).dt.strftime('%Y-%m-%d')
print(df)
</cod... | python|pandas|dataframe|date | 0 |
20,341 | 72,360,164 | Efficiently get unique elements + count - NumPy / Python | <p>I'm looking for an extension to this question <a href="https://stackoverflow.com/questions/46575364/efficiently-counting-number-of-unique-elements-numpy-python">Efficiently counting number of unique elements - NumPy / Python</a> that can also return the count of each unique element (i.e. how many times it occurs in ... | <p>In the case where <code>a</code> is of type <code>uint</code>, you can use <code>np.bincount</code> which offers a fast way to get the counts. If you do have negative int's, perhaps you can add an offset to make all positive?</p>
<p>For example:</p>
<pre class="lang-py prettyprint-override"><code>counts = np.bincoun... | python|numpy | 0 |
20,342 | 50,438,066 | Function integration returns “only length-1 arrays can be converted to Python scalars” | <p>I'm trying to integrate a function into a given range that shows the flow of particles in a zero-angle (theta) direction as a function of the energy E of the particles. I've tried several ways and got different errors but there are two that persist at the end. My knowledge of Python is limited, I try to learn new wa... | <p><code>integral</code> must have one of the signatures described in the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html#scipy.integrate.quad" rel="nofollow noreferrer">scipy documentation</a>. In your case, a function taking a double as argument and returning a double seems app... | python|function|numpy|typeerror|integrate | 1 |
20,343 | 50,592,762 | Finding most common values with Pandas GroupBy and value_counts | <p>I am working with two columns in a table. </p>
<pre><code>+-------------+--------------------------------------------------------------+
| Area Name | Code Description |
+-------------+--------------------------------------------------------------+
| N Hollywood | VIOLA... | <p>Use <code>head</code> in each group from the results of <code>value_counts</code>:</p>
<pre><code>df.groupby('Area Name')['Code Description'].apply(lambda x: x.value_counts().head(3))
</code></pre>
<p>Output:</p>
<pre><code>Area Name
77th Street RAP... | python|python-3.x|pandas|pandas-groupby | 4 |
20,344 | 50,600,105 | Sanitizing inputs by updating locals() in Python | <p>My ultimate goal is an efficient way to convert all my numeric inputs to numpy arrays and make sure they have the correct shapes.</p>
<p>Here is the behavior I was considering:</p>
<pre><code>def test_func(a, b):
for item in locals():
new_val = ... # code to sanitize the input
# ... | <p>If you simply want all the arguments of a function converted to <code>np.array</code>, it is quite helpful to use a decorator. </p>
<pre><code>import numpy as np
def np_decorator(func):
def wrapper(*args, **kwargs):
# silently convert arguments to np.array
new_args = [np.array(x) for x in args... | python|python-3.x|numpy | 2 |
20,345 | 50,591,669 | tf.image.resize_bilinear vs cv2.resize | <p>The results from <code>tf.image.resize_bilinear</code> are quite different from <code>cv2.resize</code>.</p>
<p>I found this a little bothersome. Set <code>align_corners=True</code> is not always reasonable because the four corners are not always supposed to be fixed in the corner. So is there anyway to make it a l... | <p>This is a known issue, please see
<a href="https://github.com/tensorflow/tensorflow/issues/6720" rel="noreferrer">https://github.com/tensorflow/tensorflow/issues/6720</a></p> | opencv|tensorflow|image-resizing|bilinear-interpolation | 11 |
20,346 | 45,615,850 | How to convert byte image from [0,255] to [-1,1] float range in Python for Tensorflow Mobilenet predictions? | <p>I'm an R user, new to both Python and TensorFlow, and have been struggling to get my retrained image classifier to actually make predictions when modifying <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/label_image" rel="nofollow noreferrer">label_image.py</a> for use with Mobilene... | <p><code>bytes</code> is literally a buffer of raw bytes, which lie in the range [0,255]. You can get the <code>int</code> values out by iterating over it. Then you can normalize.</p>
<pre><code>image = b'\x20\x30\x40'
normalized = [(x-128.)/128 for x in image]
print(normalized) # [-0.75, -0.625, -0.5]
</code></pre> | python|machine-learning|tensorflow|jpeg | 0 |
20,347 | 45,280,293 | Siamese Network using Rstudio Keras | <p>I'm trying to implement a siamese network using Rstudio Keras package. The network I'm trying to implement is the same network that you can see in <a href="https://sorenbouma.github.io/blog/oneshot/" rel="nofollow noreferrer">this post</a>.</p>
<p>So, basically, I'm porting the code to R and using Rstudio Keras imp... | <p>As pointed out by Daniel Falbel in his comment, the solution was updating R-keras package and then updating the tensorflow installation.</p>
<p>However, tensorflow package in R was not installing the latest 1.3 tensorflow version (it was reinstalling the 1.2 version).</p>
<p>To fix this problem, the URL to the cor... | r|tensorflow|rstudio|keras|conv-neural-network | 4 |
20,348 | 62,722,047 | plt.CLA or CLF in animations - Why does it not work for me to only show most recent plot? | <p>I want my animation only to show the most previous point, and I believe that I have to adjust something around this line: plt.gca().cla()</p>
<p>Can anyone tell me what I am doing wrong? In my animation, all the points stay visible, while I only want to show the most previous points. Any suggestions?</p>
<p>This is ... | <p>The line</p>
<pre><code>data = df.iloc[:int(i + 1)] # select data range
</code></pre>
<p>select all the rows from <code>0</code> to <code>i+1</code>, therefore you are showing a growing number of points at each frame. If you want to show only the current point, you should do:</p>
<pre><code>data = df.iloc[i] # sel... | python|pandas|matplotlib|seaborn | 0 |
20,349 | 62,565,765 | Why do you need to reassign variable after every change to Pandas Dataframe? | <p>Pandas Dataframes are suposed to be mutable, like lists. Therefore a change in the dataframe should be reflected in the previous reference.</p>
<p>However:</p>
<pre><code>df.drop(to_delete)
</code></pre>
<p>Does not delete the indexes in the variable to delete.</p>
<pre><code>df=df.drop(to_delete)
</code></pre>
<p>Y... | <p>We have the <code>inplace</code></p>
<pre><code>df.drop(to_delete, inplace=True)
</code></pre> | python|pandas|dataframe | 1 |
20,350 | 62,707,554 | How to create new csv from list of csv's in dataframe | <p>So I know my code isn't that close to right, but I am trying to loop through a list of csv's, line by line, to create a new csv where each line will list all csv's that met a condition. First column in all csv's is "date", I want to list the name of all csv's where <code>data["entry"] > 3</cod... | <p>I would do something like this. You need to modify the following snippet according to your needs.</p>
<pre><code>import pandas as pd
from glob import glob
from collections import defaultdict
# create and save some random data
df1 = pd.DataFrame({'date':[1,2,3], 'entry':[4,3,2]})
df2 = pd.DataFrame({'date':[1,2,3], ... | python|pandas|dataframe|csv|python-3.8 | 0 |
20,351 | 54,287,528 | Flask: Function is not returning any String and getting Internal Server Error 500 | <p>I am returning a bunch of strings to Front End using Flask RESTful API. The string is generated after a ML algo runs on the input string and classify this to a predefined Answer. The back-end is in MongoDB. </p>
<p>The code given below was working fine earlier. Ever since I have inserted the following lines (marked... | <p>I got the solution. I the below line</p>
<pre><code>slot_value tbl_df.loc[tbl_df.Combi.str.contains(y),'slot_value']
</code></pre>
<p>instead of <code>y</code> which is a <code>list</code>, I have changed it to <code>','.join(y)</code></p>
<p>To enlighten others: <code>le.inverse_transform</code> always produce a... | python|pandas | 0 |
20,352 | 54,450,767 | Shuffling pandas data frame rows while avoiding consecutive condition values | <p>I have a sample data frame read in using pandas. The data has two columns: 'item','label'. While I shuffle the df rows, I want to make sure the shuffled df does not have items that have the same consecutive labels.
ie. this is acceptable, because the labels 'a','b', and 'c' are not in consecutive order:</p>
<p>1: ... | <p>Thanks for the comments/pointers. I got it to work by: </p>
<pre class="lang-py prettyprint-override"><code>randomized = False
while not randomized:
xlist = xlistbase.sample(frac=1).reset_index(drop=True) # where xlistbase is the original file read in
# check for repeats
for i in range(0, len(xlist)):
... | python|pandas|shuffle | 0 |
20,353 | 54,359,740 | Modelling Loan Payments - Calculate IRR | <p>Working with loan data.
I have a dataframe with the columns: </p>
<pre><code>df_irr = df1[['id', 'funded_amnt_t', 'Expect_NoPayments','installment']]
</code></pre>
<p>ID of the Loan | Funded Amount | Expected Number of Payments | fixed instalment of the annuity.</p>
<p>I have estimated the number of payments with... | <p><code>numpy.irr</code> is the wrong formula to use. That formula is for irregular payments (e.g. $100 in month 1, $0 in month 2, and $400 in month 3). Instead, you want to use <code>numpy.rate</code>. I'm making some assumptions about your data for this solution:</p>
<pre><code> import numpy as np
df_irr['rate'] =... | python|pandas|pivot|reshape|irr | 0 |
20,354 | 54,473,924 | Splittig data in python dataframe and getting the array values automatically | <pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv('D:\ history/segment.csv')
data = pd.DataFrame(data)
data = data.sort_values(['Prob_score'], ascending=[False])
one = len(data)
actualpaid_overall = len(data.loc[data['paidstatus'] == 1])
data_split = np.array_split(... | <p>I believe you need list comprehension and for count is possible use simplier way - <code>sum</code> of boolean mask, <code>True</code> values are processes like <code>1</code>, then convert list to numpy array and use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html" rel="nofollow nore... | python|pandas|numpy | 1 |
20,355 | 73,738,464 | How to speed up pandas transform function? | <p>I'm trying to speed up or vectorise the following slow code</p>
<pre><code> def is_outlier(s):
lower_limit = 0
upper_limit = s.mean() + (s.std() * 1)
valid = s.between(lower_limit, upper_limit)
s[~valid] = np.NaN
return s
df["Difference"] = df.groupby("C... | <p>Using a custom function in <code>.transform</code> can be very costly because Pandas can't use the vectorized internal functions on the full dataframe. If you have a lot of groups (i.e. different customers) then this</p>
<pre class="lang-py prettyprint-override"><code>upper_limit = (
df.groupby("CustomerNam... | python|pandas | 1 |
20,356 | 71,417,710 | creating pandas function equivalent for EXCEL OFFSET function | <p>Let's say input was</p>
<pre><code>d = {'col1': [1,2,3,4,5,6,7,8,9,10],
'col2': [1,2,3,4,5,6,7,8,9,10],
'col3': [1,2,3,4,5,6,7,8,9,10],
'offset': [1,2,3,1,2,3,1,2,3,1]}
df = pd.DataFrame(data=d)
</code></pre>
<p>I want to create an additional column that looks like this:</p>
<pre><code>df['output'] = [1, 4, 9,... | <p>You use <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer">np.select</a>. To use it, create each of the column <code>sum</code> (1, 2, 3 ... as needed) as the possible choices, and create a boolean masks for each value in offset column as the possible conditons.</p... | python|excel|pandas | 3 |
20,357 | 71,394,944 | Convert parse text file into csv file using python? | <p>I have following sample data from my text file. I am trying to convert that text file into csv file to clean the data.</p>
<p>The file text look like:
<a href="https://i.stack.imgur.com/YQZfy.png" rel="nofollow noreferrer">data</a></p>
<p>Text data:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-... | <p>As mentioned, you can use Pandas fixed width format reader to help with this.</p>
<p>The following shows a slight variation to try and avoid specifying a large fixed <code>skiprows</code> parameter to skip over all of the lines at the start. It attempts to locate the actual start of the lines of data.</p>
<p><code>s... | python|pandas|csv|xlrd | 0 |
20,358 | 52,200,599 | Add DropOut after loading the weights in Keras | <p>I am doing king of transfer learning. What I have done is First train the model with the big datasets and save the weights. Then I train the model with my dataset by freezing the layers. But I see there was some overfitting. So I try to change the dropout of the model and load the weights since the numbers are chang... | <p>I recommend you to load the weights using the function <code>model.load_weights("weights_file.h5")</code> and then try the following:</p>
<pre><code>for layer in model.layers:
if hasattr(layer, 'rate'):
layer.rate = 0.5
</code></pre>
<p>Since only the Dropout layers have the attribute <code>rate</code>... | python|tensorflow|keras|nlp|transfer | 2 |
20,359 | 52,250,762 | python-Interpolate polynomial where coefficients are matrices | <p>I have a polynomial of the form:</p>
<pre><code>p(y) = A + By + Cy^2 ... + Dy^n
</code></pre>
<p>Here, each of the coefficients <code>A,B,..,D</code> are matrices (and therefore <code>p(y)</code> is also a matrix). Say I interpolate the polynomial at <code>n+1</code> points. I should now be able to solve this syst... | <p>Essentially, you're just doing 3600 12d polynomial regressions and composing the coefficients into matrices. For instance, the component <code>p(y)[0,0]</code> is just:</p>
<pre><code>p(y)[0, 0] = A[0, 0] + B[0, 0] * y + C[0, 0] * y**2 ... + D[0, 0] * y**n
</code></pre>
<p>The problem is that <code>np.linalg.solv... | python|numpy|linear-algebra | 1 |
20,360 | 60,526,866 | Create new ordinal variable from interval variable in Data frame preferably using list comprehension | <p>I want to create a new categorical variable in my dataframe based on an existing interval variable that simply aggregates the unique values into a smaller set of levels/values of the new variable.
I thought using a list comprehension below would be straight forward but I am getting the following error:</p>
<pre><co... | <p>Use <code>np.select</code></p>
<pre><code>cond1 = df['year'].between(1995,1999)
cond2 = df['year'].between(2000,2004)
cond3 = df['year'].between(2005,2009)
cond4 = df['year'].between(2010,2014)
df['new_val'] = np.select((cond1,cond2,cond3,cond4),
('val1','val2','val3','val4'),
... | python|pandas|list-comprehension | 0 |
20,361 | 60,422,693 | Weird indexing using numpy | <p>I have a variable, x, that is of the shape (2,2,50,100). </p>
<p>I also have an array, y, that equals np.array([0,10,20]). A weird thing happens when I index x[0,:,:,y]. </p>
<pre><code>x = np.full((2,2,50,100),np.nan)
y = np.array([0,10,20])
print(x.shape)
(2,2,50,100)
print(x[:,:,:,y].shape)
(2,2,50,3)
print(x[0... | <p>This is how numpy uses advanced indexing to broadcast array shapes. When you pass a <code>0</code> for the first index, and <code>y</code> for the last index, numpy will broadcast the <code>0</code> to be the same shape as <code>y</code>. The following equivalence holds: <code>x[0,:,:,y] == x[(0, 0, 0),:,:,y]</cod... | python|numpy | 24 |
20,362 | 60,732,036 | Grouping Ages in panda | <p>I am trying to group an age column into various groups. The groups are </p>
<pre><code>(“Children”: 0-14 years; “Youth”: 15-24 years; “Adults”: 25-65 years; “Seniors”: 65 +)
</code></pre>
<p>I did try using panda cut but it seems like my bin values are way more than the labels, here's my code so far</p>
<pre><cod... | <p>Yes: you gave 6 cutoffs for 4 bins. Revisit the documentation on how to specify those partition values. You need to eliminate the superfluous ones, likely 14 and 24. Also note that 0 is superfluous, unless you're making a category for pre-borns.</p>
<p>You have 4 categories; this mandates 3 partition values.</p>
<... | python|pandas | 0 |
20,363 | 60,634,196 | How to manually arrange rows in pandas dataframe | <p>I have a small dataframe produced from value_counts() that I want to plot with a categorical x axis. It s a bit bigger than this but:</p>
<pre><code>Age Income
25-30 10
65-70 5
35-40 2
</code></pre>
<p>I want to be able to manually reorder the rows. How do I do this?</p> | <p>You can reorder rows with .reindex:</p>
<pre><code>>>> df
a b
0 1 4
1 2 5
2 3 6
>>> df.reindex([1,... | python|pandas | 4 |
20,364 | 60,611,941 | Why is my tensorflow generator function so slow? | <p>Below generator function is too slow. Is there a way by which we can optimise this code ?.
train_dataset_c1 is train dataset for Class 1 of the form image,1
train_dataset_c0 is train dataset for Class 0 of the form image,0</p>
<pre><code>def generator(positive_dataset, negative_dataset):
while True:
for pos_rec... | <p>If you are using tensorflow 2.0 I'd recommend you using the tf.data API to speed up your pipeline. </p>
<p>Actually there is a <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_generator" rel="noreferrer">from_generator</a> function that you can apply to your generator to speed it up </p>
<p... | deep-learning|generator|tensorflow2.0 | 5 |
20,365 | 72,524,434 | Trying to mask a dataset based on multiple conditions | <p>I am trying to mask a dataset I have based on two parameters</p>
<ol>
<li><p>That I mask any station has a repeat value more than once per hour
a) I want the count to reset once the clock hits a
new hour</p>
</li>
<li><p>That I mask the data whenever the previous datapoint is lower than the current datapoint if it's... | <p>Basically you want to mask two things, the first being a duplicate value per station & hour. This can be found by grouping by station and the hour of valid, plus the precip column. On this group by you can count the number of occurances and check if it is more than one:</p>
<pre><code>df.groupby(
[df.station, ... | pandas|dataframe | 1 |
20,366 | 72,633,103 | Backreference in tf.strings.regex_replace | <p>I want to remove repeated characters e.g. hhhh, verrrry from a given string using tf.strings.regex_replace. I used the following expression</p>
<pre><code>lcased = tf.strings.regex_replace(lcased, r'(.)\1{2,}', r'\1') # repeated chars
</code></pre>
<p>But it throughs an error</p>
<pre><code>"tensorflow.python.... | <p>You can use the code below as a workaround to remove repeated characters from a string.</p>
<pre><code>import re
s = s = 'verrrry, hhhhhh'
new_s = re.sub(r'([a-z])\1+', r'\1', s)
print(new_s) #very, h
</code></pre> | python|regex|string|tensorflow | 0 |
20,367 | 40,704,586 | Split column on positive/negative values? | <p>So I came across this another little annoying problem, as another obstacle in my first steps of learning python.</p>
<p>I have outcome column which has positive/negative/zero values (winnings, loss, no commitment). I would like to split into winnings/loss based on sign, also zeroes would populate zeroes, and negati... | <p>Theres's more than one way to do this, but essentially what you want to do is apply a function that returns 0 if the number is less than or equal to zero, and the input number otherwise. And then do the opposite thing for losses. One way is:</p>
<pre><code>def winnings(value):
return max(value, 0)
def losses(v... | python|pandas | 5 |
20,368 | 18,254,269 | Matlab to Python conversion: undefined variable | <p>I am trying to convert a Matlab program into Python. It's not giving me the results I'd like.</p>
<p>Matlab Code:</p>
<pre><code>for jj=1:data_length %for each symbol in the input symbol sequence
[a,b]= min(abs(phase_recovered(jj)-U_alphabets));
quantized(jj)=U_alphabets(b);
end
</cod... | <p>I think you don't want the line <code>b = diff[a]</code>, you want something more like:</p>
<pre><code>quantized=zeros(data_length,dtype='complex')
for jj in arange(0,data_length):
diff=np.absolute((phase_recovered[jj]-u_alphabets))
b = diff.argmin()
quantized[jj] = u_alphabets[b]
</code></pre>
<p>Also... | python|matlab|numpy | 1 |
20,369 | 61,648,305 | update datatable on bokeh barchart tap | <p>I have made a bokeh bar chart and a datatable from a pandas dataframe display next to eachother on a webpage using django. I want to click on the bar chart and change the displayed data table rows based on the title of the bar chart.</p>
<p>I have put an example below. Based on the example I want to click a bar on ... | <p>Here's a working example based on your code that demonstrates the described behavior:</p>
<pre class="lang-py prettyprint-override"><code>from bokeh.io import show
from bokeh.layouts import row
from bokeh.models import ColumnDataSource, HoverTool, DataTable, TableColumn, CDSView, CustomJS, IndexFilter
from bokeh.pl... | python|bokeh|pandas-bokeh | 1 |
20,370 | 61,952,409 | How to delete the same elements in two arrays or lists?And the elements are arrays or lists | <p>Best solved in python3.
I have tried to use 'remove' to solve it.But 'list.remove()' can't handle this, it doesn't support to operate 'list in list'.
Many thanks!!! </p>
<pre><code>input:label = [[1, 1], [2, 1], [1, 2], [2, 2], [3, 3]]
target = [[2, 2], [3, 2], [2, 3], [3, 3]]
output: c = [[2, 2], [3, 3]]
</... | <pre><code>label = [[1, 1], [2, 1], [1, 2], [2, 2], [3, 3]]
target = [[2, 2], [3, 2], [2, 3], [3, 3]]
c = []
for tar in target:
if tar in label:
c.append(tar)
print(c) # output: c = [[2, 2], [3, 3]]
</code></pre> | python|arrays|list|algorithm|numpy | 2 |
20,371 | 62,020,700 | Is there a better (Pythonic) or Django way of doing using a table with slight differences across multiple pages? | <p>I'm currently using pandas to create a table which contains prices/data that is a multiple of the 'base' price. for e.g desired function</p>
<pre><code>Table I (on page1.html)
.---.-----------.-----------.------------.
| | A | B | C |
:---+-----------+-----------+------------:
| 1 | $30 ... | <p>How about something like this?</p>
<p>In <code>views.py</code>:</p>
<pre><code>from django.shortcuts import render
MULTIPLES = [1, 1.25, 1.5]
def calculate_rows(prices):
rows = []
for mult in MULTIPLES:
rows.append(
[mult * price for price in prices]
)
return records
def ... | python|django|pandas | 1 |
20,372 | 57,783,623 | Comparing two datetimestamp column , if that datetimestamp is present than create new row datetimestamp with default value | <p>I have dataframe file in which there are 9 columns , 1st column name is <code>adjusted_time</code> in which <code>datetime</code> stamp are the values but some of the <code>datetime</code> stamp values are missing. 5th column name is <code>daterange</code> in which the <code>datetime</code> stamp are in sorted and r... | <pre><code>def add_new(df):
for x in df['daterange']:
if x in list(df['adjusted_time']):
pass
else:
df.loc[len(df),:] = [x, 999, 999, 999, x]
return df
</code></pre>
<p>This is not the ideal way of doing it. I tried to use lambda but can't really do assignments inside lamb... | python|pandas|timestamp|multiple-columns | 0 |
20,373 | 57,898,696 | Whats does X of imputer = imputer.fit(X[:,1:3]) stand for, whats the meaning of imputer.fit(X[:,1:3])? | <p>I m working on a preprocessing a data set, i get the error cause of the line
imputer = imputer.fit(X[:,1:3]). Which i dont get? I understand imputer = Imputer(missing_values = "NaN", strategy = "mean"), means replace missing values with mean value both in columns and rows. Then are we trying to fit into the model th... | <p>We use imputer from sci-kit library, and that is to fill missing values, we fill missing values using mean or mode of the considered column in data set.</p>
<p>In [:,1:3], the left side before the comma indicates to select all rows in data set, you can even specify a range of rows to select as instead of : say we s... | python-3.x|pandas|data-science|sklearn-pandas | 1 |
20,374 | 58,034,491 | Boolean on a dataframe | <p>Hey guys not sure if what I am trying to do is possible but I want to make a new column in a dataframe based on whether the string says 'complete'. if it does i want the new column row to say 1 if not 0. Since I have many records i put it in a loop.</p>
<pre><code>august_report['Lease'] = np.nan
for x in august_rep... | <p><code>Numpy</code> provides an easy way to do this if you have two values like your example (using <code>np.where</code>). If you have multiple cases, look at <code>np.select</code>.</p>
<pre><code>import numpy as np
august_report['Lease'] = np.where(august_report['Transaction Types'] =='Matched Lease transaction'... | python|pandas|dataframe | 1 |
20,375 | 58,138,971 | Merging list elements with in a list and converting it into string for conversion to decimall | <pre><code>import numpy as np
txor=np.array([1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1,
0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0,
1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1,
1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1,... | <p>Its hard to tell from your question whether you have already solved the "splitting" part of your problem. You do not need to convert to string to convert to decimal. To answer the second part of your question, here is a simple way to convert your list of binaries into decimals:</p>
<pre><code>def bin_to_dec(bins):
... | python-3.x|numpy|binary | 2 |
20,376 | 34,253,018 | rpy2.ipython errors with pandas / numpy | <p>Trying to use the <code>rpy2.ipython</code> (formerly 'rmagic') extension of IPython, to get interactive R (<code>%R</code> line magic and <code>%%R</code> cell magic functions), I get the following errors...</p>
<pre><code>louis ~ $ python
Python 3.5.1 |Anaconda 2.4.0 (64-bit)| (default, Dec 7 2015, 11:16:01)
[G... | <p>I am suspecting an incompatibility between versions of the LAPACK library: the one picked at runtime on your system, the one numpy was built with, and the one R was built with.</p>
<p>Installing numpy, R, and rpy2 from source in your virtual environment should solve the issue. An alternative would be to notify the ... | numpy|pandas|ipython|anaconda|rpy2 | 0 |
20,377 | 34,151,118 | Pandas: rsplit on whole dataframe | <p>All,</p>
<p>Is it possible to run an rsplit on a whole dataframe without iterating through all columns? I have a CSV file with loads of spaces after most of the fields (Not column specific).</p>
<p>Any help is much appreciated.</p>
<p>Edit:
the csv would look like the following and I would like to remove all the ... | <p>If you can split the reading from the removal of whitespace:</p>
<pre><code>df = pd.read_csv('mycsv.csv')
df_nowhitespace = df.applymap(str.strip)
</code></pre> | python|python-2.7|pandas | 0 |
20,378 | 37,035,082 | Fastest way to sort a large number of arrays in python | <p>I am trying to sort a large number of arrays in python. I need to perform the sorting for over 11 million arrays at once. </p>
<p>Also, it would be nice if I could directly get the indices that would sort the array.</p>
<p>That is why, as of now I'm using numpy.argsort() but thats too slow on my machine (takes ove... | <p>Well for cases like those where you are interested in partial sorted indices, there's <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.argpartition.html" rel="nofollow"><code>NumPy's argpartition</code></a>. </p>
<p>You have the troublesome <code>np.argsort</code> in : <code>w[np.argsort(z)... | python|performance|sorting|numpy|pandas | 4 |
20,379 | 54,716,377 | How to do gradient clipping in pytorch? | <p>What is the correct way to perform gradient clipping in pytorch?</p>
<p>I have an exploding gradients problem.</p> | <p>A more complete example from <a href="https://github.com/pytorch/pytorch/issues/309" rel="noreferrer">here</a>:</p>
<pre><code>optimizer.zero_grad()
loss, hidden = model(data, hidden, targets)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)
optimizer.step()
</code></pre> | python|machine-learning|deep-learning|pytorch|gradient-descent | 155 |
20,380 | 54,811,910 | Python pandas to_csv causes OSError: [Errno 22] Invalid argument | <p>My code is the following: </p>
<pre><code>import pandas as pd
import numpy as np
df = pd.read_csv("path/to/my/infile.csv")
df = df.sort_values(['distance', 'time'])
df.to_csv("path/to/my/outfile.csv")
</code></pre>
<p>this code reads from infile.csv which is a 3GB csv file successfully, sorts it and fails when tr... | <p>After exploring a lot of options, including the pandas library update to the latest version (1.2.4 as of today), changing the engine to "python" or "c", debugging, etc. I finally discovered what the issue was:</p>
<p>I had my <strong>CSV files</strong> stored in a folder that was <strong>constant... | python|pandas|csv | 14 |
20,381 | 49,579,978 | Selecting, slicing, and aggregating temporal data with Pandas | <p>I'm trying to handle temporal data with pandas and I'm having a hard time...
Here is a sample of the DataFrame :</p>
<pre><code>index ip app dev os channel click_time
0 29540 3 1 42 489 2017-11-08 03:57:46
1 26777 11 1 25 319 2017-11-09 11:0... | <p>If you just need to select a particular 8 hours, you can do as follows:</p>
<pre><code>start_time = datetime.datetime(2017, 11, 9,11, 2, 14)
df[(df['click_time' >= start_time)
& (df['click_time'] <= start_time+datetime.timedelta(0, 60*60*8))]
</code></pre>
<p>Otherwise I really think you need to look ... | python|pandas|time-series | 1 |
20,382 | 27,948,363 | Numpy Broadcast to perform euclidean distance vectorized | <p>I have matrices that are 2 x 4 and 3 x 4. I want to find the euclidean distance across rows, and get a 2 x 3 matrix at the end. Here is the code with one for loop that computes the euclidean distance for every row vector in a against all b row vectors. How do I do the same without using for loops?</p>
<pre><code> i... | <p>Here are the original input variables:</p>
<pre><code>A = np.array([[1,1,1,1],[2,2,2,2]])
B = np.array([[1,2,3,4],[1,1,1,1],[1,2,1,9]])
A
# array([[1, 1, 1, 1],
# [2, 2, 2, 2]])
B
# array([[1, 2, 3, 4],
# [1, 1, 1, 1],
# [1, 2, 1, 9]])
</code></pre>
<p>A is a 2x4 array.
B is a 3x4 array.</p>
... | python|numpy|machine-learning|vectorization | 42 |
20,383 | 73,295,729 | Creating time delta diff column based on groupby id | <p>I have the following sample df</p>
<pre><code> df = pd.DataFrame({'ID':['A','A','B','B'],'TimeStamp':['2022-08-02T17:33:44.358Z',
'2022-08-02T17:33:44.600Z',
'2022-08-02T17:33:44.814Z',
'2022-08-02T17:33:45.028Z']})
</code></pre>
<p>I want to groupby Id, and get the timedelta difference between the timestamps, i ... | <p>here is one way about it
btw, if you groupby ID, then the desired result you shared is incorrected. the third row should be zero since its a different ID</p>
<pre><code>#convert the timeStamp to timestamp
df['TimeStamp'] = pd.to_datetime(df['TimeStamp'])
# create post_data via vectorization intead of lambda, it'll ... | python|pandas|group-by | 1 |
20,384 | 73,398,484 | How can I map tuple key with df values updating an existing column? | <p>I am trying to map a column of my df with a dictionary. My dictionary contains tuple as key and I want to update an existing column value based on the key. How can I achieve that ?</p>
<p>sample df</p>
<pre><code>column1 column2 column3 column4 column5
None 123 test 999 42
</code></pre>
<p>sample dic... | <p>Create <code>Series with MultiIndex</code> by keys, convert columns in same order like keys by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> and then use <a href="http://pandas.pydata.org/pandas-docs/... | python|pandas|dictionary | 1 |
20,385 | 73,224,660 | python pandas print the first item in data extracted using get_group | <pre><code>import pandas as pd
tweets = pd.read_csv("file_name")
# Group the data by hashtag to extract books with the hashtag RoeVWade only
roevwade = tweets.groupby("hashtags").get_group("['RoeVWade']")
# Print the date of the first tweet with only the RoeVWade hashtag
print(roevwade[... | <p>After "group by" data index will be change, so you must reset index as below</p>
<pre><code>roevwade = tweets.groupby("hashtags").get_group("['RoeVWade']").reset_index(drop=True)
</code></pre> | python|python-3.x|pandas|series | 0 |
20,386 | 31,094,053 | capping values based on sporadic trigger | <p>I want to mention up front that this question is very close to question # 30990147 </p>
<p><a href="https://stackoverflow.com/questions/30990147/capping-values-after-a-trigger-level-in-a-different-variable-after-groupby">Capping values after a trigger level in a different variable _after GroupBy</a></p>
<p>The dif... | <pre><code>import pandas as pd
import numpy as np
import io # I use py3.4
# your data
raw_data = ',City,date,dist,a,b\n0,Chicago,5/25/2015,6.55,0.1,36\n1,Chicago,5/25/2015,3.93,0.16,21\n2,Chicago,5/25/2015,3.27,0.06,32\n3,Chicago,5/25/2015,2.62,-0.28,35\n4,Chicago,5/25/2015,1.96,0.09,37\n5,Chicago,5/25/2015,1.31,0.04... | python|pandas|triggers | 1 |
20,387 | 30,806,924 | conditionally dividing columns in dataframes based in values pandas | <p>So i have a dataframe that looks like this...let's call it df1</p>
<pre><code> Disease Gene1 Gene2 Gene3 Gene4
0 D1 1 1 26 1
1 D2 1 1 1 1
2 D3 1 18 1 17
3 D4 25 1 1 1
4 D5 1 1 1 1
5 D6 ... | <p>If you set the indices to 'Disease' for both dfs then you can call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html#pandas.DataFrame.div" rel="nofollow"><code>div</code></a>:</p>
<pre><code>In [127]:
df.set_index('Disease').div(df1.set_index('Disease')['Counts'], axis=0)
Out... | python|pandas|dataframe | 0 |
20,388 | 30,865,933 | Advanced indexing for sympy? | <p>With numpy, I am able to select an arbitrary set of items from an array with a list of integers:</p>
<pre><code>>>> import numpy as np
>>> a = np.array([1,2,3])
>>> a[[0,2]]
array([1, 3])
</code></pre>
<p>The same does not seem to work with sympy matrices, as the code:</p>
<pre><code>&g... | <p>Your <code>a</code> and <code>b</code> does not represent similar objects, actually <code>a</code> is a <code>1x3</code> "matrix" (one row, 3 columns), namely a vector, while <code>b</code> is a <code>3x1</code> matrix (3 rows, one column).</p>
<pre><code>>>> a
array([1, 2, 3])
>>> b
Matrix([
[1],... | python|numpy|sympy | 2 |
20,389 | 30,784,248 | Finding indexes for use with np.ravel | <p>I would like to use np.ravel to create a similar return structure as seen in the MATLAB code below:</p>
<pre><code>[xi yi imv1] = find(squeeze(imagee(:,:,1))+0.1);
imv1 = imv1 - 0.1;
[xi yi imv2] = find(squeeze(imagee(:,:,2))+0.1);
imv2 = imv2 - 0.1;
</code></pre>
<p>where imagee is a matrix corresponding to value... | <p>To retrieve indexes, I usually use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow">np.where</a>. Here's an example: You have a 2 dimensional array</p>
<pre><code>a = np.asarray([[0,1,2],[3,4,5]])
</code></pre>
<p>and want to get the indexes where the values are above a... | python|matlab|numpy|indexing | 3 |
20,390 | 31,169,229 | pandas pivot_table without grouping | <p>What is the best way to use pandas.pivot_table to calculate aggregated functions over the whole table without providing the grouping? </p>
<p>For example, if I want to calculate the sum of A,B,C into one table with a single row without grouping by any of the columsn:</p>
<pre><code>>>> x = pd.DataFrame({'... | <p>I think you're asking how to apply a function to all columns of a Data Frame: To do this call the <code>apply</code> method of your dataframe:</p>
<pre><code>def myfunc(col):
return np.sum(col)
x.apply(myfunc)
Out[1]:
A 6
B 21
C 5
dtype: int64
</code></pre> | python|pandas|pivot-table | 2 |
20,391 | 67,522,231 | Combine values from two columns into third where certain conditions are met in Python using np.where | <p>In the following example df, I want to combine values from col c and d into a new col e only when a = 1:</p>
<pre><code>a c d
1 ab xy
0 cd zf
0 sd zk
1 df sd
</code></pre>
<p>I wrote the following code:</p>
<pre><code>df['e'] = np.where(df['a'] == 1, ("ERR: " + df["c"] + "... | <p>This seems to work,</p>
<pre><code>import numpy as np
df['e'] = np.where(df['a'] == 1, "Err :" + df['c'] + "-" + df['d'], np.NaN)
</code></pre>
<hr />
<pre><code> a c d e
0 1 ab xy Err :ab-xy
1 0 cd zf NaN
2 0 sd zk NaN
3 1 df sd Err :df-sd
</code></... | python|numpy|where-clause | 0 |
20,392 | 67,325,614 | Is there a way to check if a list item is the ONLY item in the list? | <p>I have a <em>list of dictionaries</em>, the whole list represents different countries, and each dictionary includes basic data about each country as following:
<strong>example a</strong></p>
<pre><code>df.countries[3]
"[{'iso_3166_1': 'DE', 'name': 'Germany'}, {'iso_3166_1': 'US', 'name': 'United States of Amer... | <p>If you have dataframe like this:</p>
<pre class="lang-none prettyprint-override"><code> countries
0 [{'iso_3166_1': 'DE', 'name': 'Germany'}, {'is...
1 [{'iso_3166_1': 'US', 'name': 'United States o...
2 []
</code></pre>
<p>T... | python|pandas|list|dictionary|data-structures | 3 |
20,393 | 34,535,081 | Pandas groupby slice of a string | <p>I have a dataframe where I want to group by the first part of an ID field. For example, say I have the following:</p>
<pre><code>>>> import pandas as pd
>>> df=pd.DataFrame(data=[['AA',1],['AB',4],['AC',5],['BA',11],['BB',2],['CA',9]], columns=['ID','Value'])
>>> df
ID Value
0 AA ... | <p>You will need to create a grouping key somehow, just not necessarily on the DataFrame itself, for eg:</p>
<pre><code>df.groupby(df.ID.str[:1])['Value'].sum()
</code></pre> | python|pandas|dataframe | 9 |
20,394 | 34,719,882 | Python Pandas: getting the entire row having maximum value of one column | <p>I'm learning <code>Pandas</code> and stumble around finding the entire row of <code>Data frame</code> having maximum of one column</p>
<pre><code> A B
0 Fruits 122
1 Veggies 23
2 Eggs 223
</code></pre>
<p>How to get the entire row where B is maximum</p>
<p>This is what I tr... | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.argmax.html" rel="nofollow"><code>argmax</code></a> to get index of the maximum value and then pass it to <a href="https://www.google.ru/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&v... | python|pandas | 4 |
20,395 | 59,936,877 | Groupby behavior on set_index | <p>I have the following dataframe:</p>
<pre><code> year state 0
0 2010 AK 24.524096
1 2010 AL 186.981422
2 2010 AR 45.076047
3 2010 AZ 91.604977
4 2010 CA -109.784572
[...]
</code></pre>
<p>I want to set the index in the order <em>state>year</em> and have the values grouped in t... | <p>Doing <code>ratio.set_index(['state', 'year']).sort_index()</code> gives the correct output. Thanks to @ALollz.</p> | python|pandas|dataframe|pandas-groupby | 0 |
20,396 | 65,363,047 | i write that code with python using the library pandas and i had no errors and no results please can you help me , the result must be a graph | <p>Code:</p>
<pre><code>import pandas as pd
data = pd.Series((3,6,9,8,5,4,2,6,3,5,8))
data.plot()
data.plot(kind='line')
</code></pre> | <p>To clarify my previous post:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
data = pd.Series((3,6,9,8,5,4,2,6,3,5,8))
plt.plot(data)
plt.show()
</code></pre>
<p>(I deleted the previous post to avoid confusion)</p> | python|pandas | 0 |
20,397 | 65,283,758 | I'm trying to iterate through a panda series of dictionaries (obtained through an API) and I want to split them into desperate series in a dataframe | <p>I'm banging my head against the wall. I'm working with the GeoDeepDive API, and trying to "tidy" the data.
My code:</p>
<pre><code>import requests
import pandas as pd
response = requests.get("https://geodeepdive.org/api/articles?pubname_like=Geochronology")
data = response.json()
df = pd.json_... | <p>Could you try if this</p>
<pre><code>...
df1 = pd.DataFrame.from_dict(dic)
df1.link = df1.link.apply(lambda l: l[0]['url'])
df1.author = df1.author.apply(lambda l: ';'.join(d['name'] for d in l))
df1.to_csv("output_file.csv")
</code></pre>
<p>fits your needs?</p> | python|json|pandas|api | 0 |
20,398 | 65,133,266 | Read csv Pandas spaces multiples | <p><a href="https://i.stack.imgur.com/X71u7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X71u7.png" alt="enter image description here" /></a></p>
<p>I have a very similar dataset in csv file with two column,</p>
<p>For Example:
<em>In first row and first column</em>
Item:"Betarraga paquete 5 ... | <p>I am able to read the exact text block you have posted as 2 columns. Please try using <code>sep='\s\s+'</code></p>
<p>After that, you can write a function that takes in a row, checks if <code>qty</code> is <code>null</code>, fixes the <code>qty</code> column and the <code>Item</code> column and returns the row. Then... | python|pandas | 2 |
20,399 | 65,292,594 | Apply tolerance in iterative for loop | <p>I have set <code>p=2</code> as an initial value and I have calculated <code>dp</code> by using the relation. And I want to make an iteration by updating the new <code>p</code> value (for first iteration <code>p1=p+dp1</code>, the second iteration <code>P2=P1+dp2</code> and so on).</p>
<p>I want to stop my loop is th... | <p>As mentionned in the comments, use a while loop :</p>
<pre class="lang-py prettyprint-override"><code>A=0.002
f=10
z=4
p=2
y0=A*np.sin(2*np.pi*f*t+p)*np.exp(-z*t)
y1= A*np.cos(2*np.pi*f*t+p)*np.exp(-z*t)
c=np.sum((yexp-y0)*y1)
d=np.sum((y1)**2)
dp=np.divide(c,d)
epsilon = 1
tolerance=0.001
while epsilon > toleran... | python|numpy|loops|iteration | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.