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
376,000
52,191,644
Python read cells in excel sheet (xlsx) with some background color
<p>I am trying to read excel sheet(xlsx), which is using background color to differentiate values. </p> <p>I tried following libraries:</p> <ol> <li>pandas, did not find any option to read background color based cells.</li> <li><p>xlrd.</p> <pre><code>import xlrd xlrd.open_workbook("filename.xlsx", formatting_info=T...
<p>Even though it might be possible through Python, the easiest way should be filtering by Color in Excel, copying that Table and pasting it elsewhere, and then importing it as you would with any Excel file with Pandas.</p> <p>As commented by DeepSpace, it has been donde before through Python but it's quite troublesom...
excel|python-3.x|pandas|xlrd
0
376,001
60,350,353
Streaming images from directory and associating prediction with file name in tensorflow
<p>I have a trained model and I need to run inference on a large directory of images. I know I can make a generator using ImageDataGenerator.flow_from_directory but it is not obvious how to associate predicted results with file names. Ideally given a keras model + directory of images i'd like to have an array of file n...
<p>What you need to do is to separate the images into a different folder, corresponding to the class. The name of the folder should be the name of the class, by using the <code>ImageDataGenerator.flow_from_directory()</code> Keras will automatically infer the class names based on the directories. As an example, you sh...
python-3.x|tensorflow|keras
0
376,002
60,422,840
Linear Regresion with PyTorch gives NaN values
<p>I'm learning regression (<code>Profit</code> vs <code>R&amp;D</code>) with PyTorch. I have created the following script: </p> <pre><code>url =https://raw.githubusercontent.com/LakshmiPanguluri/Linear_Multiple_Regression/master/50_Startups.csv starup = pd.read_csv(url) profit = np.array(starup['Profit']).reshape(-1...
<p>I suggest the following changes:</p> <p>Change 1: remobing <code>requires_grad_(True)</code></p> <pre><code>rd_torch = torch.from_numpy(rd).float() </code></pre> <p>Change 2: including <code>model.train()</code> before the training loop:</p> <pre><code>... model.train() for i in range(iterations): ... </code></p...
python|pytorch|linear-regression|nan|gradient-descent
0
376,003
60,484,479
TensorFlow repeat function fails with ValueError: None values not supported
<p>I have implemented the following custom <code>Layer</code> that modify the size of a learnable parameter <code>seed_vectors</code> upon call according to the size of input <code>x</code> using the function <code>repeat</code>.</p> <pre><code>import tensorflow as tf from tensorflow.keras.layers import Dense from ten...
<p>The fix should be quite simple: use <code>b = tf.shape(z)[0]</code> instead. Explanation:</p> <p>The problem is that you are trying to repeat <code>b</code> times, which (I suppose) is the variable batch size. When not running in eager mode, this is represented by the value <code>None</code> in the shape. Thus, you...
tensorflow|keras|repeat
6
376,004
60,508,422
Creating URNs based on a row ID
<p>I have a pandas dataset that has rows with the same Site ID. I want to create a new ID for each row. Currently I have a df like this:</p> <pre><code>SiteID SomeData1 SomeData2 100001 20 30 100001 20 30 100002 30 40 </code></pre> <p>I am looking to achieve the below output</p> <p>Output...
<p>Add helper <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> converted to strings to column <code>SiteID</code> :</p> <pre><code>s = df.groupby(['SomeData1','SomeData2']).cu...
python-3.x|pandas
1
376,005
60,645,554
Fix duplicate rows when spliting csv using pandas
<p>I'm pretty new at Python and I can't find exactly what I need when searching. I tried a bunch of random things I saw on here with .merge and dropping duplicates but nothing is working for me.</p> <p>I have a file that has an <code>Images</code> column that can have any number of links separated by a comma. My goal ...
<pre><code>df = pd.concat([df,df['Images'].str.split(',',expand=True)], axis=1) df.columns = ['Dealer','Stock#','VIN','Images','Images1','Images2','Images3'] df.drop(columns=['Images'], inplace=True) </code></pre>
python|pandas|dataframe
0
376,006
60,563,856
Insert CSV through Pandas to SQLITE: How to avoid the Memory Error?
<p>I experience the memory error when trying write pandas dataframe from CSV into SQLITE database. The CSV file has 430 MB and 6 000 000 lines. </p> <p>For smaller files it works absolutely alright. However I would like to know how to avoid the Memory error for bigger files.</p> <p>The reading by chunks works fine an...
<p>When you insert records in a SQL database, two sizes are to be considered:</p> <ul> <li>the size of an individual <code>INSERT</code></li> <li>the global size between consecutive <code>COMMIT</code></li> </ul> <p>Because until the bunch of requests are commited, the database has to be able to rollback everything, ...
python|pandas|sqlite|csv
4
376,007
60,440,764
Select elements of an (n,n,2) numpy array with an (n,n) shaped mask in numpy without using loops
<p>I have a (n,n,2) numpy array whose elements I want to select based on a (n,n) mask without using loops. Is there a way to vectorize this operation in numpy? Say I have a numpy array </p> <pre><code>X = array([[[18, 8], [ 9, 2], [11, 4], [18, 14]], [[ 8, 10], [13, 5], ...
<pre><code>In [393]: I,J = np.nonzero(M) In [394]: I,J Out[394]: (array([0, 1, 1, 2]), array([0, 0, 1, 2])) In [395]: X[I,J,:] ...
python|arrays|numpy
0
376,008
60,477,626
Lookup values from one DataFrame to create a dict from another
<p>I am very new to Python and came across a problem that I could not solve.</p> <p>I have two Dataframe extracted columns only needed to consider, for example,</p> <pre><code>df1 Student ID Subjects 0 S1 Maths, Physics, Chemistry, Biology 1 ...
<p>Use <code>explode</code> and <code>map</code>, then you can do a little grouping to get your output:</p> <pre><code>(df.set_index('Student ID')['Subjects'] .str.split(', ') .explode() .map(df2.set_index('Subjects')['Subject ID']) .reset_index() .groupby('Subjects')['Student ID'] .agg(list)) Subje...
python|pandas|dictionary
1
376,009
60,615,895
Create diagnoal matrix from rows of a matrix in tensorflow
<p>I want to create a diagonal matrix from rows of another matrix. E.g. if given matrix is:</p> <pre><code> M=[e_1,e_2,e_3] </code></pre> <p>where $e_i$, i=1,2,3, is a vector. Now my output looks like this:</p> <pre><code>N = [e_1,0,0 0, e_2,0 0,0, e_3 ] </code></pre> <p>Assume 0 in the above matri...
<p>You can try this:</p> <pre><code>e_1 = np.array([1,2,3]) e_2 = np.array([4,5,6]) e_3 = np.array([7,8,9]) M = [e_1, e_2, e_3] # output = np.hstack(np.eye(e_1.shape[0])[:,:,None] * M) output = np.hstack(np.eye(len(M))[:,:,None] * M) </code></pre> <p>Output:</p> <pre><code>array([[1., 2., 3., 0., 0., 0., 0., 0., 0...
python|tensorflow|keras
1
376,010
60,610,529
Find last non-NaN value along axis in sorted multi-dimensional numpy array
<p>I'm looking at some 3D ocean temperature data (time, depth, lon, lat), and would like to extract the value at the lowest depth to create a 2D map of the temperature at the ocean floor. </p> <p>The ocean floor is a mask that creates somewhat of a sorted array along the depth axis with all NaN values concentrated at ...
<p>Numpy's <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.take_along_axis.html" rel="nofollow noreferrer">take_along_axis</a> should work for this. The last step can be expressed as follows:</p> <pre><code>B = np.take_along_axis(A, lv[:,None,:,:], axis=1).squeeze() </code></pre>
python|arrays|numpy|nan|numpy-ndarray
0
376,011
60,673,560
How delete rows from dataframe after comparison
<p>I want to filter my dataframe, use the part of <code>filter</code> with condition. And I do't know how to do it</p> <pre><code>import numpy as np table = pd.DataFrame({'movie': ['thg', 'thg', 'mol', 'mol', 'lob', 'lob'], 'rating': [3., 4., 5., np.nan, np.nan, np.nan], 'name': [...
<p>I believe you need:</p> <pre><code>table[table['name'].isin(filt.loc[filt['qty']&lt;3,'name'])] </code></pre> <hr> <pre><code> movie rating name 0 thg 3.0 John 1 thg 4.0 Paul </code></pre> <p>Note: i have changed the <code>filter</code> variable to <code>filt</code> since <code>filter</code> is ...
python|pandas|dataframe|filter|comparison
4
376,012
60,640,573
How do i insert blank rows after every new rows in pandas python
<p>I've a data</p> <pre><code> 0002 100789 Clearing charges 1000.00- Pending 0002 239890 Cheque bounce 20.00 client accepted 0001 789652 Export docs 200.00 Bank of Italy charges </code></pre> <p>Output file should be</p> <pre><code>0002 100789 Clearing charges 1000.00- ...
<p>You can use <code>df.to_csv()</code> to make your life a litter easier (and your code a little faster).</p> <p><code>df.to_csv()</code> then has an argument <code>line_terminator</code>. This controls what separates one row from another in the resulting <code>.csv</code> file.</p> <p>How exactly a newline is encod...
python|pandas
1
376,013
60,497,838
calculating ratio on pandas based on condition
<p>I have a dataframe similar to the following. </p> <pre><code>date mood count 1/1/16 negative 400 1/1/16 positive 500 3/1/16 negative 200 5/1/16 positive 700 5/1/16 negative 300 </code></pre> <p>I want to get the positive/negative ratio in a new column df['ratio'] for each date. If there i...
<p>Pivot into a temporary DataFrame, then divide <code>positive</code> by <code>negative</code>:</p> <pre><code>temp = df.pivot(index='date', columns='mood', values='count') temp mood negative positive date 1/1/16 400.0 500.0 3/1/16 200.0 NaN 5/1/16 300.0 700.0 (tem...
python|pandas|csv
1
376,014
60,686,281
pandas check if two values are statistically different
<p>I have a pandas dataframe which has some values for Male and some for Female. I would like to calculate if the percentage of both genders' values is <strong>significantly different or not and tell confidence intervals of these rates</strong>. Given below is the sample code:</p> <pre><code>data={} data['gender']=['ma...
<p>Use t-test.In this case, use a two t test, meaning you are comparing values/means of two samples.</p> <p><em>I am applying an alternative hypothesis; A!=B. I do this by testing the null hypothesis A=B. This is achieved by calculating a p value. When p falls below a critical value, called alpha, I reject the null h...
python-3.x|pandas|statistics
2
376,015
60,565,549
Related to multiple swamplots inside a figure Pandas
<p>This question is related to <a href="https://stackoverflow.com/questions/41492681/group-multiple-plot-in-one-figure-python">group multiple plot in one figure python</a>, "individual 28 plots". This is my code:</p> <pre><code>for column in df.columns[1:]: sns.set() fig, ax = plt.subplots(nrows=3, ncols=3) # ...
<p>Instead of iterating through columns, iterate through multiples of 9 with <code>range</code> to index the data frame by column number while placing each <code>swarmplot</code> into the <code>ax</code> array you define:</p> <pre><code>from itertools import product ... sns.set(style="whitegrid") for i in range(1, 10...
python|pandas|matplotlib|swarmplot
1
376,016
60,700,472
PyTorch AutoEncoder - Decoded output dimension not the same as input
<p>I am building a Custom Autoencoder to train on a dataset. My model is as follows</p> <pre><code>class AutoEncoder(nn.Module): def __init__(self): super(AutoEncoder,self).__init__() self.encoder = nn.Sequential( nn.Conv2d(in_channels = 3, out_channels = 32, kernel_size=3,stride=1), ...
<p>The mismatch is caused by the different output shapes of <code>ConvTranspose2d</code> layer. You can add <code>output_padding</code> of 1 to first and third transpose convolution layer to solve this problem.</p> <p>i.e. <code>nn.ConvTranspose2d(in_channels=1024,out_channels=512,kernel_size=5,stride=2, output_paddin...
python|computer-vision|pytorch|autoencoder|torchvision
3
376,017
60,397,322
Running tflite sample segmentation app with different model
<p>I am trying to run the sample app from <a href="https://github.com/tensorflow/examples/tree/master/lite/examples/image_segmentation/android" rel="nofollow noreferrer">tensorflow</a> for image segmentation with a different model. I would like to run it with the model <a href="https://github.com/sercant/android-segmen...
<p>You seem to have two unrelated problems</p> <p><strong>1) The method <a href="https://github.com/tensorflow/examples/blob/master/lite/examples/image_segmentation/android/lib_utils/src/main/java/org/tensorflow/lite/examples/imagesegmentation/utils/ImageUtils.kt" rel="nofollow noreferrer">scaleBitmapAndKeepRatio</a> s...
android|tensorflow|tensorflow-lite
0
376,018
60,467,136
Scaling of features produces all NaN values
<p>I have the following pandas data frame <code>df</code>:</p> <pre><code>COL1 COL2 COL3 0.0 -258.0 A 0.0 -262.2 A 0.0 -210.0 C 0.0 -84.0 B 0.0 -237.0 A 0.0 -277.2 B 0.0 -273.0 A 0.0 15.0 B 0.0 21.0 C 0.0 -61.8 C </code></pre> <p>I want to apply <code>RobustScaler</c...
<p>Are you sure that you are not missing something else? Because I've run your code with your dataset and it worked well.</p> <p>Before Scaler</p> <pre><code> COL1 COL2 COL3 0 0.0 -258.0 A 1 0.0 -262.2 A 2 0.0 -210.0 C 3 0.0 -84.0 B 4 0.0 -237.0 A 5 0.0 -277.2 B 6 0.0 -273.0 A ...
python|pandas|scikit-learn
1
376,019
60,344,310
Creating a custom cumulative sum that calculates the downstream quantities given a list of locations and their order
<p>I am trying to come up with some code that will essentially calculate the cumulative value at locations below it. Taking the cumulative sum almost accomplishes this, but some locations contribute to the same downstream point. Additionally, the most upstream points (or starting points) will not have any values cont...
<p>You can use <a href="https://pypi.org/project/networkx/" rel="nofollow noreferrer"><code>networkx</code></a> to deal with the relationships. First, make your order DataFrame like:</p> <pre><code>print(df_order) source target 0 Site 1 Site 3 1 Site 2 Site 3 2 Site 3 Site 4 3 Site 4 Site 5 4 Site 5 No...
python-3.x|pandas|dataframe|math|cumulative-sum
1
376,020
60,337,076
tensorflow custom loss function with additional input data
<p>I try to build a custom loss function for a sequential model. In this loss function y_true and y_pred are used to calculate an error. When I try to replace the y_true tensor, so all the true values from the model with external true values which should be the same, I get different results (about half of the expected ...
<p>Unless you set a seed for the model to use you will never get the same result even if you use the same code and the same data.</p>
python|tensorflow|keras|tensor|loss-function
0
376,021
60,475,895
Pytorch "upsample_bilinear2d_out_frame" not implemented for 'Byte'
<p>I have trained a custom object detection model using the steps described in this <a href="https://colab.research.google.com/github/pytorch/vision/blob/temp-tutorial/tutorials/torchvision_finetuning_instance_segmentation.ipynb#scrollTo=UYDb7PBw55b-" rel="nofollow noreferrer">link</a>. I am able to train my model but ...
<p>I was also getting the same error, seems that need to normalize the dataset before feeding to the model. I used albumentations for transformation &amp; normalization.<br /> Below is the code snippets:</p> <pre><code>def get_transform(train): if train: train_transform = A.Compose( [ A.Med...
python|pytorch|object-detection|torch|torchvision
0
376,022
60,638,431
filter a Pandas dataframe for added unique values
<p>I would like to know what I need to do in order to filter a dataframe, keeping unique values of <code>Name</code> column, adding values from <code>Value</code> column and adding a new column for counting appearances of each <code>Name</code></p> <p>what I have is this:</p> <pre><code> Name Type Value 0 appl...
<p>Try <code>groupby</code> method:</p> <pre><code>df.groupby(["Name","Type"]).agg(["count","sum"]) </code></pre> <p>Result:</p> <pre><code> Value count sum Name Type apple A 3 9 banana B 2 5 carrot C 1 3 pear P 1 4 </code></pre> <p>Howe...
python|pandas|vectorization
4
376,023
60,449,298
How to unseed a random sequence previously seeded in numpy?
<p>I'm trying to generate random numbers within a multiprosses function. My issue is I need to seed the first part of the random generation but not the second part. I would like the seed for the first part to be the same for all process.</p> <p>What I tried is unseed the generator by picking a random Int (<code>np.ran...
<p>You can save the state of the random number generator, and restore it later:</p> <pre><code>original_state = np.random.get_state() np.random.seed(seed) # ... stuff using your seeded random np.random.set_state(original_state) </code></pre>
python|numpy|random
1
376,024
60,519,964
How to train a custom model for object detection using models/official/vision/detection?
<p>How to train a custom model for object detection using <a href="https://github.com/tensorflow/models/tree/master/official/vision/detection" rel="nofollow noreferrer">models/official/vision/detection</a>?</p>
<p>To train a new model, the training entry is <a href="https://github.com/tensorflow/models/blob/master/official/vision/detection/main.py" rel="nofollow noreferrer">main.py</a>.</p> <p>Here are a few steps of how to add new models.</p> <p>If you want to just build a simple model, say MyRetinaNet, on top of current e...
tensorflow-model-garden
0
376,025
60,518,170
Tensorflow Serving - grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with: status = StatusCode. UNAVAILABLE
<p>I got the following issue when trying to serve TF models using TF serving server</p> <pre><code>grpc._channel._Rendezvous: &lt;_Rendezvous of RPC that terminated with: status = StatusCode.UNAVAILABLE details = "Connect Failed" debug_error_string = "{"created":"@1583228501.130612312","description":"Faile...
<p>It definitely seems to be indicating that no communication could be established between the TensorFlow server and the client.</p> <p>My suspicion is that the notation for specifying a default environment variable value (<code>${SERVING_PORT:-8500}</code>) is not supported for whatever reason.</p> <p>One way to tes...
tensorflow|tensorflow-serving
0
376,026
60,436,212
I do not understand why Python give me a np.darray object is not callable
<blockquote> <p><strong>I want to find the nearest point to point p but it does not work</strong></p> </blockquote> <pre><code>import numpy as np import matplotlib.pyplot as plt point = np.array([[1,1],[1,2],[1,3],[2,1], [2,2],[2,3], [3,1], [3,2], [3,3]]) p = np.array([2.5,2]) plt.plot(point[:,0], point[:,1], "ro") ...
<p>replace <code>distance(p, point[i])</code> with distance calculation</p> <pre><code>distance = np.zeros(point.shape[0]) for i in range(len(distance)):^M distance[i] = sum((p-point[i])**2)**0.5 </code></pre>
python|numpy
0
376,027
60,416,231
Groupy Pandas DataFrame with Multiple Conditions
<p>I need to groupby on a single field, then get the nlargest(14) records on a date field, then get the mean of another field, and I am getting stuck on the logic.</p> <pre class="lang-py prettyprint-override"><code>data = [['NRB000043', nan, None, Timestamp('2020-01-27 00:00:00')], ['NRB000042', nan, None, Timestamp...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.agg.html" rel="nofollow noreferrer"><code>.agg</code></a> method:</p> <pre><code>df.groupby('sid').agg({'timedate': lambda x: x.nlargest(14), 'measure': 'mean'}) print(df) timedate ...
python|pandas|dataframe
1
376,028
60,700,457
How to convert datatype of all columns in a pandas dataframe
<p>I have pandas dataframe with 200+ columns. All the columns are of type int. And I need to convert them to float type. I could not find a way to do it. I tried</p> <pre><code>for column in X_data: X_data[column].astype('float64') </code></pre> <p>But after the for loop, when I print <code>X_data.dtypes</code>, ...
<p>If you want to convert specific columns to specific types you can use:</p> <pre><code>new_type_dict = { 'col1': float, 'col2': float } df = df.astype(new_type_dict) </code></pre> <p>It will now convert the selected columns to new types</p> <p>I found it from ...
python|pandas
2
376,029
60,704,268
How to repeat only a certain element in a list?
<p>Assuming a list as follows:</p> <pre><code>article = ['a', 'b', 'c', 'd'] </code></pre> <p>and a variable named <code>times</code></p> <p>Now, based on the value of the variable <code>times</code>, I want to repeat just the element <code>'a'</code> in the <code>article</code> list that many times.</p> <p><strong...
<p>Use <code>+</code> for join lists:</p> <pre><code>['a']*times + ['b', 'c', 'd'] </code></pre> <p>In numpy is possible use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow noreferrer"><code>numpy.repeat</code></a> with <a href="https://docs.scipy.org/doc/numpy/reference...
python|python-3.x|pandas|numpy
9
376,030
60,380,897
Calculate cosine similarity between a pandas Dataframe column and a list containing string values
<p>I am currently doing this:</p> <pre><code>def word2vec(word): from collections import Counter from math import sqrt # count the characters in word cw = Counter(word) # precomputes a set of the different characters sw = set(cw) # precomputes the "length" of the word vector lw = sqrt(...
<p>You can use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.cosine_similarity.html" rel="nofollow noreferrer">cosine_similarity</a> function from <a href="https://scikit-learn.org/stable/" rel="nofollow noreferrer">sklearn</a> which is a vectorized version of cosine similarity com...
python|pandas|parallel-processing
0
376,031
60,334,907
Dataframe pct_change(), best way to ignore or evade the TypeError for columns
<p>Given the code:</p> <pre><code>import pandas as pd import numpy as np df_ = pd.DataFrame(np.array([[1.79, 1, 0, 0, 0, pd.Timestamp('2018-01-01 00:00:07'), 0.0, 1.3075932699341621, 0.14, 0.20999999999999996, 2.58], [1.83, 1, 0, 0, 0, pd.Timestamp('2018-01-01 00:00:07'), 1.05, 1.307593269934162...
<p>First if necessary convert columns to floats and then seelct only numeric columns by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer"><code>DataFrame.select_dtypes</code></a>:</p> <pre><code>def f(x): try: return x.astype(f...
python|pandas|numpy
2
376,032
60,457,276
Why do i get this error when I try to perform some logical operation on dataframes?
<p>This is my DataFrame:<br> <img src="https://i.stack.imgur.com/uJvVe.png" alt="DataFrame"></p> <pre><code>data.where(data["Gender"] == "Male") and data.where(data["Age"] == 19) </code></pre> <p>I'm trying to print matching values but i get this error. Explain the output.</p> <pre><code>----------------------------...
<p>You're getting this error as you're comparing with <code>and</code> when you should be using <code>&amp;</code>. You should also separate with brackets. Try the following.</p> <pre><code>data[(data['Gender'] == 'Male') &amp; (data['Age'] == 19)] </code></pre> <p>Have a look at this <a href="https://stackoverflow.c...
python|pandas|dataframe
2
376,033
60,643,029
model_main.py file is using Python2.7 instead of Python3
<p>I'm currently using python3 to run model_main.py file. I followed each step to <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md" rel="nofollow noreferrer">install object_detection api</a></p> <p>I've made sure that each command is run with a python3 prefix bu...
<p>offhand, I'd say that somehow /home/abrar/.local/lib/python2.7/site-packages/tensorflow/models/research/pycocotools is being added to your path which, by name, implies a directory full of python2.7 stuff. Try adding:</p> <pre><code>import sys print(sys.path) </code></pre> <p>to the top of your script to determine...
python|tensorflow
0
376,034
60,420,978
Using np.pad() on structured array
<p>Another <a href="https://stackoverflow.com/questions/60418843/numpy-expand-and-repeat">post</a> I had does exactly what I wanted, but I cannot seem to implement on a structured array.</p> <p>Say I have an array like so:</p> <pre><code>&gt;&gt;&gt; arr = np.empty(2, dtype=np.dtype([('xy', np.float32, (2, 2))])) &gt...
<p>Your padding works, it's the assignment to ar["xy"] that fails, you can't change the shape of a structure.</p> <pre><code>&gt;&gt;&gt; arr = np.empty(2, dtype=np.dtype([('xy', np.float32, (2, 2))])) &gt;&gt;&gt; ar2 = np.pad(arr['xy'], [(0, 0), (0, 2), (0, 0)], mode='edge') &gt;&gt;&gt; ar2.shape (2, 4, 2) &gt;&gt;...
python|numpy
2
376,035
60,584,314
Need clarification in Pareto Distribution Code in Python
<p>Can you please explain 'output.T' in code? I have searched on google, but could not find any answers to help to know the code better. The code is to plot Pareto distribution.</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from scipy.stats import pareto xm = 1 # scale alphas = [1, 2, 3] # s...
<p>For your case it looks like you'll have a list of lists converted into an array. The <code>.T</code> takes a transpose, similar to the operation on matrices from mathematics. You can see the difference via: <code>output.T.shape</code> vs. <code>output.shape</code></p> <p>here is a small example:</p> <pre><code>&g...
python|numpy|scipy
4
376,036
60,719,382
rewriting a loop in numpy for faster execution
<p>I am writing a function which accepts a numpy array <code>a</code> of length 200, and matrix <code>M</code> of size 200 x 200, and does the following operation :</p> <pre><code>for i in range(len(a)): x = a[i] for j in range(len(a)): y = a[j] z = M[i][j] d[i][j] = 2 * z/(y+x) return ...
<p>Numpy's ufuncs all have an <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.outer.html?highlight=outer#numpy.ufunc.outer" rel="nofollow noreferrer"><code>outer</code></a> method to perform operations "cross-wise" on two arrays. So to avoid most intermediate calculation and vectorize as far ...
python-3.x|numpy
2
376,037
60,661,377
Why does second iteration always fail?
<p>I am trying to create a dict of z_scores by filtering a dataframe based upon five locations.</p> <p>No matter which location is first in the list, I always get the first key:value pair placed into the dict, and no matter which location is second, I always get this error:</p> <pre><code>Traceback (most recent call ...
<p>In python, the interpreter puts a higher priority on your variable names in the local scope than method names, so when you use <code>z_score</code> as a variable name, it masks access to the <code>z_score</code> method name, if you change the name of your <code>z_score</code> variable, your code should run.</p>
python-3.x|pandas|numpy
0
376,038
60,610,053
Working with very large matrices in numpy
<p>I have a transition matrix for which I want to calculate a steady state vector. The code I'm using is adapted from <a href="https://stackoverflow.com/q/52137856/3972493">this question</a>, and it works well for matrices of normal size:</p> <pre><code>def steady_state(matrix): dim = matrix.shape[0] q = (matr...
<p>Here's some ideas to start with:</p> <p>We can use the fact that any initial probability vector will converge on the steady state under time evolution (assuming it's ergodic, aperiodic, regular, etc).</p> <p>For small matrices we could use</p> <pre class="lang-py prettyprint-override"><code>def steady_state(matri...
python|numpy|matrix|large-data|pytables
0
376,039
60,412,254
Separate column values by backslash pandas
<p>I have a dataframe like this:</p> <pre><code>data = {'id': [1,1,1,2,2], 'value': ['red','red\blue','yellow','oak','oak\wood'] } df = pd.DataFrame (data, columns = ['id','value']) </code></pre> <p>What I want is:</p> <pre><code>id value count 1 red 2 1 blue 1 1 yellow 1 2 oak 2 2 wood ...
<p>You can <strong>replace</strong> all non-alphanumeric characters from your value and then do a split</p> <pre><code>df1 = (df.assign(value = df['value'].replace({r'\W': ' '}, regex=True).str.split()) .explode('value') .groupby(['id','value'], sort=False) .size() .reset_index(name='count')) </cod...
python|pandas
0
376,040
60,666,996
In the pandas dataframe, \\ N is randomly exist and i want to remove it
<p>I made a <code>pandas.dataframe</code>.</p> <p>I got rid of <code>NAN</code> with <code>pandas.dropna</code>, but <code>\\N</code> wasn't removed by <code>dropna</code>.</p> <p>Please tell me how I can get rid of it.</p>
<pre><code>df = df.replace(r'^\\N$', np.nan, regex=True).dropna() </code></pre> <hr /> <p><em><strong>Code could be like:</strong></em></p> <pre><code>import pandas as pd import numpy as np from numpy import nan df = pd.DataFrame([ ['test1', 1], ['\\N', 2], ['test2', 3], [nan, 4], ['\\N', 5], [...
python|pandas|dataframe
3
376,041
60,663,217
Group non-unique datetime column by date and sum values in python
<p>I have dataframe <code>df</code> as below:</p> <pre><code> start_time end_time count 0 2020-02-03 08:42:21.997 2020-02-03 09:34:18.737 3116 1 2020-02-03 09:34:18.837 2020-02-03 10:16:56.583 2557 2 2020-02-03 10:17:00.480 2020-02-03 13:18:51.540 10911 3 2020-02-03 13:18:51.640 ...
<p>Super close, <code>datetime.dt.date</code> is how you access just the date potion of the datetime object (<a href="https://www.geeksforgeeks.org/python-pandas-series-dt-date/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/python-pandas-series-dt-date/</a>). Try:</p> <pre class="lang-py prettyprint-overrid...
python|pandas|datetime|data-processing
1
376,042
60,722,128
Resample Pandas time series at custom interval and get interval number within a year
<h3>Context:</h3> <p>I have a data frame similar to this, except that it extends over decades of data:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'time':['2003-02-02', '2003-02-03', '2003-02-04', '2003-02-05', '2003-02-06', '2003-02-07', '2003-02-08', '2003-02-09','2003-02-10', '2003-02-11...
<p>How about trying <code>pandas.Series.dt.dayofyear</code> and divide that result by the interval you want? This would be equivalent to <code>pandas.Series.dt.week</code> if you used 7 as your interval.</p> <p>The proof is left as an exercise for the reader.</p>
python|pandas
2
376,043
60,675,117
Returning A String From .loc Query
<p>I have a simple pandas dataframe:</p> <pre><code>import pandas as pd data = [['tom', 10], ['nick', 15], ['juli', 14]] df = pd.DataFrame(data, columns = ['Name', 'Age']) </code></pre> <p>If I select the Name from row index 1, I get a simple string object:</p> <pre><code>df.loc[1].Name Out[9]: 'nick' </code></pre...
<p>As @ayhan said in comment above, you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.item.html" rel="nofollow noreferrer"><code>pandas.Series.item()</code></a> like this:</p> <pre><code>&gt;&gt;&gt; df.loc[df.Age==15, 'Name'].values.item() 'nick' </code></pre> <p>You can a...
python|pandas|dataframe
4
376,044
60,479,144
Using for loop to grab values of one column based on the value of another column
<p>I am trying to grab all the values of one column based on the value of another. I found some helpful stackoverflow questions already that are related to mine, but the solution in those don't seem to work on a variable range. Do I need to do something different for a variable? </p> <p>I am trying to only grab the ...
<p>Can't you just <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html" rel="nofollow noreferrer">group by</a> the year and month and then proceed from there?</p> <pre><code>for _, v in df.groupby(['year', 'month'])['open']: tempOpenDF = v # do stuff </code></pre>
python|pandas|for-loop
1
376,045
60,355,956
convert this matrix equation into something numpy can understand
<p>I know how to solve basic linear matrix equations with numpy. </p> <p>However, I have a matrix A and the equation A^2 + xA + yI = 0, where x and y are not vectors, but rather a scalar. I is the identity matrix, and 0 is the zero matrix of dimensions matching A.</p> <p>This is a super easy on paper for small matric...
<blockquote> <p>The issue I am facing is parsing the equation in its form above to one that is in the form of a system of equations (or alternatively a linear matrix equation of the form Ax = B</p> </blockquote> <p>Say that <em>A</em> has <em>n</em> columns. For a square matrix <em>Q</em> with <em>n</em> columns, le...
python|numpy|linear-algebra
1
376,046
60,349,071
How to utilise the date_parser parameter of pandas.read_csv()
<p>I am getting an issue with the <code>timestamp</code> column in my csv file.</p> <blockquote> <p>ValueError: could not convert string to float: '2020-02-21 22:00:00'</p> </blockquote> <p>for this line:</p> <pre><code> import numpy as np import pandas as pd import matplotlib.pylab as plt from datetime import...
<h2>Performing Conversion On CSV Input Columns While Reading In The Data</h2> <p>Reading in CSV data applying conversion to the timestamp column to get float values:</p> <pre><code>&gt;&gt;&gt; df = pd.read_csv('~/Downloads/fx_intraday_1min_GBP_USD.csv', ... converters={'timestamp': ... ...
python|pandas|dataframe
3
376,047
72,819,809
NaNs not recognized in df.loc or for loops
<p>I currently have a df with a column <code>Outliers</code>. When I do:</p> <pre><code>df.Outliers.value_counts(dropna = False) </code></pre> <p>I get:</p> <pre><code>NaN 2862 1.0 600 0.0 257 </code></pre> <p>However, when I try to display only these rows with:</p> <pre><code>df.loc[df.Outliers == np.nan] #...
<p>Pandas needs help sometimes when working with <code>np.nan</code> as it isn't always recognized correctly. However, you can use a <code>isna()</code> to find all columns/rows where there is data that includes a nan</p> <pre><code>df = pd.DataFrame({ 'Column1' : [np.nan, 2, 3, 4], 'Column2' : [1, np.nan, 3, n...
python|pandas|dataframe|numpy|nan
0
376,048
72,572,973
Using tfrec files in Keras
<p>I feel like this should be simple but cannot for the life of me work it out.</p> <p>I have this melanoma dataset(<a href="https://www.kaggle.com/datasets/cdeotte/melanoma-512x512/code" rel="nofollow noreferrer">https://www.kaggle.com/datasets/cdeotte/melanoma-512x512/code</a>) (in tfrec format) downloaded to my loca...
<p>I figured it out. This will add all images to a list as 3d array.</p> <pre><code>def _parse_image_function(example_proto): return tf.io.parse_single_example(example_proto, features) def preprocess_image(image): image = tf.io.decode_image(image, channels=3) return image path = '/Users/adban/Dissertation...
tensorflow|keras|kaggle|tfrecord
2
376,049
72,702,323
how to group by dataframe and move categories to columns
<pre><code>lst = [ ['s001','b1','typeA'],['s002','b1','typeB'],['s003','b1','typeC'],['s004','b1','typeD'], ['s005','b1','typeA'],['s006','b1','typeB'],['s007','b1','typeC'],['s008','b1','typeD'], ['s009','b2','typeA'],['s010','b2','typeB'],['s011','b2','typeC'] ] df=pd.DataFrame(lst,columns=['sn','setting','sta...
<p>Let us do</p> <pre><code>out = pd.crosstab(df.setting,df.status,margins = True,margins_name = 'Total').drop(['Total']) # reset_index() Out[97]: status typeA typeB typeC typeD Total setting b1 2 2 2 2 8 b2 1 1 1 0 3 ...
python|pandas|dataframe
0
376,050
72,744,419
Slice 3d-tensor-based dataset into smaller tensor lengths
<p>I have a dataset for training networks, formed out of two tensors, my features and my labels. The shape of my demonstration set is [351, 4, 34] for features, and [351] for labels.</p> <p>Now, I would like to re-shape the dataset into chunks of size k (ideally while loading data with DataLoader), to obtain a new demo...
<p>You can reshape the input to the desired shape (first dimension is <code>n</code> times longer) while the label can be repeated with <a href="https://pytorch.org/docs/stable/generated/torch.repeat_interleave.html#torch.repeat_interleave" rel="nofollow noreferrer"><code>torch.repeat_interleave</code></a>.</p> <pre><c...
python|tensorflow|pytorch|pytorch-dataloader
1
376,051
72,790,441
Add hyperlinks to pandas Styler table depending on index and column of each cell
<p>I have a dataframe like</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>foo</th> <th>bar</th> </tr> </thead> <tbody> <tr> <td>Germany</td> <td>1.0</td> <td>2.0</td> </tr> <tr> <td>England</td> <td>3.0</td> <td>4.0</td> </tr> <tr> <td>France</td> <td>5.0</td> <td>6.0</td> </tr> ...
<p>The styler.format method takes a cell value and can restructure it, including formatting it into a hyperlink.</p> <p>Suppose your cell value was &quot;w;v&quot;, then <code>&quot;&lt;a x={0}&gt;{1}&quot;.format(cell_value.split(&quot;;&quot;))</code> would return <code>&quot;&lt;a x=w&gt;v&quot;</code>.</p> <p>The t...
python|pandas|dataframe
1
376,052
72,809,505
Overwriting vs mutating pytorch weights
<p>I'm trying to understand why I cannot directly overwrite the weights of a torch layer. Consider the following example:</p> <pre class="lang-py prettyprint-override"><code>import torch from torch import nn net = nn.Linear(3, 1) weights = torch.zeros(1,3) # Overwriting does not work net.state_dict()[&quot;weight&quo...
<p>This is because <code>net.state_dict()</code> first creates a <code>collections.OrderedDict</code> object, then stores the weight tensor(s) of this module to it, and returns the dict:</p> <pre class="lang-py prettyprint-override"><code>state_dict = net.state_dict() print(type(state_dict)) # &lt;class 'collections...
python|pytorch
1
376,053
72,603,256
Update or create from file CSV in Django
<p>In my view, I created this which allows to add several plants thanks to a CSV file :</p> <pre><code>class UploadFileView(generics.CreateAPIView): serializer_class = FileUploadSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.i...
<p>here you are</p> <pre><code>class UploadFileView(generics.CreateAPIView): serializer_class = FileUploadSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) file = serializer.validated_data['...
python|django|pandas|django-rest-framework
2
376,054
72,639,261
Unexpected behaviour in numpy np.where with np.logical_and
<p>I want to find an RGB pixel in a numpy tri-dimensional array (X/Y/RGB) created with Pillow</p> <pre><code>conditions = np.logical_and(np.logical_and(array[:,:,0]==rgb[0],array[:,:,1]==rgb[1]),array[:,:,2]==rgb[2]) res = np.flip(np.transpose(np.where(conditions))).tolist() </code></pre> <p>It works like a charm.</p> ...
<p>Your code seems as though it correctly identifies values within the given tolerance.</p> <p>Here's my test code:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np array = np.reshape(np.array([i%3 + (i//3) / 10 for i in range(27)]), (3,3,3)) print('array:', array, '', sep='\n') rgb = [0,1,2] for ...
python|arrays|numpy
2
376,055
72,552,605
How to fix Tensorflow Datasets memory leak when shuffling?
<p>I want to train a model on the Stanford Dog Breed dataset which I download using Tensorflow Datasets, but when I go to train the model in Google Colab with GPU, it results in a memory error and causes Colab to restart the runtime:</p> <pre><code>tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:39] Overriding ...
<p>I don't see the network that you use for training, But: <em>(<code>shuffle_files=True</code> then your data are shuffling)</em></p> <p>If I Understand Correctly (IIUC), your error came from the size of your images in the dataset. You can solve this by resizing images before use in training like below:</p> <pre><code...
python|tensorflow|memory|tensorflow-datasets
0
376,056
72,736,219
labeling Confidence interval and coefficient using ggplot in Pandas
<p>I tried to label coefficient and Confidence interval using the following code:</p> <pre><code>pp =p.ggplot(leadslags_plot, p.aes(x = 'label', y = 'mean', ymin = 'lb', ymax = 'ub')) +\ p.geom_line(p.aes(group = 1),color = &quot;b&quot;) +\ p.geom_pointrange(color = &quot;b&quot;,siz...
<p>The issue is that to get a legend you have to map on aesthetics. In <code>ggplot2</code> (the R one) this could be easily achieved by moving <code>color=&quot;b&quot;</code> inside <code>aes()</code> which however does not work in plotnine or Python. Maybe there is a more pythonistic way to get around this issue but...
python|pandas|ggplot2|plotnine
1
376,057
72,510,883
variational autoencoder with limited data
<p>Im working on a binary classificaton project, and im using VAE (variational autoencoder) to handle the imbalance between the 2 classes by generating new samples for the minority class.</p> <p>the first class (majority class) contains 20000 samples, and the second one (minority class) contains 500 samples.</p> <p>Aft...
<p>Though 500 training Images are not good enough to generate diversified images from a VAE, you can still try producing some. It's better to take mean of latents of 10 different images (or even more) and pass it through the decoder ( if you're already doing this, ignore it. If you're doing some other method, try this)...
tensorflow|autoencoder|data-augmentation|data-generation
0
376,058
72,561,693
python print array inside the dictionary
<p>I want to print 'array' inside the dictionary but my code gives me 'each value' of the array.</p> <p>for example, &quot;array_ex&quot; is a dictionary and has values like below with 12 rows for each array...</p> <pre><code>{&quot;0_array&quot;: array([[17., 20., 15., ..., 42., 52., 32.], [24., 33., 19., .....
<p>Simply loop over the rows:</p> <pre><code>for i,a in array_ex.items(): # or for a in array_ex.values() for row in a: print(row) </code></pre>
python|arrays|numpy
2
376,059
72,678,307
using a list as positional index for another list
<p>I have two Python lists.</p> <p>The first list (called <code>converted</code>) reported n values (columns) extracted from an Excel file. Each element in the list &quot;converted&quot; contains multiple column values extracted from the Excel file (see the output)</p> <p>The second list (called <code>values_index</cod...
<pre><code>&quot;&quot;&quot; If I interpret the issue description correctly the built in zip() function may meet the objective. &quot;&quot;&quot; converted = ['a', 'b', 'c', 'd', 'e', 'f'] value_index = [1, 2, 3, 4, 5, 6] desired_relationship = zip(value_index,converted) for relationship in desired_relationship: ...
python|arrays|pandas|database|list
0
376,060
72,752,927
Pandas centred rolling window rank returns wrong value
<p>I'm trying to calculate the rank of a column value within a rolling window in Pandas like this:</p> <pre><code>df = pd.DataFrame( [[1, 10], [2, 20], [3, 50], [4, 30], [5, 40]], columns=['order_col', 'rank_col']) df['r...
<p>The following is a workaround, you'd use rank in apply and explicitly take the center value.</p> <p>The code inspects the index of the series to recognize that it's the first window and not the last.</p> <pre><code>def series_rank_center(series): if 1 in series.index and len(series) &lt; 3: return series...
python|pandas|rolling-computation
1
376,061
72,772,487
Memory Leak With Custom Object Detection Model Tensorflow
<p>I am biggner in tensorflow. I used transfer learning machanism and create custom object detection model using &quot;ssd_resnet101_v1_fpn_keras&quot; pre-trained model.</p> <p>I follow the below documentation for custom traning:</p> <pre><code>https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/...
<p>For me, the solution was following:</p> <pre><code># first define detect_fn and decorate with tf.function detect_fn = tf.function(tf.saved_model.load(visa_icon_model)) # when predicting visa_icon_detections = detect_fn.signatures['serving_default'](input_tensor) </code></pre> <p>I did a stress test with about 100 ...
python-3.x|tensorflow|object-detection-api
1
376,062
72,800,632
Grouping by date range (timedelta) with Pandas
<p>This question was asked before, but I want to extend on it. Because I do not have enough experience points I could not comment on the question so I am reposting the link below followed by my comments:</p> <p><a href="https://stackoverflow.com/questions/46839032/grouping-by-date-range-with-pandas">Grouping by date ra...
<p>You can use a <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with a custom group:</p> <pre><code># convert to datetime s = pd.to_datetime(df['date'], dayfirst=False) # set up groups of consecutive dates within ± 3 days group = (...
python|pandas|datetime|pandas-groupby|pandas-resample
1
376,063
72,629,283
Getting "Performance Warning" when trying to add multiple columns in pandas DataFrame
<p>Please find below a dataframe:</p> <p><a href="https://i.stack.imgur.com/UeLR2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UeLR2.png" alt="enter image description here" /></a></p> <p>Logic: For every new entry, first I need to check time if it exists. If it exists, I want to add new column sup...
<p>Here is how you can avoid this warning while adding values one at a time:</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime import pandas as pd df = pd.DataFrame(columns=[&quot;time&quot;]).set_index(&quot;time&quot;) start = pd.to_datetime(datetime.now()) for i in range(288): ...
python|pandas|dataframe|performance
0
376,064
72,715,505
How to use Tochvision.Transforms
<p>I want to use <code>torchvision.transforms</code> but get the following error:</p> <p><code>TypeError: Input image tensor permitted channel values are [1, 3], but found 1080</code></p> <p>Using this code:</p> <pre><code>tensor = torch.tensor(image) jitter = torchvision.transforms.ColorJitter(brightness=.5, hue=.3) j...
<p>Your channel axis should be first, not last.</p> <p>Either use <a href="https://pytorch.org/vision/main/generated/torchvision.transforms.ToTensor.html" rel="nofollow noreferrer"><code>T.ToTensor</code></a> and input your NumPy array into the transformation pipeline. To apply multiple transforms such as what we are t...
python|pytorch|torchvision
0
376,065
72,750,294
Tensorflow requires numpy version ~=1.19.2, matplotlib requires numpy version 1.23.0
<p>I'd expect it to be a fairly common problem when installing a lot of python packages that there would be dependency collisions like package A depending on a certain version of package C and package B depending on another version of package C as a result of which both A and B cannot coexist in a project.</p> <p>In my...
<p>I believe you can try installing an older matplotlib version, which will likely be compatible with the python version required by tensorflow.</p> <p>That said, I recommend that you use Python's <a href="https://docs.python.org/3/tutorial/venv.html" rel="nofollow noreferrer">virtual environment</a> (if you're not alr...
python|numpy|dependency-management
2
376,066
72,548,193
Tensorflow: `tf.reshape((), (0))` works fine in eager mode but ValueError in Graph mode
<p>As the title, the function <code>tf.reshape((), (0))</code> works perfectly fine in eager mode. But when I use it in Graph mode, it returns:<br /> <code>ValueError: Shape must be rank 1 but is rank 0 for '{{node Reshape}} = Reshape[T=DT_FLOAT, Tshape=DT_INT32](Reshape/tensor, Reshape/shape)' with input shapes: [0], ...
<p>Might be related to this <a href="https://github.com/tensorflow/tensorflow/issues/46776" rel="nofollow noreferrer">bug</a>. Try something like this:</p> <pre><code>@tf.function def test_graph(): x = tf.reshape((), (0, )) return x b = test_graph() b #&lt;tf.Tensor: shape=(0,), dtype=float32, numpy=array([], ...
python|tensorflow|tensorflow2.0
1
376,067
72,723,140
Need Help Implementing a Rolling window | IndexError: Index 52 is out of bounds for axis 0 with size 14
<p>I'm running into an indexing error when trying to implement a rolling window for my data regression results.</p> <p>For example, I'm trying to run a rolling regression from weeks 1-52, 2-53, 3-54, 4-55... and so on.</p> <p>Here is the code that I have so far. For <code>data=rolling_window.iloc[y:x]</code>, how would...
<p>Here is the code that does a rolling regression.</p> <pre><code>def rolling_regression_stats(): tickers = df[['FDX', 'BRK', 'MSFT', 'NVDA', 'INTC', 'AMD', 'JPM', 'T', 'AAPL', 'AMZN', 'GS']] rolling_window = df iterable = zip(range(1110), range(52,1162)) for y, x in iterable: for t in tickers...
python|pandas|dataframe|statistics|statsmodels
0
376,068
72,506,015
Strange memory usage of a custom LSTM layer in tensorflow and training gets killed
<p>I'm trying to create a custom LSTMCell in TensorFlow. I have a CPU with 24GB of RAM (No GPU). Firstly I have created an LSTMCell as the default LSTMCell. The code is given below:</p> <pre><code>class LSTMCell(tf.keras.layers.AbstractRNNCell): def __init__(self, units, **kwargs): self.units = units ...
<p>I found the reason. LSTMCell is being called for every element of the sequence. For the given input shape of <code>(1874, 1024)</code>, in every forward call, the calculations on call are being done 1874 times, and it's keeping these intermediate data on memory to calculate the gradients. It was not my intention. I ...
python|tensorflow|neural-network|lstm|recurrent-neural-network
1
376,069
72,569,809
Live data is put inside of columns (making a dataset) but does not update when I use pd.merge, it only occurs on one row
<p>I am working on a project which involves python 3.9, the code collects live data from the sensors and builds a new dataset, I then try to update the data set and all goes well, untill I come up with the <code>pd.merge</code> , this only allows a single row to be merged onto one random row of the live data mitigating...
<p>I have used the line</p> <pre><code>pd.concat([df1, df2],axis=1) </code></pre> <p>Adds the columns in df1 to the end of df2 (rows should be identical)</p> <p>which helped solve the problem of my dataframe not updating.</p>
python|pandas|merge|spyder
1
376,070
72,661,441
add column and put desired value depending on the condition
<p><a href="https://i.stack.imgur.com/RrRoM.png" rel="nofollow noreferrer">screenshot of the dataframe table</a></p> <p>I want to have another column name final grade that will get the average grade and checks if the average grade is greater than &gt; or equal = to 75. And if so put 'Passed' and if not put 'FAILED'</p>...
<p>You need to use apply with a lambda function. The example below is from <a href="https://www.geeksforgeeks.org/using-apply-in-pandas-lambda-functions-with-multiple-if-statements/" rel="nofollow noreferrer">geeksforgeeks</a>. Hope it helps!</p> <p><code>df['Result'] = df['Maths'].apply(lambda x: 'Pass' if x&gt;=5 els...
python|pandas
0
376,071
72,503,111
How to have logarithmic bins in a Python loglog plot
<p>Is it possible to use matplotlib.pyplot.loglog with log binning?</p>
<p>Maybe use the function <code>set_xscale()</code> o <code>set_yscale()</code> e <code>semilogx()</code> o <code>semilogy()</code>. If you have to set both axes in the logarithmic scale, we use the function <code>loglog()</code>.</p>
python|numpy|matplotlib
-1
376,072
72,757,329
Python df.groupby(level=0).mean() looses columns
<p>So I wrote a program that generates analytical data, it has 60 rows and 37 columns. It concats perfectly, so I have all the tables I need going in order one after one (downwards). No columns or rows are missing.</p> <p><a href="https://i.stack.imgur.com/kk5pB.png" rel="nofollow noreferrer">example of rows</a></p> <p...
<p>It will take mean of only numerical columns I guess this is why you might be loosing columns.</p>
python|pandas|dataframe|concatenation
0
376,073
72,680,042
All my columns are indexes in pandas. How to solve that and 'reset' the index?
<p>So, When i do <code>print(mydf.columns)</code> with my one of my dataframes, i get this result:</p> <pre><code>Index([ 'facility', '2022-01-01', '2022-02-01', '2022-03-01', '2022-04-01', 'YTD', 'state_name' ], dtype='object' ) </code></pre> <p>And because of that I can't join this dataframe with another one...
<p>you can run <code>set_index</code> to set an index:</p> <pre><code>[ins] In [14]: df Out[14]: foo bar 0 1 3 1 2 4 2 3 5 [ins] In [15]: df.set_index(&quot;foo&quot;) Out[15]: bar foo 1 3 2 4 3 5 </code></pre>
python|pandas
1
376,074
72,648,464
Convert Dataframe to dictionary with one column as key and the other columns as another dict
<p>Currently I have a dataframe.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>A</th> <th>B</th> </tr> </thead> <tbody> <tr> <td>123</td> <td>a</td> <td>b</td> </tr> <tr> <td>456</td> <td>c</td> <td>d</td> </tr> </tbody> </table> </div> <p>I would like to convert this into a d...
<p>Consider the following:</p> <pre><code>import pandas as pd df = pd.DataFrame({'ID':[1,2,3], 'A':['x','y','z'], 'B':[111,222,333]}) </code></pre> <p>What you're going for would be returned with the following two lines:</p> <pre><code>df.set_index('ID', inplace=True) some_dict = {i:dict(zip(row.keys(), row.values)) fo...
python|pandas|dataframe|dictionary
0
376,075
72,795,990
How to split multiindex columns without creating 'nan' column name
<p>I have a data frame with multi-index columns like the below (the data frame has been flattened from a nested dictionary)</p> <pre><code>Index(['A/service1/service2/200', .... 'D/service1/service2/500/std'],) </code></pre> <p>Now when I try to split the columns using this line of code</p> <pre><code>df....
<p>You can use nested dictioanry comprehension with split nested keys:</p> <pre><code>c = ['A/service1/service2/200', 'D/service1/service2/500/std'] df = pd.DataFrame( [[3296, 1000]], columns=c, index=['ts']) print (df) out = {k: {tuple(k1.split('/')): v1 for k1, v1 in v.items()} ...
python|pandas|dataframe
0
376,076
72,734,323
how to assign the number in pandas dataframe for the unique value appearing in the row based on given column
<p><strong>Data Frame looks like</strong></p> <pre><code>Unique Id Date H1 2/03/2022 H1 2/03/2022 H1 2/03/2022 H1 3/03/2022 H1 4/03/2022 H2 9/03/2022 H2 9/03/2022 H2 10/03/2022 </code></pre> <p><strong>Expected Data Frame</s...
<p>There are a bunch of ways to do this, the primary issue is going to be that you need to treat the date as a date object so that October doesn't get moved ahead of September in your second group.</p> <pre><code>import pandas as pd df = pd.DataFrame({'Unique_Id': ['H1', 'H1', 'H1', 'H1', 'H1', 'H2', 'H2', 'H2'], 'Dat...
python|pandas
1
376,077
72,827,151
Reshape 3-d array to 2-d
<p>I want to change my array type as <code>pd.DataFrame</code> but its shape is:</p> <pre><code>array_.shape (1, 181, 12) </code></pre> <p>I've tried to reshape by the following code, but it didn't work:</p> <pre><code>new_arr = np.reshape(array_, (-1, 181, 12)) </code></pre> <p>How can I change its shape?</p>
<p>NumPy array dimensions can be reduced using various ways; some are:<br /> using <a href="https://stackoverflow.com/questions/18691084/what-does-1-mean-in-numpy-reshape"><code>np.squeeze</code></a>:</p> <pre><code>array_.squeeze(0) </code></pre> <p>using <code>np.reshape</code>:</p> <pre><code>array_.reshape(array_.s...
python|numpy
2
376,078
72,501,211
Python: show rows if there's certain keyword from the list and show what was the detected keyword
<p>I was trying to get a data frame of spam messages so I can analyze them. This is what the original CSV file looks like.</p> <p><img src="https://i.stack.imgur.com/I9W7k.png" alt="original data frame" /></p> <p>I want it to be like <img src="https://i.stack.imgur.com/2RIlH.png" alt="filtered data frame" /></p> <p>Thi...
<p>You can define a function that gets the result for each row:</p> <pre><code>def detect_keyword(row): for key in keyword: if key in row['text']: return key </code></pre> <p>then get it done for all rows with pandas.apply() and save results as a new column:</p> <pre><code>df['detected_word'] = ...
python|pandas
1
376,079
72,686,088
how to access the elements of a list that is a pandas object
<p>I have a listof characters (seqMut2) which is a series pandas object in dataframe, I try to browse this list as a normal list to retrieve the position of elements that are not spaces with this code:</p> <pre class="lang-py prettyprint-override"><code> index2 = chDeux[chDeux['allele'] == y].index.values index3...
<p>You can filter for the rows where the value is different from a space ' '</p> <pre><code>import pandas as pd df = pd.DataFrame({'a':list('my name is')}) a 0 m 1 y 2 3 n 4 a 5 m 6 e 7 8 i 9 s # Get only the values that are not empty strings print(df[df['a'].ne(' ')]) Output: a 0 m 1 y 3 n ...
python|pandas|dataframe
0
376,080
72,746,236
Number Formatting in DataFrame
<p>How can I format a subset of a DataFrame according to a custom formatting logic?</p> <p><strong>Before</strong>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;"></th> <th style="text-align: left;">Country</th> <th style="text-align: left;">Last</th> <th style="t...
<p>Original Data:</p> <pre><code>df = pd.DataFrame({'Country': ['United States', 'Japan','China','United Kingdom','Euro Area'], 'Last': [8.60, 2.50, 2.00, 9.10, 8.10], 'Previous': [8.30, 2.50, 2.10, 9.00, 7.40], 'Abs. Change': [0.30, 0.00, -0.10, 0.10, 0.70]})...
python|python-3.x|pandas|dataframe|python-2.7
1
376,081
72,588,053
if column a == value, drop rows where column b equals
<p>I am trying to drop rows in my df where SPCD == 104, drop rows where Age &gt;= 950 and for some reason I can't for the life of me figure out how to do it.</p> <pre><code>dropped_ages = d_age[ (d_age['SPCD'] == 104) &amp; (d_age['Age'] &gt;= 950) ] </code></pre> <p>This is a line of code I've tried, but it ended up d...
<p>Negate your condition:</p> <pre class="lang-py prettyprint-override"><code>d_age[(d_age[&quot;SPCD&quot;] != 104) | (d_age[&quot;Age&quot;] &lt; 950)] </code></pre> <p>This outputs:</p> <pre class="lang-py prettyprint-override"><code> SPCD Age 1 104 300 3 133 200 4 104 400 5 133 100 </code></pre>
python|pandas|dataframe|drop
4
376,082
72,520,974
pandas `to_numeric` integer downcast cast floats not to integer
<p>With this sample dataframe:</p> <pre><code>&gt;&gt;&gt; d = pd.DataFrame({'si': ['1', '2', 'NA'], 's': ['a', 'b', 'c']}) &gt;&gt;&gt; d.dtypes # si object s object dtype: object </code></pre> <h2>My first attempt was to use astype and the 'Int64' NA aware int type, but I got a</h2> <p>traceback</p> <pre><cod...
<p>Unfortunately, <code>pandas</code> is still adapting/transitioning to fully supporting integer <code>NaN</code>. For that, you have to explicitly convert it to <code>Int64</code> after your <code>pd.to_numeric</code> operation.</p> <p>No need to downcast.</p> <pre><code># Can also use `'Int64' as dtype below. &gt;&g...
python|pandas|casting
2
376,083
72,581,297
Merge two NumPy arrays into one
<p>Say I have the following two arrays, <code>a</code> and <code>b</code>:</p> <pre><code>import numpy as np a = np.array([[[1, 0], [1, 1]], [[1, 0], [0, 0]], [[0, 0], [1, 0]]]) b = np.array([[[0, 2], [0, 0]], [[0, 0], ...
<p>Maybe you can start with a matrix with zeros and then assign the flags one by one:</p> <pre><code>import numpy as np a = np.array([[[1, 0], [1, 1]], [[1, 0], [0, 0]], [[0, 0], [1, 0]]]) b = np.array([[[0, 2], [0, 0]], ...
python|arrays|numpy|numpy-ndarray|mask
4
376,084
72,659,366
Resampling dataframe in Python
<p>I'm trying to resample and plot the average temperature of a city from a dataframe by year using Pandas. I'm successfully creating a copy of the data however, I keep running into this issue. <a href="https://i.stack.imgur.com/1a3Dz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1a3Dz.png" alt="en...
<p>You only save the AverageTemperature column. Try keeping all columns, or at least include the Y column too:</p> <pre><code>df2 = df[(df['City'] == 'Aden') &amp; (df['Country'] == 'Yemen')].copy() </code></pre>
python|pandas|dataframe|google-colaboratory|resampling
0
376,085
72,746,988
Merge cells using python
<p>In the process of a loop that Reads each workbook (I have like 4 separate excel files), and copy each column, cell by cell, to the new spreadsheet, <strong>Could not get the formatting for the title which was merged cells and centered AND the line/cell borders</strong></p> <pre><code> ...
<p>I could not replicate #2 and #3. The cell borders and column widths are preserved from the original spreadsheets.</p> <p>I was able to fix the merged cells by adjusting the min and max columns of the <code>MergedCellRange</code>. They need to be increased by the number of columns added to the sheet so far.</p> <pre ...
python|excel|pandas|xlsxwriter
0
376,086
72,668,001
How to delete first row in a csv file using python
<p>i want to delete only first row (not the headers) of the csv in python I have tried many solutions with import csv or pandas but nothing have worked for me yet. all solutions either printed out the csv and didnt modify the original file.</p> <p>And important i do not want to print out or skip/ignore the first line i...
<p>After reading the csv file as csv reader, next() will return each row in the file, so can be solved like this:</p> <pre class="lang-py prettyprint-override"><code>import csv csv_file_name= '&lt;your_file_name&gt;.csv' file = open(csv_file_name) csvreader = csv.reader(file) # store headers and rows header = next(cs...
python|pandas|csv|variables
1
376,087
72,706,098
Changing date order
<p>I have csv file containing a set of dates.</p> <p>The format is like:</p> <pre><code>14/06/2000 15/08/2002 10/10/2009 09/09/2001 01/03/2003 11/12/2000 25/11/2002 23/09/2001 </code></pre> <p>For some reason <code>pandas.to_datetime()</code> does not work on my data. So, I have split the column into 3 columns, as day,...
<p>This will allow you to take the column of dates and turn it into pd.to_datetime()</p> <pre><code>#This is assuming the column name is 0 as it was on my df #you can change that to whatever the column name is in your dataframe df[0] = pd.to_datetime(df[0], infer_datetime_format=True) df[0] = df[0].sort_values(ascendi...
pandas|join
1
376,088
72,806,634
Calculating the Difference in values in a dataframe
<p>I have a dataframe that looks like this:</p> <pre><code>index Rod_1 label 0 [[1.94559799] [1.94498416] [1.94618273] ... [1.8941952 ] [1.89461277] [1.89435902]] F0 1 [[1.94129488] [1.94268905] [1.94327065] ... [1.93593512] [1.93689935] [1.93802091]] F0 2 [[1.94034818] [1.93996006] [1.93940095] ... [1.927008...
<p>This should be much faster, I've tested up till 1M elements per cell for 10 rows which took 1.5 seconds to calculate the diffs (but a lot longer to make the test table)</p> <pre><code>import pandas as pd import numpy as np import time #Create test data np.random.seed(1) num_rows = 10 rod1_array_lens = 5 #I tried wi...
python|pandas
1
376,089
72,737,550
Why tf.keras.layers.concatenate adds parameters to my model?
<p>I'm trying to convert a Tensorflow code into Pytorch. My UNet in Pytorch has different number of parameters than Tensorflow's. After many researches, I figured out that the concatenate step in my TF code adds parameters to my model (+3,133,440). Of course, I have some skepticism about that but the summary with and w...
<p>Here is some explications about the resolution of my problem, thanks to @Jan.</p> <ul> <li>In the UNet architecture, the skip connection part works differently as the ResNet one. The UNet needs to <strong>concatenate</strong> the outputs of the encoder part layers with the decoder layers ones, whereas the ResNet <st...
tensorflow|pytorch|conv-neural-network
0
376,090
72,700,511
How to split a Pandas column of different lists into multiple columns and set it as column names?
<p>I have the following Pandas Dataframe.</p> <pre><code>data = pd.DataFrame( { &quot;client&quot;: [&quot;first&quot;, &quot;second&quot;, &quot;third&quot;, &quot;fourth&quot;, &quot;fifth&quot;, &quot;sixth&quot;, &quot;seventh&quot;, &quot;eighth&quot;, &quot;ninth&quot;, &quot;tenth&quot;, &quot;eleventh&quot;...
<p>You can do</p> <pre class="lang-py prettyprint-override"><code>out = data.join(data['requiredFields'].str[0].str.get_dummies(sep=', ').replace({0: None, 1: 'y'})) </code></pre> <pre><code>print(out) client Lifetime Tokens path \ 0 first 24 30 kyc 1 second 24 30 co 2 th...
pandas|list|dataframe
0
376,091
72,615,061
How to count number of combinations in python?
<p>In this dataset: <a href="https://i.stack.imgur.com/SBhBV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SBhBV.png" alt="enter image description here" /></a></p> <p>I want to count number of matches between two teams.</p> <p>Is there any tool in python for this?</p>
<p>Assuming you want to count combinations independently of order, you can aggregate as <a href="https://docs.python.org/3/library/stdtypes.html#frozenset" rel="nofollow noreferrer"><code>frozenset</code></a> and use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.value_counts.html" rel="nofollow no...
python|pandas
3
376,092
72,504,402
Installing TensorFlow on M1 Chip - Issues. - PackagesNotFoundError: The following packages are not available from current channels:
<p>I have an M1 chip but am having issues installing Tensorflow. I've tried a number of different methods but I feel im completely stuck.</p> <p>I was following this particular tutorial - <a href="https://betterdatascience.com/install-tensorflow-2-7-on-macbook-pro-m1-pro/" rel="nofollow noreferrer">https://betterdatasc...
<p>I could able to install Tensorflow on Mac Os without any issue with these following steps</p> <pre><code>python3 -m venv ~/tensorflow-metal source ~/tensorflow-metal/bin/activate python -m pip install -U pip python -m pip install tensorflow-macos python -m pip install tensorflow-metal </code></pre>
python|tensorflow|apple-m1
0
376,093
72,778,660
Python/Pandas - Unstack or Melt multidimensional table
<p>I'm having a beginning to the language issue with unpivoting a table. I'm hoping that it's just a vocabulary thing and I'll be off and running. I have a table with three dimensions, within the dimensions, there are three elements and this table covers three time periods. The tables that I work with are more comple...
<p>Reading a Multi-Dimensional Table in CSV format:</p> <pre><code>df = pd.read_csv('df_pivoted.csv', header=[0,1,2], index_col=[0]) ... male_female Total M F adult_youth Total A Y Total A ...
python|pandas
2
376,094
72,499,706
numpy.vstack losing precision float16
<p>I'm trying to perform a precise calculation for linear regression using only one digit as precise number. without numpy it works just fine but numpy performs better for large amount of items that's why I need use numpy. But the issue is that when I build the matrix for the X axis I lose my decimal precision as you c...
<p>To control <code>dtype</code> in <code>concatenate</code> (and all 'stack'), the arguments have to match:</p> <pre><code>In [274]: np.vstack([np.array([1,2,3], 'float16'), np.ones(3,'float16')]) Out[274]: array([[1., 2., 3.], [1., 1., 1.]], dtype=float16) </code></pre> <p>Default dtype for <code>ones</code> ...
python|numpy|floating-point|precision|floating-accuracy
0
376,095
72,818,025
assign 0 when value_count() is not found
<p>I have a column that looks like this:</p> <pre><code>group A A A B B C </code></pre> <p>The value C exists sometimes but not always. This works fine when the C is present. However, if C does not occur in the column, it throws a key error.</p> <pre><code> value_counts = df.group.value_counts() new_df[&quot;C&q...
<p>One way of doing it is by converting series into dictionary and getting the key, unless not found return the default value (in your case it is 0):</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'group': ['A', 'A', 'B', 'B', 'D']}) new_df = {} character = &quot;C&quot; new_df[character] = df...
python|python-3.x|pandas|numpy
2
376,096
72,670,978
Invalid constraint using where in xpress optimizer
<p>How can I use a nonlinear function like <code>numpy.where</code> in xpress solver in Python? Is it possible? If not, what other method to use?</p> <p><a href="https://i.stack.imgur.com/y3Zg9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y3Zg9.png" alt="" /></a></p> <p><a href="https://i.stack.im...
<p>In order to use non-linear functions with xpress you have to wrap them as user functions by means of <a href="https://www.fico.com/fico-xpress-optimization/docs/latest/solver/optimizer/python/HTML/xpress.user.html" rel="nofollow noreferrer">xpress.user()</a>. Your code should look something like this:</p> <pre><code...
python|numpy|nonlinear-optimization|mixed-integer-programming|xpress-optimizer
0
376,097
72,750,074
ValueError: operands could not be broadcast together with shapes (3,5) (3,)
<p>I have 15 ode equations need to be solved simultaneously and I want to solve them using solve_ivp.</p> <p>There are each 5 states for T, co2, and q. The initial conditions are T=20, co2 = 0, q=0</p> <p>I tried to separate them into 3 lists, one for T, one for co2, and one for q.</p> <p>I am not sure how to resolve t...
<p>I am giving an example based answer as I recreated the exact error message. So what is the problem here is that you are not following <strong>Numpy broadcasting rules</strong>. Which basically says arrays can be broadcasted (given certain operation) if their <strong>dimensions</strong> are <strong>same</strong> or <...
python|numpy|scipy|ode
0
376,098
72,506,599
object from tfds.load() gives AttributeError: 'Tensor' object has no attribute 'map'
<p>I'm working on a project and I had to change the way the CIFAR10 dataset is brought into the program. Previously, the dataset was loaded from a GCS link, but I'm trying to do it with my code, getting this kind of data</p> <pre><code>ds = tfds.load('cifar10', split=['train'], shuffle_files=False, data_dir=self._data_...
<p>From the comments, thanks to: <strong>I'mahdi</strong>.</p> <p>To solve the Error of the question, I changed:</p> <pre><code>input_ds = input_ds.map(lambda x,y:(tf.cast(x, tf.int32),tf.cast(y, tf.int32))) </code></pre> <p>into:</p> <pre><code>img_ = tf.cast(input_ds, tf.int32) </code></pre> <p>And, with other change...
python|tensorflow|dataset
0
376,099
72,798,554
How to use multiprocessing to share a large database among processes
<p>The logic of my program is very simple, there's a fairly large (12000x5000, will be 12000x50000 in the future) database (currently CSV) and a single 12000x1 row, and it calculates the correlation (there's some more logic in the function to speed things up a bit, but that's the gist of it) between the row and each of...
<p>You can use <strong>shared memory</strong> so to avoid the slow inter-process communication. You can find a pretty good example in the post <a href="https://stackoverflow.com/questions/7894791/use-numpy-array-in-shared-memory-for-multiprocessing">Use numpy array in shared memory for multiprocessing</a>.</p> <p>Alter...
python|pandas|performance|multiprocessing|shared-memory
2