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
2,000
55,870,212
How to convert a numpy array dtype=object to a sparse matrix?
<p>I have an numpy array of dtype = object containing multiple other arrays for elements and I need to convert it to a sparse matrix.</p> <p>Ex:</p> <pre><code>a = np.array([np.array([1,0,2]),np.array([1,3])]) array([array([1, 0, 2]), array([1, 3])], dtype=object) </code></pre> <p>I have tried the solution given by ...
<p>You can't. This error arises when it tries to find the nonzero elements of <code>a</code>. A sparse matrix just stores the nonzero elements of a matrix. Try</p> <pre><code>np.nonzero(a) </code></pre> <p>If your array contained lists instead of arrays, it would work - sort of:</p> <pre><code>In [615]: a = np....
python|numpy|scipy
2
2,001
64,815,718
Filter column value from other columns' values and turn the results into multiple lists Pandas
<pre><code> import pandas as pd data = {&quot;Country&quot;: [&quot;AA&quot;, &quot;BB&quot;,&quot;CC&quot;,&quot;DD&quot;,&quot;EE&quot;,&quot;FF&quot;,&quot;GG&quot;], &quot;1990&quot;: [0,1,1,1,0,1,1], &quot;1991&quot;: [0,0,1,1,1,0,1], &quot;1992&quot;: [1,1,1,1,1,0,0], &quot;1...
<p>One way using dict comprehension with <code>groupby</code> on <code>axis=1</code>:</p> <pre><code>res = {name: i.index[i[name]].tolist() for name, i in df.set_index(&quot;Country&quot;).astype(bool).groupby(level=0, axis=1)} print (res) {'1990': ['BB', 'CC', 'DD', 'FF', 'GG'], '1991': ['CC', 'DD', 'EE', 'GG'], '...
python|pandas|list
0
2,002
64,945,683
Walk along 2D numpy array as long as values remain the same
<p><strong>Short description</strong><br> I want to walk along a numpy 2D array starting from different points in specified directions (either 1 or -1) until a column changes (see below)</p> <p><strong>Current code</strong></p> <p>First let's generate a dataset:</p> <pre><code># Generate big random dataset # first colu...
<p>You don't have to whole input array in while loop. You could just use the column that values you want to check.</p> <p>I refactored a little bit your code as well so there is no <code>while True</code> statement and so there is no <code>if</code> that raises error for no particular reason.</p> <p>Code:</p> <pre clas...
python|arrays|numpy
0
2,003
64,731,533
Great accuracy on IMDB Sentiment Analysis. Is there any train data leakage I'm missing?
<p>I'm getting an unusual high accuracy on a sentiment analysis classifier I'm testing with python <code>sklearn</code> library. This is usually some sort of training data leakage but I can't figure out if that's the case.</p> <p>My dataset has ~50k nonduplicated IMDB reviews.</p> <pre><code>import pandas as pd import ...
<p>A good way to test if there is data leakage would be to check the performance on the validation set in the repository you linked, <a href="https://github.com/ricardorei/lightning-text-classification/blob/master/data/imdb_reviews_test.csv" rel="nofollow noreferrer">here</a>.</p> <p>I downloaded the dataset and tried ...
python|pandas|machine-learning|scikit-learn|confusion-matrix
1
2,004
64,865,618
Create ID column in a pandas dataframe
<p>I have a dataframe containing a trading log. My problem is that I do not have any ID to match buy and sell of a stock. The stock could be traded many times and I would like to have an ID to match each finished trade. My original dataframe a sequential timeseries dataframe with timestamps. The below example illustrat...
<p>Try this:</p> <pre><code>m = df1['deal'] == 'buy' df1['ID'] = m.cumsum().where(m) df1['ID'] = df1.groupby('stock')['ID'].ffill() df1 </code></pre> <p>Output:</p> <pre><code> stock deal ID 0 A buy 1.0 1 B buy 2.0 2 C buy 3.0 3 A sell 1.0 4 C sell 3.0 5 A buy 4.0 6 A s...
python|pandas|dataframe
3
2,005
69,534,875
Exclude df rows where a dates field: time/seconds are between a specific period
<p>Morning All,</p> <p>I have a very large df but need to strip out data NOT between 8.30am AEST to 5pm UTC.</p> <pre><code># Dates are dd/mm/yyyy df ={ 'rfq_create_date_time': ['01/10/2021 00:00:00 AM', '02/10/2021 01:01:01 AM', '03/10/2021 05:00:00 AM...
<p>To use <code>between_time</code>, as you've probably realised, the date/time needs to be the index of the dataframe.</p> <p>When the date/time is a column in the dataframe you can use 'standard' filtering.</p> <pre><code>from datetime import time import pandas as pd # Dates are dd/mm/yyyy data = { &quot;rfq_cr...
python|pandas
1
2,006
69,599,377
Python Congressional Plotly TypeError: Object of type MultiPolygon is not JSON serializable for Congressional Districts
<pre><code>import pandas as pd from census import Census import geopandas as gpd import numpy as np import plotly.io as pio import plotly.express as px pio.renderers.default='browser' file_path = &quot;Path&quot; # Load Census Median Age by District Data c = Census(&quot;KEY&quot;) district_df = c.acs1.state_congre...
<ul> <li>it's not clear to me if your <em>geojson</em> is valid. Given you are plotting US census data, may as well use US census mapping data <a href="https://www.census.gov/geographies/mapping-files/time-series/geo/carto-boundary-file.html" rel="nofollow noreferrer">https://www.census.gov/geographies/mapping-files/ti...
python|pandas|plotly|choropleth
0
2,007
69,314,600
Python - Error in String literal str.replace
<p>I have attempted to replace a <code>string</code> in a column with either of the two commands below. For both of them, I am getting the &quot;SyntaxError: EOL while scanning string literal&quot; error. Please help/guide. Thanks.</p> <pre><code>df['filename'] = df['filename'].str.replace(&quot;H:\May2017\hb_ymvid\HB_...
<p><code>\</code> denotes escape sequence in <code>python</code>, if you mean literal <code>\</code> then use <code>\\</code>, i.e. replace</p> <pre><code>&quot;H:\May2017\hb_ymvid\HB_ED_S\Pictures1\05cropped_PC\&quot; </code></pre> <p>using</p> <pre><code>&quot;H:\\May2017\\hb_ymvid\\HB_ED_S\\Pictures1\\05cropped_PC\\...
python|pandas|dataframe
0
2,008
41,175,797
How to create a list of dictionaries
<p>I want to calculate data on the frequencies of words in documents grouped by year, and then place the data in a pandas dataframe. </p> <p>My routine creates a dictionary for each row, containing words and frequencies as keys and values. I then want to loop through years, appending the dictionaries to each other to ...
<p>As the previous poster mentioned, append() is a list method but not a dict method. This should work, though:</p> <pre><code>import pandas word_data = [] # list type word_counts_1 = {'year': '1965', 'word1':20, 'word2': 250, 'word3': 125} # dict type word_counts_2 = {'year':'1966','word1':150, 'word4': 250, 'word...
python|pandas|dictionary
1
2,009
53,899,752
How can I create a custom connection between two different keras layers in LeNet5 architecture?
<p>I am working on <a href="https://engmrk.com/lenet-5-a-classic-cnn-architecture/" rel="nofollow noreferrer">LeNet5</a> architecture. I want to implement a custom connection between the layers C3 and S2 as explained <a href="https://i.stack.imgur.com/UBhya.png" rel="nofollow noreferrer">here</a>. How do I have to defi...
<p><strong>You can create the following custom layer classclass:</strong></p> <pre><code>CustomLayer(tf.keras.layers.Layer): &quot;&quot;&quot; Custom layer with initialize matrix = connect_matrix. &quot;&quot;&quot; def __init__(self, activation, units, connect_matrix): super(CustomLayer, self).__init__() sel...
tensorflow|machine-learning|keras|neural-network|data-science
0
2,010
53,858,902
How to save Tensorflow encoder decoder model?
<p>I followed <a href="https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb#" rel="nofollow noreferrer">this tutorial</a> about building an encoder-decoder language translation model and built one for my native la...
<p>You can save a Keras model in Keras's HDF5 format, see:</p> <p><a href="https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model" rel="nofollow noreferrer">https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model</a></p> <p>You will want to do something like:</p> <pre><code>import tf.keras mod...
tensorflow|keras|google-cloud-ml|encoder-decoder
0
2,011
54,221,484
Select data based on multiple criteria using Pandas
<p>I am new to using Pandas. I want to select rows from a dataframe where multiple columns match in value. Along the lines of:</p> <p>if column A equals column AB and column B equals column BC </p> <p>then I want those values. </p> <p>I haven't actually used an if statement, I read iteration was not good to use with...
<p>You'll simply need to add the conditions inside parenthesis inside your <code>.loc</code> and not repeat a DF filter inside the df filter:</p> <p>First, creating a crude datasample, as you didn't provide one besides the image:</p> <pre><code># creating the values, first one will be ID, then next 4 will be the values...
python|pandas|select
3
2,012
54,057,338
Weight decay loss
<p>I need to write a code to gradually decay the weight of my loss function by computes lambda with given steps, But I don't have any idea. Any help will be appreciated.</p> <p>This is my Loss function:</p> <pre><code>loss_A = criterion(recov_A, real_A) loss_Final = lambda_A * loss_A + #lambda_A is a fixed number: 10...
<p>To decay the fixed number depends on the number of steps or even the number of epochs you can use the following code or you can write the code as a function and call it whenever you want.</p> <pre><code>final_value = 1e-3 # Small number because dont end up with 0 initial_value = 20 starting_step = 25 total_step =...
python|python-3.x|pytorch
1
2,013
53,970,733
i want to compute the distance between two numpy histogram
<p>i'm creating an image processing program and i want to measure the wasserstein distance between two numpy histograms. the two histogram are created with the function <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html" rel="nofollow noreferrer">numpy.histogram</a></p> <p>i tried the...
<p>thank to SpghttCd the solution was simple ... i had just to replace</p> <pre><code>wasserstein_distance(histogram1, histogram2) </code></pre> <p>with</p> <pre><code>wasserstein_distance(histogram1[0], histogram2[0]) </code></pre>
python|numpy|opencv|histogram|distance
0
2,014
53,803,676
Binary Markov-K Random Generator
<p>Hello Stackoverflow Community, </p> <p>currently I'm working on an entropy encoder (MQ-coder) implementation (cython wrapper and internal c source code). To create a test setting, I want to use a binary markov-k random generator, that outputs numpy arrays as input for the encoder. What would be the easiest way to i...
<p>FYI: this generates a table[256] of probabilities, based on the bits of it's (ascii) input.</p> <p>Usage: <code>cat*.c| ./a.out</code></p> <p>;-)</p> <hr> <pre><code>#include &lt;stdio.h&gt; struct cell { unsigned nhit; unsigned ones; } cells[256] ={{0,0},}; int main(void) { unsigne...
python|numpy|random|scipy|generator
0
2,015
38,179,248
Absolute difference of two NumPy arrays
<p>Is there an efficient way/function to subtract one matrix from another and writing the absolute values in a new matrix? I can do it entry by entry but for big matrices, this will be fairly slow...</p> <p>For example:</p> <pre><code>X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] for i in range...
<p>If you want the absolute element-wise difference between both matrices, you can easily subtract them with NumPy and use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.absolute.html" rel="noreferrer"><code>numpy.absolute</code></a> on the resulting matrix. </p> <pre><code>import numpy as np X = ...
python|arrays|numpy
27
2,016
38,368,500
What's the most efficient way to sum up an ndarray in numpy while minimizing floating point inaccuracy?
<p>I have a big matrix with values that vary greatly in orders of magnitude. To calculate the sum as accurate as possible, my approach would be to reshape the ndarray into a 1-dimensional array, sort it and then add it up, starting with the smallest entries. Is there a better / more efficient way to do this?</p>
<p>I think that, given floating point precision problems, the best known algorithm for your task is <a href="https://en.wikipedia.org/wiki/Kahan_summation_algorithm" rel="noreferrer">Kahan summation</a>. For practical purposes, Kahan summation has an error bound that is independent of the number of summands, while nai...
python|numpy|precision
6
2,017
38,324,603
How to keep a slice of a numpy array and clear the rest from memory?
<p>I have a list which contains several large <code>numpy arrays</code></p> <p>I want to only keep a slice of each of those arrays, and clear my system memory. I have tried using the keywords <code>del</code> and <code>None</code> but those do not seem to have any effect (I use the fedora system monitor to monitor RAM...
<p>You can add zero to the slice:</p> <p><code>smallSlice = bigArray[...,::10]</code></p> <p><code>del bigArray</code></p> <p>will leave bigArray in memory, as there is a copy the slice points to.</p> <p><code>smallSlice = bigArray[...,::10] + 0</code></p> <p><code>del bigArray</code></p> <p>will create a new array, an...
python|python-3.x|numpy
0
2,018
66,091,666
Move one column to another dataframe pandas
<p>I have a DataFrame <code>df1</code> that looks like this:</p> <pre><code>userId movie1 movie2 movie3 0 4.1 0.0 1.0 1 3.1 1.1 3.4 2 2.8 0.0 1.7 3 0.0 5.0 0.0 4 0.0 0.0 0.0 5 2.3 0.0 2.0 </code></pre> <p>and a...
<pre><code> df1=pd.concat([df1,df2['movie6']],axis=0) </code></pre>
python|pandas|dataframe
0
2,019
66,311,611
When and How Keras calculate metrics for each batch of samples?
<p>I was seeing how Keras custom metrics working, and calculation doesn't match between <code>tf.print</code> in metric function and callback print of <code>model.fit</code>.</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf # tf2.4.1 import numpy as np model = tf.keras.models.Sequential( ...
<p>In keras, the training loss/metric is calculated at the end of each epoch as the mean of loss/metric in each batch. so in your case:</p> <pre><code>EPOCH 1: (0.02672063 + 0.109848022) / 2 = 0.068284326 EPOCH 2: (0.0456855185 + 0.088704437) / 2 = 0.06719497775 </code></pre> <p>which correspond to:</p> <pre><code>hist...
python|tensorflow|machine-learning|keras|deep-learning
1
2,020
65,910,850
How can I get a value from other dataframe's column based on other index?
<p>Take this dataframe <code>df</code> fragment:</p> <pre><code> col_1 col_2 col_3 0 aaa !!! sss 1 bbb @@@ jjj 2 ccc !!! NaN 3 ddd $$$ nnn 4 eee %%% xxx </code></pre> <p>I need to run a <code>fillna()</code> on <code>col_3</code> to get the value of <code>col_1</code> based on the first o...
<p>Here's how to get this done:</p> <ul> <li><p>Step 1: Do a Groupby of <code>col_2</code> and find the values of <code>col_1</code> but pick only the first entry of this value</p> </li> <li><p>Step 2: Convert this into a dictionary Both of these steps can be accomplished by doing:</p> <p><code>df.groupby('col_2')['col...
python|pandas|dataframe
1
2,021
66,316,981
How to build a custom accuracy metric with tolerance in TF2?
<p>I want to build a custom accuracy metric with tolerance. Instead of counting elements exactly equal in <code>y_true</code> and <code>y_pred</code>, this accuracy regards the two elements are consistent if their difference within a given tolerance value. For example, if the differences between predicted degrees and t...
<p>You can't make a list comprehension with a tensor. The operation you're looking for is <a href="https://www.tensorflow.org/api_docs/python/tf/where" rel="nofollow noreferrer"><code>tf.where</code></a> and you can use it as follows:</p> <pre><code>def accuracy_with_tolerence(y_true, y_pred): threshold = 5 dif...
python|tensorflow|keras|customization|metrics
1
2,022
66,306,546
Append array as column to dataframe (or create new dataframe according to other dataframe's date)
<p>First of all, I want to say that there's a lot of similar questions and I'm spending almost 2 days looking and try to solve my problem, using all of the functions but couldn't find what I need, even though I believe there's going to be a very simple solution.</p> <p>Complete code</p> <pre><code>import matplotlib.pyp...
<p>The easiest is to use <code>pd.concat</code> like this:</p> <pre class="lang-py prettyprint-override"><code>mt = pd.Series( [34.678714, 34.087302, 33.857141, 33.250000, 33.124999, 31.818181, 31.082676, 29.107807, 30.144405], index=['2019-12-31', '2020-01-02', '2020-01-03', '2020-01-06', '2020-01-07', '2020-0...
python|pandas|dataframe|matplotlib|series
0
2,023
52,665,131
How we can create similarity matrix from dictionar?
<p>I have a dict as following:</p> <pre><code>dic = {a1: [a,b,c], b1:[b,k,l]}. </code></pre> <p>I want to create a similarity matrix for each key's value list. for example, for key <code>a1</code>, I want to compute similarities between <code>(a,b), (a,c) and (b,c)</code> using suppose method <code>f</code>. <code>f...
<p>If <code>f</code> is expensive and not vectorizable, you could use <code>np.tri</code> and friends along the lines of</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from operator import itemgetter as iget &gt;&gt;&gt; # set up an example &gt;&gt;&gt; a1, b1 = 'a1', 'b1' &gt;&gt;&gt; a, b, c, k, l = np...
python|numpy|scipy
1
2,024
46,353,749
How to Union Intersecting Geometries in Same Geopandas Dataframe
<p>I have a dataframe with circles, some of which intersect others. I want to merge those intersecting regions to be new rows in the dataframe, adding the attributes from the intersecting regions. I only see how to use sjoin between two dataframes.</p>
<p><strong>Setup</strong> </p> <pre><code>import geopandas as gpd, pandas as pd from urbansim.maps import dframe_explorer from shapely.geometry import Point %matplotlib inline c1 = Point(1, 0).buffer(1) c2 = Point(.5, 0).buffer(1) gdf = gpd.GeoDataFrame(dict(A=[1, 2], B=[3, 4]), geometry=[c1, c2]) gdf.plot() </cod...
pandas|union|intersect|geopandas
1
2,025
46,627,610
Successfully installed SciPy, but "from scipy.misc import imread" gives ImportError: cannot import name 'imread'
<p>I have successfully installed scipy, numpy, and pillow, however I get error as below</p> <blockquote> <p>ImportError: cannot import name 'imread'</p> </blockquote>
<p><code>imread</code> and <code>imsave</code> are deprecated in scipy.misc</p> <p>Use <code>imageio.imread</code> instead after <code>import imageio</code>.</p> <p>For saving - Use <code>imageio.imsave</code> instead or use <code>imageio.write</code></p> <p>For resizing use <code>skimage.transform.resize</code> ins...
tensorflow|scipy|ubuntu-16.04|python-import
0
2,026
58,173,241
text classification with machine learning
<p>I have a data set, with news headlines and the category of that news. I wish I could predict the category of the news by entering only its headline. I need to be able to classify text. Thank you</p>
<p>your question cannot be answered completely, but i can give you some starting points. , you need to do some own research this tutorial will is good for start. <a href="https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/" rel="nofollow noreferrer">link</a></p> <p>For local development i w...
python|tensorflow|machine-learning
0
2,027
69,038,101
Pandas groupBy multiple columns and aggregation
<p>In dataframe have 4 columns col_A,col_B,col_C,col_D.Need to group the columns(col_A,col_B,col_C) and aggregate mean by col_D. Below is the code snippet I tried and it worked</p> <p><code>df.groupby(['col_A','col_B','col_C']).agg({'col_D':'mean'}).reset_index()</code></p> <p>But in addition to the above result, also ...
<p>Using <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#named-aggregation" rel="nofollow noreferrer">Named Aggregation</a>:</p> <pre class="lang-py prettyprint-override"><code>result = ( df.groupby(['col_A', 'col_B', 'col_C'], as_index=False) .agg(mean=('col_D', 'mean'), count=(...
python|pandas
2
2,028
44,590,646
Iterating through a dataframe to create PDF documents
<p>I have a worksheet that I have imported as a Pandas dataframe which looks something like this:</p> <p>FileName FilePath Date Pagestart PageEnd</p> <p>file1 path1 date1 5 10</p> <p>file2 path2 date2 20 100</p> <p>My goal...
<pre><code>import PyPDF2 import os for row in df.itertuples(): page_start, page_end = row.PageStart, row.PageEnd output_filename = generate_output_name filename = os.path.join(row.FilePath, row.FileName) with PdfFileMerger() as merger: merger.append(filename, pages=(page_start, page_en)) ...
python|python-3.x|pandas|pdf|dataframe
1
2,029
44,434,416
Plot basic example of neural network
<p>I am studying about neural network tutorial and made simple perceptron code like this below </p> <p>The purpose is </p> <ul> <li>Spliting 20 points into two groups.</li> </ul> <p>perceptron.py</p> <pre><code>import numpy as np from pprint import pprint import pandas as pd import matplotlib import matplotlib.py...
<p>You can plot using <code>scatter</code> for data and <code>contour</code> for boundary decision:</p> <pre><code>xx = np.linspace(-2,10) yy = np.linspace(-2,10) [X1,X2] = np.meshgrid(xx,yy) Y = [t(i) for i in range(len(x))] Z = (w[0] * X1.ravel() + w[1] * X2.ravel()) + b plt.scatter(x[:,0], x[:,1], s=20, c=Y, cma...
python|pandas|neural-network|deep-learning|artificial-intelligence
0
2,030
61,113,087
TypeError: 'DataFrame' object cannot be interpreted as an integer in python 3.7
<p>I have a simple question, I am creating new column in a list of dataFrame within function. I got this error</p> <pre><code>data['datenum'] = np.zeros((data)) TypeError: 'DataFrame' object cannot be interpreted as an integer </code></pre>
<p>Your argument to np.zeros needs to be an integer. Right now you have data, which you say is a DataFrame. Perhaps you're looking for: </p> <pre><code>data['datenum'] = np.zeros(data.shape[0]) </code></pre> <p>If you have multiple dataframes, you can do the following: </p> <pre><code>for data in dataframes: da...
python|python-3.x|pandas|python-2.7
1
2,031
69,821,979
Stop Tensorflow trying to load cuda temporarily
<p>I have this code to disable GPU usage:</p> <pre><code>import numpy as np import os os.environ[&quot;CUDA_VISIBLE_DEVICES&quot;] = &quot;-1&quot; import tensorflow as tf w = tf.Variable( [ [1.], [2.] ]) </code></pre> <p>I get this output still, not sure why :</p> <pre><code>E:\MyTFProject\ve...
<p>You can try to reinstall tensorflow with CPU-only version. The links are available here depending on your OS and your python version: <a href="https://www.tensorflow.org/install/pip?hl=fr#windows_1" rel="nofollow noreferrer">https://www.tensorflow.org/install/pip?hl=fr#windows_1</a></p>
tensorflow
0
2,032
69,778,354
Pandas mistake when reading date from excel file
<p>Pandas error when reading date from excel file. I am creating a dataframe using the following command.</p> <pre><code>df = pd.read_excel(&quot;report_file.xls&quot;, parse_dates=['operation_date']) df.dtypes operation_date datetime64[ns] </code></pre> <p>Everything looks good. But when analyzing the dataframe, an e...
<p>Try passing the date format explicitly, something like this:</p> <pre><code>pd.read_excel( &quot;report_file.xls&quot;, parse_dates=['operation_date'], date_parser=lambda x: pd.to_datetime(x, format='%Y-%m-%d %I:%M:%S') ) </code></pre>
python|excel|pandas|datetime64
0
2,033
69,933,833
Calculate de mean of a list inside of a Nested Dictionary
<p>I have a nested dictionary, that I transformed in a pickle file. The pickle file can be found <a href="https://github.com/joaodavidfreitas/sistemas_inteligentes/blob/main/map_results_LSTM_acoes_variandotest.pickle" rel="nofollow noreferrer">here</a>. To open the pickle file is just like thar:</p> <pre><code>import p...
<p>The problem is that <code>values</code> is a string, not a dictionary like you try to use it. <code>keys()</code> returns a list of strings. I suggest you use <code>items()</code> instead to get the key, value pairs from the dictionary you are iterating. This will also let you avoid the long indexing syntax from the...
python|numpy|dictionary|time-series|mean
1
2,034
43,132,792
matplotlib unexpected results polar plot
<p>I am trying to plot simple function r = 3*sin(2*theta) using matplotlib:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.pyplot as plt theta = np.arange(0,2*np.pi,0.01) r = 3.0*np.sin(2.0*theta) ax = plt.subplot(111, projection='polar') ax.plot(theta, r) plt.show() </code></...
<p>this patches the polar plot for neg r</p> <pre><code>import numpy as np import matplotlib.pyplot as plt theta = np.arange(0,2*np.pi,0.01) r = 3.0*np.sin(2.0*theta) theta = theta + (1 - np.sign(r))*np.pi/2 # add pi to points with negative r values r = np.abs(r) # make all r values postive to fake out matplotlib ax =...
python|numpy|matplotlib
1
2,035
72,256,427
Determine if geopandas point is in generic polygon with holes
<p>This thread <a href="https://stackoverflow.com/questions/48097742/geopandas-point-in-polygon">here</a> gave a solution of how to determine if a <code>geopandas</code> <code>POINT</code> is in a solid <code>POLYGON</code>.</p> <p>What would be a generic solution to determine this for a <code>POLYGON</code> with holes...
<p>Strictly the sample you have provided are polygons. Geometry contains a hole.</p> <p>It's pretty straight forward to test, just use <strong>convex_hull</strong>. Code below does both tests.</p> <pre><code>pnts.assign( **{ **{key: pnts.within(geom) for key, geom in polys.items()}, **{key+&quot;_...
python|pandas|geopandas|point-in-polygon
0
2,036
72,360,913
Is there a non-looping way to perform text searching in a data frame
<p>I have a huge list of ngrams to search. I want to know what frequency they have on my historic dataframe and the mean of a numeric variable that I have on my historic. I have a really really ugly way of doing it (that works), but as the list of ngrams is huge, it's really slow.</p> <p>I am trying to avoid doing the ...
<p>Try DataFrame.apply()</p> <pre class="lang-python prettyprint-override"><code>def func(x): temp = pd.DataFrame(data={'ngram' : [i], 'count' : historic_df['text_variable'].str.contains(i, na=False).sum(), 'mean' : historic_df[historic_df['text_variable']...
python|pandas|n-gram
0
2,037
72,146,783
Groupby id and change values for all rows for the earliest date to NaN
<p>I have the following id, i would like to groupby id and then replace value <code>X</code> with <code>NaN</code>. My current df.</p> <pre><code> ID Date X other variables.. 1 1/1/18 0.118758835 1 1/1/18 0.148103273 1 1/1/18 0.365541214 1 1/2/18 0.405002687 1 1/2/18 0.130580...
<p>You can call <code>min</code> in <code>groupby.transform</code> to get the earliest dates for each ID; then compare it with &quot;Date&quot; to get a boolean mask; finally use the mask to <code>mask</code> earliest &quot;X&quot;s:</p> <pre class="lang-py prettyprint-override"><code>df['X'] = df['X'].mask(df.groupby(...
python|pandas|dataframe|pandas-groupby
1
2,038
50,291,083
how to parse selected values from nested json using pandas
<p>I am trying to parse only a selected elements from nested json.</p> <p>below is my json file</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>{ "creation-date": "Fri Ma...
<p>I'm not really sure why you want to get this into pandas. You only have two columns with one value for each of them.</p> <p>Also, the pandas json loader isn't really designed to get data from your ad hoc JSON files, but to load more regular ones.</p> <p>I would extract the data I wanted and load that into pandas i...
python|pandas
0
2,039
50,457,074
How to polyfit() an OpenCV calcHist() histogram?
<p>I have something like this:</p> <pre><code>import numpy as np import cv2 as cv from matplotlib import pyplot as plt import numpy.polynomial.polynomial as poly img = cv.imread('SomeImage.jpg') color = ('b','g','r') for i,col in enumerate(color): histr = cv.calcHist([img],[i],None,[32],[0,256]) plt.plot(hist...
<p>It looks like a minor syntax mistake when calling <code>np.linspace</code>. The correct syntax is</p> <pre><code>x = np.linspace(interval_start, interval_end, number_of_points) </code></pre> <p>so in your case, that would be</p> <pre><code>x = np.linspace(0, 1, histr.shape[0]) </code></pre>
python|numpy|opencv
1
2,040
50,653,562
Why does "tf.constant(tf.random_normal((10, 4)))" cause an error?
<p>In the following code, "a" works perfectly fine, and "c" also works. But "b" causes an error. Could someone explain the reason?</p> <pre><code>#!/usr/bin/python import tensorflow as tf import numpy as np a = tf.Variable(tf.random_normal((10, 4))) b = tf.constant(tf.random_normal((10, 4))) c = tf.constant(np.rando...
<p>I am also a new one who start using tensorflow. I believe that there is something wrong with your variable type. According to the tensorflow API, you should feed a constant or list of value to 'tf.constant()'. However, in you code, before you initialize the variables and run this session, 'tf.random_normal()' is som...
python|tensorflow|initialization
1
2,041
45,374,905
higher precision in python
<p>I am running some <code>python</code> v3.3.2 scripts that use <code>numpy</code> and <code>scipy</code> and <code>math</code>. I am suspecting that there is an issue of numerical precision in my computation, and I would like to increase the precision in some particular modules that I have written and see if it makes...
<p>When your code is based on numpy/scipy and co., you can only use the types supported by these libs. Here is the <a href="https://docs.scipy.org/doc/numpy/user/basics.types.html" rel="nofollow noreferrer">overview</a>.</p> <p>The paragraph <a href="https://docs.scipy.org/doc/numpy/user/basics.types.html#extended-pre...
python-3.x|numpy|scipy|precision|scientific-computing
2
2,042
62,605,998
fill column with value of a column from another dataframe, depending on conditions
<p>I have a dataframe that looks like this (my input database on COVID cases)</p> <p>data:</p> <pre><code> date state cases 0 20200625 NY 300 1 20200625 CA 250 2 20200625 TX 200 3 20200625 FL 100 5 20200624 NY 290 6 20200624 CA 240 7 20200624 TX 100 8 20200624...
<p>You can do:</p> <pre><code>df = df.set_index(['date', 'state']).unstack().reset_index() # fix column names df.columns = df.columns.get_level_values(1) state CA FL NY TX 0 20200624 240.0 NaN 290.0 NaN 1 20200625 250.0 100.0 300.0 200.0 </code></pre> <p>Later, to set i...
python|pandas|numpy
4
2,043
62,488,554
Pandas shows data in a wrong diagram
<p>I have two functions which both create a diagramm. But when I run those 2 functions, in the second one is the data which should be in the first one. Here are the diagramms:<a href="https://i.stack.imgur.com/u3oII.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u3oII.jpg" alt="enter image descripti...
<p>You could try this. Matplotlib needs to know, if you want a <em>new figure</em> for each plot or not.</p> <pre class="lang-py prettyprint-override"><code>from pandas import DataFrame import sqlite3 import matplotlib.pyplot as plt import pandas as pd from datetime import date, datetime datum = str(date.today()) da...
python|pandas|matplotlib
1
2,044
54,291,617
Vectorizing array access from indices matrix
<p>Consider the following:</p> <pre><code>In [51]: arr = np.arange(6, 10) In [52]: idx = np.random.randint(4, size=(3, 4)) In [53]: idx Out[53]: array([[0, 3, 3, 1], [1, 3, 3, 2], [1, 1, 1, 1]]) In [54]: result = np.empty_like(idx) In [55]: for i in range(idx.shape[0]): ...: result[i] = arr[idx[i]]...
<p>As noted in the comments, you can simply index into the array <code>arr</code> using the <code>idx</code> array.</p> <pre><code>In [47]: arr Out[47]: array([6, 7, 8, 9]) In [48]: idx Out[48]: array([[3, 2, 2, 0], [0, 3, 2, 3], [3, 2, 2, 3]]) In [49]: arr[idx] Out[49]: array([[9, 8, 8, 6], ...
python|numpy|multidimensional-array|vectorization|matrix-indexing
0
2,045
54,362,961
Concatenating, sorting, and re-partitioning xyz data
<p>I have a situation where I have two lists of [x, y, z] data, I want to concatenate these lists, sort them, then extract a matrix for the z values, with x increasing along the columns, and y increasing along the rows. </p> <p>To give an example:</p> <pre><code>list1 = np.linspace(-2,2,3) list2 = np.linspace(-1,1,3)...
<p>My approach would be </p> <pre><code>result = [] _, occurences = np.unique(dat_sorted[:,0], return_inverse=True) for i in range(np.max(occurences) + 1): result.append(dat_sorted[occurences == i, 2]) </code></pre> <p>This will give you a x value ordered list of y value ordered arrays of z values. This is not a...
python|numpy|sorting|multidimensional-array|data-structures
2
2,046
54,413,499
How to use the black/white image as the input to tensorflow
<p>When implementing the reinforcement learning with tensorflow, the inputs are black/white images. Each pixel can be represented as a bit 1/0.</p> <p>Can I give the data directly to tensorflow, with each bit as a feature? Or I had to expand the bits to bytes before sending to tensorflow? I'm new to tensorflow, so som...
<p>You can directly load the Image data as you would normally do, the Image being binary will have no effect other that the input channel width becoming 1 for the input.</p> <p>Whenever you put an Image through a convnet, each output filter generally learns features for all the channels, so in case of a binary image, ...
tensorflow
0
2,047
73,638,057
count number of elements in a list inside a dataframe
<p>Assume that we have a dataframe and inside the dataframe in a column we have lists. How can I count the number per list? For example</p> <pre><code>A B (1,2,3) (1,2,3,4) (1) (1,2,3) </code></pre> <p>I would like to create 2 new columns wit...
<p>You can use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer"><code>.apply</code></a> method on the Series for the column <code>df['A']</code>.</p> <pre><code>&gt;&gt;&gt; import pandas &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; pd.DataFrame({&quot;colum...
python|pandas
2
2,048
73,776,270
Try catch condition while combining CSV files in pandas
<p>I am combining multiple csv files into a single dataframe using this line -</p> <pre><code>df = pd.concat(map(pd.read_csv, files), ignore_index=True) </code></pre> <p>I was earlier using a <code>for</code> loop where I combine two dataframes at time. This allowed me to use <code>try-catch</code> statements to catch ...
<p>try:</p> <pre><code>files = ['file1.csv', 'file2.csv', 'file3.csv'] def readcsv(path): try: dff = pd.read_csv(path) except pd.errors.EmptyDataError: print('error') dff = pd.DataFrame([]) #or anything else when error happen #I put empty dataframe here so the concat don't fail,...
python-3.x|pandas
1
2,049
73,743,698
Pandas UDF with dictionary lookup and conditionals
<p>I want to use pandas_udf in Pyspark for certain transformations and calculations of column. And it seems that pandas udf can't be written exactly as normal UDFs.</p> <p>An example function looks something like below:</p> <pre><code>def modify_some_column(example_column_1, example_column_2): lookup_dict = {'a' :...
<p>With this simple if/else logic, you don't have to use UDF. In fact you should avoid to use UDFs as much as possible.</p> <p>Assuming you have the dataframe as follow</p> <pre><code>df = spark.createDataFrame([ ('a', 'something'), ('a', 'something else'), ('c', None), ('c', ''), ('c', 'something')...
apache-spark|pyspark|pyspark-pandas|pandas-udf
1
2,050
71,371,204
How can I use row index values as column for dataframe?
<p>So, I collected data from 21 participants with 16 EEG channels and I extracted the Gamma band. My current dataframe looks like this ([336 rows x 2 columns]):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Channels</th> <th>Gamma</th> </tr> </thead> <tbody> <tr> <td>Fp1</td> <td>0.345908...
<p>One approach is to group by the Channels and then set these groups as columns of your new dataframe. Assuming following dataframe:</p> <pre><code> Channels Gamma 0 Fp1 0.345908 1 Fp2 0.121232 2 Fp1 0.455908 3 Fp2 0.213212 </code></pre> <p>Then apply this code to the dataframe:</p> <pre><...
python|pandas|dataframe|transpose|melt
2
2,051
52,296,757
Pandas DataFrame equivalent of laravel's 'pluck' on collections
<p>I am using pandas on python 3.6.5, I desire to achieve similar result on a DataFrame instance as the Collection's "pluck" method in Laravel. For example:</p> <p>DataFrame</p> <pre><code> one two 0 beer wine 1 beer tomato </code></pre> <p>PHP Laravel code:</p> <pre><code>$plucked = $collection-&gt;plu...
<p>You can select ell entries in a DataFrame column by simply doing:</p> <pre><code>storage_variable = df['Column Name'] </code></pre> <p>So, in your case that would be:</p> <pre><code>plucked = df['two'] </code></pre>
php|python|laravel|pandas|dataframe
0
2,052
60,665,717
module 'tensorflow_core._api.v2.data' has no attribute 'Iterator'
<p>Can't figure out what to use instead of Iterator</p> <p>I tried tf.compat.v1.data.Iterator instead but got another error - <code>AttributeError: 'PrefetchDataset' object has no attribute 'output_types'</code></p> <p>code:</p> <pre><code>train_ds = prepare_for_train(labeled_ds) val_ds = tf.data.Dataset.from_tenso...
<p>I was able to reproduce your error. Here is how you can fix it in <code>Tensorflow Version 2.x</code>.</p> <p>You need to define <code>iter</code> as below -</p> <pre><code>iter = tf.compat.v1.data.Iterator.from_structure(tf.compat.v1.data.get_output_types(train_dataset), ...
tensorflow2.0|tensorflow-datasets
2
2,053
60,380,852
How to find a string match in df col based on list of strings?
<p>I have a list of 1000 corporate companies and a df of all previous transactions for the year. For every match, I would like to create a new row value (True) in the new column (df$Covered).</p> <p>I am not sure why I keep getting the errors below. I tried researching these questions but no luck so far.</p> <p><a ...
<p>Thanks everyone, it has to do with my Customer_List having special characters so I needed to use map(re.escape</p> <p>This link helped me below <a href="https://stackoverflow.com/questions/28539253/python-regex-bad-character-range">Python regex bad character range.</a></p>
python|pandas
0
2,054
72,744,383
How can I input space separated integers in pyhton numpy array. (Like the list(map(int,input().spli(" ")) function does for a list.)
<p>I have tried to find alternatives but only available for list not for numpy arrays</p> <p>I tried this but didnt work:</p> <pre><code>5 1 2 3 4 5 Traceback (most recent call last): File &quot;&lt;string&gt;&quot;, line 6, in &lt;module&gt; File &quot;/usr/local/lib/python3.8/dist-packages/numpy/core/numeric.py&q...
<p>You can just convert to a numpy array:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np numbers = input('Enter some numbers: ').split() x = np.array(list(map(int, numbers))) print(x) </code></pre> <p>Output:</p> <pre><code>Enter some numbers: 1 2 3 4 5 [1 2 3 4 5] </code></pre>
python|arrays|numpy|dictionary|input
1
2,055
72,559,010
In Pandas, how can I perform the .diff() method to numerical values only in a column that also contains NaNs?
<p>I have a Pandas dataset and I would like to calculate the difference of a column element compared with another element of the same column. In order to do so, the most intuitive method to apply is <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.diff.html" rel="nofollow noreferrer">.diff()</a></...
<p>You'll need to <code>dropna</code> and set up a temporary variable, and <code>reindex</code> like this:</p> <pre><code>import numpy as np df = pd.DataFrame({&quot;col&quot;: [1, np.nan, 3, 4, np.nan, np.nan, 10, np.nan, 13]}) idx = df.index # create index from original data tmp = df.dropna() # drop nan rows tmp.d...
python|pandas|dataframe|nan
2
2,056
72,776,999
How to apply a point transformation to many points?
<p>I have a gridded temperature dataset and a list of weather stations across the country and their latitudes and longitudes. I want to find the grid points that are nearest to the weather stations. My gridded data has coordinates x,y which latitude and longitude are a function of. <a href="https://i.stack.imgur.com/Cl...
<p>There is no need to use geopandas in here... just use <code>crs.transform_points()</code> instead of <code>crs.transform_point()</code> and pass the coordinates as arrays!</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import cartopy.crs as ccrs data_crs = ccrs.LambertConformal(central_longi...
python|pandas|numpy|python-xarray|cartopy
0
2,057
72,808,258
Jupyter not showing visual representation
<p>I am researching to make a visual representation of clusters, and I have found the following source: <a href="https://plotly.com/python/v3/3d-point-clustering/#3d-clustering-with-alpha-shapes" rel="nofollow noreferrer">https://plotly.com/python/v3/3d-point-clustering/#3d-clustering-with-alpha-shapes</a></p> <p>In it...
<p>I got it to display in Jupyter notebook. The error was due to plotly authenticiation error, so import iplot from offline.</p> <pre><code>from plotly.offline import iplot iplot(fig, filename='3d point clustering') </code></pre> <p>Here is the complete code:</p> <pre><code>import chart_studio.plotly as py from plotly....
python|pandas|plotly|cluster-analysis
0
2,058
72,601,457
change string into datetime in pandas
<p>How can I change the following string datetime into datetime in python.Here's my dataframe</p> <pre><code>IN OUT 2022/6/10 10:20:30.00000000000000000000000000 2022/6/17 13:25:30 2022/6/5 12:48:10.0 2022/6/11 10:15 2022/6/9 08:25:30 2022/6/13 10:25:30 2022-06-08 17:18:37.00000000000000000000 0 0 0 2022-06-0...
<p>Letting pandas infer the format should get you started. You can parse to datetime data type like</p> <pre class="lang-py prettyprint-override"><code>df['IN'] = pd.to_datetime(df['IN'], errors='coerce') df['IN'] 0 2022-06-10 10:20:30 1 2022-06-05 12:48:10 2 2022-06-09 08:25:30 3 2022-06-08 17:18:37 4 ...
python|pandas|string|date|datetime
0
2,059
59,553,742
Error while custom periods based resampling using resample('W'),sum() in python
<p>I have the data frame ( frame_combined_DF) which looks like this. I need to do custom resampling based on Time_W weeks provided for each SKU.</p> <pre><code>frame_combined_DF SKU Qty Time Time_W WY 2011-10-17 ABC 12.0 11.0 2 2012-01-16 ABC 20.0 11.0 ...
<p>From your sample data I see that <em>WY</em> is the index column.</p> <p>But check whether this column is of <em>datetime</em> type (not <em>string</em>). If it is not, run <code>frame_combined_DF.index = pd.to_datetime(frame_combined_DF.index)</code>.</p> <p>Another point to note is that <em>newdf</em> is a <stro...
python|pandas|numpy
1
2,060
59,697,708
Get date from list with `numpy.datetime64`-objects
<p>I have a list with quite some dates. Unfortunately they are all appear as <code>numpy.datetime64</code>-object. Does anyone has an idea of how I could extract the actual date? The list looks like this: </p> <pre><code>[numpy.datetime64('2016-01-04T00:00:00.000000000'), numpy.datetime64('2016-01-14T00:00:00.0000000...
<p>Here's a way to do using <code>.astype</code>:</p> <pre><code>dates = [str(x.astype('datetime64[D]')) for x in dates_list] ['2016-01-04', '2016-01-14', '2016-01-17', '2016-01-24'] </code></pre>
python|pandas|numpy|datetime|type-conversion
2
2,061
59,503,069
Need to add dataframes in a excel in iterative format
<p>I have created a pandas dataframe from dictionary and i need to copy the unique column data to a excel in the same sheet But its just writing one dataframe and doesnt write anything after that Help! Below is the code:</p> <pre><code>import pandas import csv import os act_dict = {'bmc': [], 'adc': [], 'volume': []...
<pre><code>l1 = bmc_data.bmc.unique() print(l1) startcol=startrow = 0 file_name='/home/laxmi/Documents/volume_analyser_project/idmc.xlsx' writer = pandas.ExcelWriter('idmc.xlsx', engine='xlsxwriter') count1=(len(l1)) print(count1) for i in range(count1): df_i=bmc_data[bmc_data.bmc==l1[i]] df_i = df_i.sort_value...
python|pandas
0
2,062
32,325,410
Label regions with unique combinations of values in two numpy arrays?
<p>I have two labelled 2D numpy arrays <code>a</code> and <code>b</code> with identical shapes. I would like to re-label the array <code>b</code> by something similar to a <a href="http://resources.arcgis.com/EN/HELP/MAIN/10.1/index.html#//00080000000s000000" rel="nofollow noreferrer">GIS geometric union</a> of the two...
<p>If I understood the circumstances correctly, you are looking to have unique pairings from <code>a</code> and <code>b</code>. So, <code>1</code> from <code>a</code> and <code>1</code> from <code>b</code> would have one unique tag in the output; <code>1</code> from <code>a</code> and <code>3</code> from <code>b</code>...
python|arrays|numpy|scipy|python-2.6
5
2,063
40,600,308
Python: track job progress using tqdm
<p>I am using the following code to track a job progress:</p> <pre><code>from tqdm import tqdm, tqdm_pandas tqdm.pandas(tqdm()) my_df['target'] = my_df.progress_apply(lambda x: my_fun(x), axis = 1) </code></pre> <p>Then the code provide progress tracking like below:</p> <pre><code> 0%| | 0/5 [00:00&lt;?, ...
<p>Yes, just use the mininterval argument:</p> <pre><code>tqdm.pandas(tqdm, mininterval=5) </code></pre>
python|pandas|progress
1
2,064
18,700,620
printing sub-array in numpy as Matlab does
<p>How can you print sub-arrays in numpy the same way Matlab does? I have a 3 by 10000 array and I want to view the first 20 columns. In Matlab you can write</p> <pre><code>a=zeros(3,10000); a(:,1:20) Columns 1 through 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...
<p>Does this give what you want?</p> <pre><code>&gt;&gt;&gt; for item in a[:,0:20].T: print '\t'.join(map(str,item.tolist())) </code></pre> <p>Or this?</p> <pre><code>&gt;&gt;&gt; for item in a[:,0:20]: print '\t'.join(map(str,item.tolist())) </code></pre>
python|matlab|numpy
1
2,065
61,949,905
Getting Invalid argument: shape of all inputs must match:values[0].shape = [401408] != values[1].shape = [24485888] when using IoU metric in keras
<p>I'm using UNet to train on the TACO dataset, which is in COCO format. I tried training my model with the accuracy metric, only to end up with validation accuracy and accuracy reaching 1.000, which is honestly too good to be true. I was told that accuracy isn't exactly a fitting metric for segmentation problems, whic...
<p>I was facing a similar issue. the problem was with the output layer where the number of filter I had was 1 but the mask was a 3D image hence the filter number was suppose to be 3. maybe for you too, the number of filters in output layers doesn't match the mask dimensions. try changing it</p>
python|tensorflow|machine-learning|keras
0
2,066
61,861,814
list reshape as similar to dictionary type
<p>I'm dealing with patent data with pandas and numpy. the steps that I've done and data I've got from the raw data is below.</p> <p>code</p> <pre><code>title = df['title'].tolist() cpc = df_cpu['cpc'].tolist() z = zip(title, cpc) </code></pre> <p>result</p> <pre><code> ('(real-time information transmission syste...
<p>If I understood the end goal correctly, you want to use <code>split()</code> to split the cpc codes string, using <code>','</code> as the separator. This will generate a list, which you can then iterate through to create a new list/tuple.</p> <p>Here is a snippet that I think accomplishes what you want:</p> <pre><...
python|pandas|numpy
1
2,067
58,150,686
How to find the eigenvalues in Python with a matrix different to the identity matrix
<p>I am trying to find the eigenvalues of a characteristic equation in Python, the problem is that in the equation |A-lambda I|=0, the matrix that multiplies lambda isn't the identity matrix, but I have to make clear that this matrix different to the identity matrix is a diagonal matrix.</p>
<p>The problem you're facing is known as the generalized eigenvalue problem. An example solution with <code>numpy</code> is given in <a href="https://stackoverflow.com/questions/24752393/solve-generalized-eigenvalue-problem-in-numpy">this</a> question.</p>
python|numpy|matrix|linear-algebra|eigenvalue
0
2,068
58,142,567
Streaming NumPy data as input to Tensorflow
<p>I was reading <a href="https://www.tensorflow.org/guide/datasets" rel="nofollow noreferrer">https://www.tensorflow.org/guide/datasets</a> to look for a solution to stream NumPy arrays stored in npz files, which may be too large to fit in memory. This snippet is provided in the documentation:</p> <pre><code># Load t...
<p>The utilities for <code>.npy</code> files indeed allocate the whole array into memory. </p> <p>If all of your input data fit in memory, the simplest way to create a Dataset from them is to convert them to <code>tf.Tensor</code> objects and use <code>Dataset.from_tensor_slices()</code> like you are doing above. </...
python|numpy|tensorflow
1
2,069
58,066,558
Pandas Group-By and Sum not creating a new Data Frame
<p>I have a dataframe - </p> <pre><code> TransactionDT TransactionAmt TransactionHour 0 86400 68.5 0 1 86401 29.0 1 2 86469 59.0 1 3 86499 50.0 2 4 86506 50.0 ...
<pre><code>sliced_data2 = data.groupby('TransactionHour',as_index = False).agg({"TransactionAmt" : "sum"}) </code></pre>
python|pandas
1
2,070
34,095,310
Pandas: How to get the column name where a row contain the date?
<p>I have a dataframe named <code>DateUnique</code> made of all unique dates (format datetime or string) that are present in my other dataframe named <code>A</code>.</p> <pre><code>&gt;&gt;&gt; print(A) 'dateLivraisonDemande' 'abscisse' 'BaseASDébut' 'BaseATDébut' 0 2015-05-27 2004-01-10 ...
<p>You can make a function that returns the appropriate column. Use the vectorized <code>isin</code> function, and then check if <code>any</code> value is <code>True</code>.</p> <pre><code>df = pd.DataFrame({'dateLivraisonDemande': ['2015-05-27']*7 + ['2015-05-27', '2015-05-29', '2015-04-10'], 'ab...
python|pandas
1
2,071
37,006,897
scipy optimize SLSQP only takes last ineq constrant into account
<p>Let's say I have a portfolio with weights, sum = 1.<br> Then I want to define pockets (0, 1, 2) with some assets included in those pockets, and sum(weights_pocket_assets) &lt; pocket_max_weight<br> On my UI, I have a 3 columns for each pocket, filled with 1 if asset is in pocket, 0 otherwise (this array is called 'p...
<p>As often, it was a problem with variable scope (odd stuff since variables were still defined, but overwritten. I did not investigate more to fully understand). The following code works as expected (all pockets constraints taken into account):</p> <pre><code>constr += ({'type': 'ineq', 'fun': lambda x, m...
python|python-3.x|numpy|scipy
0
2,072
36,940,253
TensorFlow: change tanh of BasicRNNCell to another op?
<p>I want try some other transfer functions besides the default <code>tanh</code> in TensorFlow's <code>BasicRNNCell</code>.</p> <p>The original implementation is like:</p> <pre><code>class BasicRNNCell(RNNCell): (...) def __call__(self, inputs, state, scope=None): """Most basic RNN: output = new_state = tanh(W *...
<p>You do not need to change the code of the tensor flow implementation for this.</p> <p>The BasicRNNCell has a parameter called activation function. You can just simply change that from tf.tanh to whatever activation function you want.</p>
python|inheritance|neural-network|tensorflow|recurrent-neural-network
2
2,073
54,747,845
Bokeh graph doesn't plot properly
<p>The following code doesn't generate a graph:</p> <pre><code>import pandas import numpy as np from bokeh.plotting import figure, show, output_file from bokeh.io import output_notebook from datetime import datetime output_notebook() TOOLS="hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,\ ...
<p>OK, as far as I can tell, this is what you want (using some project sample data, since you did not provide anything to run your code with):</p> <pre><code>from bokeh.plotting import figure, show from bokeh.sampledata.commits import data p = figure(x_axis_type="datetime", y_axis_type="datetime") p.circle(x=data.ind...
python|pandas|bokeh
1
2,074
49,710,174
Is there a way to recognise an object in an image?
<p>I am looking for some pre-trained deep learning model which can recognise an object in an image. Usually the images are of type used in shopping websites for products. I want to recognise what is the product in the image. I have come across some pre-trained models like VGG, Inception but they seems to be trained on ...
<p>I think the best way to do this is to build your own training set with the labels that you need to predict, then take an existing pre-trained model like VGG, remove the last fully connected layers and train the mode with your data, the process called transfer learning. Some more info <a href="https://www.tensorflow....
tensorflow|deep-learning|keras|image-recognition
0
2,075
49,556,135
Load one-line-json formatted data into Pandas DataFrame
<p>I have a json doc with 7 columns and only 1 row.I am not able to load this Json into a DataFrame with read_json.</p> <pre><code>url_global = 'https://api.coinmarketcap.com/v1/global/' df_global = pd.read_json(url_global) ValueError: If using all scalar values, you must pass an index </code></pre>
<p>The params in this function is somehow complicated and un-orthogonal. I find it helpful to use</p> <pre><code>pds.read_json("https://api.coinmarketcap.com/v1/global/", typ='series') </code></pre> <p>output would be (the type is 'pandas.core.series.Series')</p> <pre><code>active_assets 6.7700...
python|pandas|dataframe
0
2,076
27,913,806
How to keep rows where at least one column satisfy a condition in Pandas
<p>I have the following DF:</p> <pre><code>In [1]: import pandas as pd In [2]: mydict = {'foo':[0, 0.3,5], 'bar':[1,0.55,0.1], 'qux': [0.3,4.1,4]} In [3]: df = pd.DataFrame.from_dict(mydict, orient='index') In [4]: df Out[4]: 0 1 2 qux 0.3 4.10 4.0 foo 0.0 0.30 5.0 bar 1.0 0.55 0.1 </code></p...
<pre><code>In [201]: df.loc[(df &gt; 2).any(axis=1)] Out[201]: 0 1 2 qux 0.3 4.1 4 foo 0.0 0.3 5 </code></pre>
python|pandas
10
2,077
73,294,933
Pytorch: How to generate random vectors with length in a certain range?
<p>I want a <code>k</code> by <code>3</code> by <code>n</code> tensor representing <code>k</code> batches of <code>n</code> random 3d vectors, each vector has a magnitude (Euclidean norm) between <code>a</code> and <code>b</code>. Other than rescaling the entries of a random <code>kx3xn</code> tensor to <code>n</code> ...
<p>Assuming <code>a &lt; b</code>, you now have a constraint on the 3rd random number due to the norm. i.e <code> sqrt(a^2 - x^2 - y^2) &lt; z &lt; sqrt(b^2 - x^2 - y^2)</code></p> <p>Now <code>a^2 - x^2 - y^2 &gt; 0</code> which implies that <code>x^2 + y^2 &lt; a^2</code></p> <p>We need two sets of generate numbers s...
python|numpy|random|pytorch
2
2,078
73,354,949
Reformatting a dataframe to replace repeating similar rows with a new column
<p>Input.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Phrase number</th> <th>Words said</th> </tr> </thead> <tbody> <tr> <td>John</td> <td>Phrase 1</td> <td>Hi!</td> </tr> <tr> <td>John</td> <td>Phrase 2</td> <td>How are you?</td> </tr> <tr> <td>John</td> <td>Phrase 3</td>...
<p>you can use <code>pivot</code> but have to use a few other methods to clean up the index and columns names (in order to exactly match the desired output):</p> <pre><code>df = (df.pivot(index='Name', columns='Phrase number') .droplevel(0, axis=1) .reset_index() .rename_axis('', axis=1)) df Out[1]: ...
python|pandas
0
2,079
73,320,055
How to apply a low pass filter to a dicom image in python?
<p>I am trying to apply some blur using a low pass filter to a dicom image, however my resulting dicom image is not correct (see image below) (all data below is publicly available)</p> <pre><code>from scipy import fftpack import numpy as np import imageio from PIL import Image, ImageDraw import numpy as np import pydic...
<p>I fixed the code using the GaussianBlur of cv2 library</p> <pre><code>dicom = pydicom.dcmread(&quot;./CT000000.dcm&quot;) dicom.PixelData = cv2.GaussianBlur(dicom.pixel_array, (7, 7), 0) #save the image dicom.save_as(r&quot;./result.dcm&quot;) </code></pre>
python|numpy|opencv|image-processing|pydicom
0
2,080
34,917,727
Stacked bar plot by grouped data with pandas
<p>Let's assume I have <code>pandas</code> dataframe which has many features and I am interested in two. I'll call them <code>feature1</code> and <code>feature2</code>.</p> <p><code>feature1</code> can have three possible values. <code>feature2</code> can have two possible values.</p> <p>I need bar plot grouped by <c...
<p>Also, I have found another way to do this (with pandas):</p> <p><code>df.groupby(['feature1', 'feature2']).size().unstack().plot(kind='bar', stacked=True)</code></p> <p>Source: <a href="https://stackoverflow.com/questions/26683654/making-a-stacked-barchart-in-pandas">making a stacked barchart in pandas</a></p>
python|pandas|plot
24
2,081
67,495,100
Problem with freezing pytorch model - requires_grad is always true
<p>I have tried to freeze part of my model but it does not work. Gradient computation is still enabled for each layer. Is that some sort of bug or am I doing something wrong? :)</p> <pre class="lang-py prettyprint-override"><code>model = models.resnet18(pretrained=True) # To freeze the residual layers for param in mod...
<p>This is just a typo (<code>require_grad</code> must be <code>requires_grad</code>):</p> <pre class="lang-py prettyprint-override"><code># To freeze the residual layers for param in model.parameters(): param.requires_grad = False # it was require_grad for param in model.fc.parameters(): param.requires_grad ...
python|pytorch
2
2,082
67,286,133
Creating new column based on other column values with condition
<p>I have a column with values:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">brand</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">Brand1</td> </tr> <tr> <td style="text-align: left;">Brand2</td> </tr> <tr> <td style="text-align: left;"></td> </tr...
<p>This answer just focusses on <em>Why did the first iteration not work</em></p> <p>In your code when you replace the <code>data.brand</code> with the <code>regex</code>, you replace with <code>np.nan</code> which is not <code>nan</code>, hence the first init cannot identify the condition in the next line : <code>np.w...
python|pandas|dataframe|numpy
2
2,083
34,670,464
How can I add coordinate system / reference frame information to my data to avoid errors?
<p>Often times when dealing with vectors, reference frames are implicitly enforced through documentation, comments, or worse, (human) memory. For example, I want to compute the torque acting on a body moving with a given velocity from a plane due to drag (using a simple drag model):</p> <pre><code>torque = velocity.do...
<p>If I understand correctly you are looking to implement what Sympy provides in the vector module. Have a <a href="http://docs.sympy.org/0.7.2/modules/physics/mechanics/vectors.html" rel="nofollow noreferrer">look</a> at the <code>ReferenceFrame</code> class. </p> <pre><code>from sympy.physics.vector import Reference...
python|math|numpy|coordinates|physics
2
2,084
60,068,277
free up the memory allocation cuda pytorch?
<blockquote> <p>RuntimeError: CUDA out of memory. Tried to allocate 12.00 MiB (GPU 1; 11.91 GiB total capacity; 10.12 GiB already allocated; 21.75 MiB free; 56.79 MiB cached)</p> </blockquote> <p>I encountered the preceding error during pytorch training. <br/> I'm using pytorch on jupyter notebook. Is there a way ...
<p>I had the same issue sometime back. There are generally two way I go about.</p> <ol> <li>Decrease the batch size</li> </ol> <p>Sometimes, even when I had decrease the batch size to '1', this issue persists. Then I changed my approach as follows.</p> <ol start="2"> <li>Decrease the image size ( or patch size, dependi...
gpu|pytorch
2
2,085
59,965,978
Making computation more efficient using a binary file
<p>I am solving N coupled differential equations (u1(t),v1(t),u2(t),v2(t),...) iteratively. I have a ring of N oscillators, and each oscillator is connected to P neighbours. I am trying to improve the efficiency by not saving all of my iteration steps into lists, but instead by exporting my results for every 10th time ...
<p>In your second computation, in the first line, you are allocating the <code>u</code> and <code>v</code> arrays to the same memory location. That is, when you assign to <code>u[j]</code> and <code>v[j]</code>, you assign to the same place, overwriting the previous content. This will give a completely different comput...
python|python-3.x|numpy|binary|differential-equations
1
2,086
63,798,869
Replace dot product for loop Numpy
<p>I am trying to replace the dot product for loop using something faster like NumPy</p> <p>I did research on dot product and kind of understand and can get it working with toy data in a few ways in but not 100% when it comes to implementing it for actual use with a data frame.</p> <p>I looked at these and other SO thr...
<p>Evidently <code>unit_vectors</code> is a dictionary, from which you extract to 2 values, <code>u1</code> and <code>u2</code>.</p> <p>But what are those? Evidently dicts as well (this iteration would not make sense with a list):</p> <pre><code>for dimension in u1: if dimension in u2: dot_product += u1[di...
python|python-3.x|numpy|nlp|self
1
2,087
63,845,441
Key/Value Pairs in Pandas Dataframe
<p>I have a dataframe that I created by merging multiple MATLAB <code>.mat</code> files and then loading the merged list of dictionaries to pandas.</p> <pre><code> KEY_COLUMN VALUE_COLUMN 0 [[[KEY1]], [[KEY2]], [[KEY3]], [[KEY4]]] [[VALUE], [VALUE], [VALUE], [VALUE]] 1 [[[KEY2...
<p>Let's create a new dataframe by mapping key value pairs inside a list comprehension and using <code>np.squeeze</code> to remove the single dimensions:</p> <pre><code>df1 = pd.DataFrame([dict(zip(*map(np.squeeze, v))) for v in df.to_numpy()]) </code></pre> <p>Result:</p> <pre><code># for sample data KEY1 KEY2 ...
python|pandas|matlab|dataframe
0
2,088
46,716,472
Getting a " A nested call to gcloud failed" error when trying to create a datalab in gcloud
<p>Just starting to use Google Cloud Platform. Trying to familiarize myself with tensorflow and am following the Stack Skills tutorial Machine Learning and TensorFlow on the Google Cloud. I am using the gcloud console on firefox and following the tutorial I use the commands</p> <ul> <li>gcloud config set core/project ...
<p>It is likely that "my-first-project" does not exist as a project that your account has access to. You need to create the project first either through the console, or via the command line:</p> <pre><code>gcloud projects create my-first-project </code></pre>
tensorflow|google-cloud-platform|google-cloud-datalab
0
2,089
46,849,831
Using the OR operator seems to only take the first of two conditions when used with np.where filter
<p>Here is a small sampling of my dataset:</p> <pre><code>Search_Term Exit_Page Unique_Searches Exit_Pages_actual nitrile gloves /store/catalog/product.jsp? 10 /store/catalog/product.jsp? zytek gloves /store/product/KT781010 20 /store/pro </code></pre> <p>So th...
<p>@tw-uxtli51nus in the comments is basically correct.</p> <p>We can accomplish what you want by wrapping logical conditions with () and using '|' in place of 'or'.</p> <p>So np.where would look like:</p> <pre><code>df['new_col'] = np.where( ( (df['Exit_Page'].str[:10]=='/store/cat') | (df['Exit_Pag...
python|python-3.x|pandas
1
2,090
38,643,151
Importing structured data into python
<p>I have a text file with a set of arrays in it that looks like this:</p> <pre><code>[(0,1,3),(0,4,5),...(1,9,0)] [(9,8,7),(0,4,5),...(1,9,0)] </code></pre> <p>where the rows are not the same length. </p> <p>This is essentially a list of paths, where each set of points is a path, ie:</p> <pre><code>(0,1,3),(0,4,5...
<p>The following code reads the data in (assuming one path per line, and no extra whitespace) into a list of numpy arrays, then demonstrates how to compute the distance between two points.</p> <pre><code>import numpy as np import numpy.linalg as la #replace with your datafile datafile = "../data/point_path.txt" paths...
python|arrays|numpy|import
0
2,091
63,111,918
Unable to replace NaN value with a date in pandas
<p>Trying to replace a <code>NaN</code> in a <code>datetime</code> column with another <code>datetime</code> object from the same pandas dataframe. I have tried set_value, at, <code>loc</code>. They all result in <code>nan</code> being saved instead of the actual date.<br /> Here is the most recent code I tried, seein...
<p>For example, to fill empty column <code>column_to_fill</code> with values from the same dataframe <code>df</code> with values from column <code>column_from</code> use:</p> <pre><code>df['column_to_fill'] = df['column_to_fill'].fillna(df['column_from']) </code></pre>
python|pandas|datetime|nan
0
2,092
63,214,018
How to prevent/avoid duplicate row insert in dataframe?
<p>here's my code snippet:</p> <pre><code>insert os insert sys insert pandas as pd data=[['2019-04-04',1105],['2019-04-05',1145],['2019-04-06',1125],['2019-04-07',1130],['2019-04-08',1122], ['2019-04-09',1105],['2019-04-10',1145],['2019-04-11',1125],['2019-04-12',1130],['2019-04-13',1122], ['2019-05-04',11...
<pre><code>date_str = '2019-05-14' price = 1200 if any(pp['Date'] == date_str): print('Date already exists.') else: pp.loc[len(pp)] = [date_str, price] print('New date added to dataframe.') print(pp) </code></pre>
python|pandas
0
2,093
62,986,296
TypeError: '<=' not supported between instances of 'str' and 'int' Duplicate
<p>I am using Python3 and I'm working on several files where some of my data (AYield &amp; BYield) is missing which is considered a NaN, however, when I'm running the last line of the code, I get an error. Both Ask and Bid data frames contain the same rows and columns. Thank you</p> <pre><code>Askyield = pd.read_excel(...
<p>I can reproduce this error with this example:</p> <pre><code>import pandas as pd df = pd.DataFrame(dict(x=[&quot;5&quot;, &quot;10&quot;], y=[1, 4])) df.dtypes # x object # y int64 # dtype: object df[df.x &gt; df.y] # TypeError: '&gt;' not supported between instances of 'str' and '...
python|pandas|dataframe|nan
2
2,094
63,285,923
Why is i not incrementing in for loop?
<p>I'm new to programming may I know why my <code>i</code> is not incrementing in the for loop. I want to update the plot name for each subplot. Thank you.<br /> <img src="https://i.stack.imgur.com/5Vbwd.png" alt="Code screenshot" /></p> <pre><code>from matplotlib import pyplot as plt fig= plt.figure() fig,axes = plt.s...
<p>This is because your axes array is like shown below</p> <pre><code>[[&lt;matplotlib.axes._subplots.AxesSubplot object at 0x000001DCA32BB2E0&gt; &lt;matplotlib.axes._subplots.AxesSubplot object at 0x000001DCA54476A0&gt; &lt;matplotlib.axes._subplots.AxesSubplot object at 0x000001DCA547D250&gt;]] </code></pre> <p>...
python|numpy|for-loop|matplotlib|subplot
3
2,095
63,319,129
Index Error: Unable to print cost_function
<p>I am trying to run a for loop to print the cost functions for three different slopes and bias = 0 by defining a function. The dataset has 5 rows and cost function is to predict marks based on attendance. I am able to print cost function if I define three separate functions for each value of slope. Here is my code:</...
<p>You aren't accessing the elements of your slope df correctly. <code>slope.shape</code> returns <code>(3, 1)</code> so you want to iterate through the row number, not the column number.</p> <p><code>sum_of_squared_error += (y - (slope.iloc[0, i]*x + bias)) ** 2</code> should be: <code>sum_of_squared_error += (y - (sl...
python|pandas
1
2,096
67,636,342
python how to choose just special elements from df string
<p>Please, help. I need to choose just 'yellow', 'green', 'black' or combinatons of these elements, if there are several of them in the string. df:</p> <pre><code>0 ['blue','green','white','yellow','orange','pink','black'] 1 ['green','yellow','orange','pink','pink'] 2 ['white','orange','black'] 3 ['green','white','yell...
<p>Your dataframe <code>df</code>:</p> <pre><code> val 0 ['blue','green','white','yellow','orange','pin... 1 ['green','yellow','orange','pink','pink'] 2 ['white','orange','black'] 3 ['green','white','yellow','orange'] 4 ['green'] </code></pre> <p>Try with <code>apply()</code> and list comprehension:</p> <p...
python|pandas
1
2,097
67,644,891
How do I create embeddings for every sentence in a list and not for the list as a whole?
<p>I need to generate embeddings for documents in lists, calculate the Cosine Similarity between every sentence of corpus 1 with every sentence of corpus2, rank them and give out the best fit:</p> <pre><code>embed = hub.load(&quot;https://tfhub.dev/google/universal-sentence-encoder/4&quot;) embeddings1 = [&quot;I'd li...
<p>As I mentioned in the comment, you should write the for loop as follows:</p> <pre><code>for sentence in embeddings1: print(sentence, embed([sentence])) </code></pre> <p>the reason is simply that embed is expecting a list of strings as an input. No more detailed explanation than that.</p>
python|tensorflow|nlp|cosine-similarity|sentence-similarity
0
2,098
31,795,045
How can I make pandas.to_excel() include the index but NOT on a separate line?
<p>When I save a Pandas DataFrame to Excel (with the index option left as it's default: True), the resulting Excel file has a line beneath the row of headers. Said row contains the index name. How can I avoid that extra line and just have the index name(s) show up in the same row as the rest of the column headers?</p> ...
<p>It appears that setting merge_cells (which is by default True) to False accomplishes the objective, but it's not immediately clear to me why that's the case.</p> <pre><code>df[field_list].to_excel(path, merge_cells=False) </code></pre>
python|excel|pandas
0
2,099
41,560,796
Numpy not found after installation
<p>I just installed numpy on my PC (running windows 10, running python 3.5.2) using WinPython, but when i try to import it in IDLE with: <code>import numpy</code> I get the ImportError: <code>Traceback (most recent call last): File "C:\Users\MY_USERNAME\Desktop\DATA\dataScience1.py", line 1, in &lt;module&gt; i...
<p>In Linux and Mac OS systems we can install modules directly by mentioning</p> <pre><code>pip install modulename (or) sudo pip install modulename </code></pre> <p>in terminal or command prompt.</p> <p>But in windows we should mention location of python folder in c directory like c:\python3 and later we should use<...
python|numpy|python-3.5
1