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
369,800
67,089,849
AttributeError: 'GPT2TokenizerFast' object has no attribute 'max_len'
<p>I am just using the huggingface transformer library and get the following message when running run_lm_finetuning.py: AttributeError: 'GPT2TokenizerFast' object has no attribute 'max_len'. Anyone else with this problem or an idea how to fix it? Thanks!</p> <p>My full experiment run: mkdir experiments</p> <p>for epoch...
<p>The <a href="https://github.com/huggingface/transformers/issues/8739" rel="noreferrer">&quot;AttributeError: 'BertTokenizerFast' object has no attribute 'max_len'&quot; Github issue</a> contains the fix:</p> <blockquote> <p>The <code>run_language_modeling.py</code> script is deprecated in favor of <code>language-mod...
tokenize|huggingface-transformers|transformer-model|huggingface-tokenizers|gpt-2
6
369,801
66,856,104
Conditioning on NumPy array based on values from different arrays
<p>Suppose I have two (sample) arrays in the following manner:</p> <pre><code>a = np.array([4, 5,-1, 2, -3, 3, -4]) b = np.array([0, 1, 0, 0, 1, 1, 0]) </code></pre> <p>Now, I want to calculate the count of occurrences where (a &gt; 0 and b == 0) and also where (a &lt; 0 and b == 1). How can I condition an array based ...
<p>One can use the bitwise-and operator <code>&amp;</code>. Take care to wrap the expressions in parentheses because <code>&amp;</code> binds more tightly</p> <pre class="lang-py prettyprint-override"><code>a[(a &lt; 0) &amp; (b == 1)] </code></pre> <p>One can achieve the same behavior with <a href="https://numpy.org/d...
python|numpy
4
369,802
66,950,845
ValueError: Cannot feed value of shape (64,) for Tensor 'TargetsData/Y:0', which has shape '(?, 1)'
<p>I have quite a bit of experience with Python programming in general, but am very new to neural networks and deep learning. After having gone through Tech With Tim's Mega AI course, I decided to create a neural network on my own. It's very simple - it takes in a name and outputs 0 or 1 depending on its gender - 0 = m...
<p>The error is self-explaining</p> <pre><code>ValueError: Cannot feed value of shape (64,) for Tensor 'TargetsData/Y:0', which has shape '(?, 1)' </code></pre> <p>It means your passed shape of <code>y</code> which is <code>(64,)</code> doesn't match the expected shape <code>(?, 1)</code>. To fix it, you only need to c...
python|pandas|numpy|tensorflow|neural-network
0
369,803
66,800,810
How can I randomly set elements to zero in TF?
<p>The pure numpy solution is:</p> <pre><code>import numpy as np data = np.random.rand(5,5) #data is of shape (5,5) with floats masking_prob = 0.5 #probability of an element to get masked indices = np.random.choice(np.prod(data.shape), replace=False, size=int(np.prod(data.shape)*masking_prob)) data[np.unravel_index(in...
<p>Use <a href="https://www.tensorflow.org/api_docs/python/tf/nn/dropout" rel="nofollow noreferrer"><code>tf.nn.dropout</code></a>:</p> <pre><code>import tensorflow as tf import numpy as np data = np.random.rand(5,5) </code></pre> <pre><code>array([[0.38658212, 0.6896139 , 0.92139911, 0.45646086, 0.23185075], [...
python|numpy|tensorflow
2
369,804
66,844,236
Refer to or INNER JOIN a Pandas dataframe value in the WHERE clause of a SQL Server query
<p>I have a pandas dataframe from which I want to retrieve patient values from a SQL Server table based upon their matching patient id column called PatID</p> <pre><code>query = &quot;SELECT * FROM [Hospital].[dbo].[Patient] WHERE PatID= df.PatID&quot; df2 = pd.read_sql(query, sql_conn) </code></pre> <p>Is there any w...
<p>I think that generates a list of your ids and concatenate it in your sql query is the easiest way to solve this problem</p> <pre><code>ids = ','.join(df['PatID'].unique()) query = f&quot;SELECT * FROM [Hospital].[dbo].[Patient] WHERE PatID in ({ids})&quot; df2 = pd.read_sql(query, sql_conn) </code></pre> <p>Be care...
python|sql|sql-server|pandas|join
1
369,805
66,991,331
Replacing nested loops in Python using NumPy
<p>So I have these 6 nested loops, and their purpose is only to multiply and add arrays <code>X</code> and <code>Y</code> over different indices to get array <code>Z</code>.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np dim_a = 5 dim_b = 9 Z = np.zeros((dim_a,dim_b,dim_b,dim_a)) X = np.arange(...
<p>You can certainly do with <a href="https://numpy.org/doc/stable/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>np.einsum</code></a>:</p> <pre><code>Z[i,a,b,j] += X[m,e,b,j] * Y[m,e,a,i] * 2 </code></pre> <p>translates to</p> <pre><code>Z = np.einsum('mebj,meai-&gt;iabj', X,Y) * 2 </code></pre...
python|arrays|python-3.x|numpy
2
369,806
66,849,863
Tensorflow 2 :NotImplementedError: numpy() is only available when eager execution is enabled
<p>There is a question in this code, I delete <code>SeBlock</code> class and just run CNN class, then all is well. If I plug <code>SeBlock</code> to <code>CNN</code> class the error will occur, and display <code>NotImplementedError</code>. I don't know cause this problem, I try to solve this problem, but what method I ...
<p>This <a href="https://github.com/IBM/dl-learning-path-assets/blob/main/fundamentals-of-deeplearning/examples/Eager_Execution_in_TensorFlow_2.x_with_output.ipynb" rel="nofollow noreferrer">notebook</a> should help to upgrade, check, and enable. Good luck!</p>
python|artificial-intelligence|classification|tensorflow2
-1
369,807
67,013,645
Appliyng data augmentation to all but one class in python
<p>I have a dataset with 8 categories and I'm currently performing data augmentation in all the classes with the following code:</p> <pre><code>train_dataGen = ImageDataGenerator(rescale=None,horizontal_flip=True,rotation_range=90, vertical_flip=True) train_generator = train_dataGen....
<p>Yes you need to use 2 generators and you can iterate with the help of chain method</p> <p>following your example :</p> <pre><code>from itertools import chain train_others = ImageDataGenerator(rescale=None,horizontal_flip=True,rotation_range=90, vertical_flip=True) train_cats= Imag...
python|tensorflow|keras|data-augmentation
1
369,808
66,873,185
How to use a custom .csv dataset in TensorFlow Recommenders library?
<p>I'm new to tensorflow. I want to train a recommendation model on my dataset using the TensorFlow Recommenders library and the simple code provided at:</p> <p><a href="https://github.com/tensorflow/recommenders" rel="noreferrer">https://github.com/tensorflow/recommenders</a></p> <p>I want to know how can I use (load ...
<pre><code>import pandas as pd DATA_URL = &quot;D:/ratings.csv&quot; df = pd.read_csv(DATA_URL) ratings = tf.data.Dataset.from_tensor_slices(dict(df)).map(lambda x: { &quot;user_id&quot;: str(x[&quot;user_id&quot;]), &quot;item_id&quot;: str(x[&quot;item_id&quot;]), &quot;rating&quot;: float(x[&quot;rating...
python|tensorflow|tensorflow-datasets|recommendation-engine|recommendation-system
4
369,809
66,777,819
Is there any better way to store unpacked values in python
<p>I'm having a function which unpack 6 values and I'm storing those values in 6 variables but is there any better approach for unpacking those values and storing unlike writing large line of code.</p> <pre><code>var_value1,var_value2,var_value3,var_value4,var_value5,var_value6 = Some_function() </code></pre> <p>Note: ...
<ul> <li><a href="https://www.python.org/dev/peps/pep-0008/#indentation" rel="nofollow noreferrer">Indent</a></li> </ul> <p>or</p> <ul> <li>Create a dictionary, unpack there, <br /> <br /> <code>var_val = Somefunction()._asdict()</code> <br /> <br /> and navigate using keys</li> </ul>
python-3.x|pandas
1
369,810
67,107,580
How to set all unmasked values to a certain value?
<p>In Python I have a masked array, <code>mask_array</code>, and I want to set all remaining (unmasked) values to 1. When I do <code>mask_array[(mask_array &gt;= 0) &amp; (mask_array &lt; 0)= 1</code>, the cells keep their original values and do not change to 1. When I do <code>mask_array[mask_array&gt;=0]=1</code>, al...
<p>The condition <code>(mask_array &gt;= 0) &amp; (mask_array &lt; 0)</code> can't match any cell. No value inside <code>mask_array</code> can be <em>bigger or equal to 0</em> <strong>and</strong> <em>smaller than 0</em> at the same time, so nothing matches =&gt; no changes</p>
python|numpy
1
369,811
67,027,649
How to unlist a list with one value inside a pandas columns?
<p>I have a pandas data frame:</p> <pre><code>Id Col1 1 ['string'] 2 ['string2'] </code></pre> <p>Is possible to convert the data frame into another data frame that look like this?</p> <pre><code>Id Col1 1 string 2 string2 </code></pre> <p>I tried with this way but only get the <code>[</code>....
<blockquote> <p>I tried with this way but only get the [.</p> </blockquote> <p>Then this means they are <code>str</code>ings, not <code>list</code>s. You can convert them to <code>list</code>s by <code>apply</code>ing <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="noreferrer"><code>ast.liter...
python|pandas|dataframe
5
369,812
67,059,958
Invalid number of arguments during code refactoring scipy SLSQP
<p>I am trying to optimize an objective function using <code>scipy.optimize.minimize.</code></p> <p>Initially, I kept getting the error</p> <p><code>TypeError: numpy boolean subtract, the - operator, is deprecated, use the bitwise_xor, the ^ operator, or the logical_xor function instead.</code></p> <p>After looking for...
<p>With a boolean dtype array:</p> <pre><code>In [131]: x = np.ones(4, bool) </code></pre> <p>Your first error:</p> <pre><code>In [132]: x-x Traceback (most recent call last): File &quot;&lt;ipython-input-132-966d70d4047a&gt;&quot;, line 1, in &lt;module&gt; x-x TypeError: numpy boolean subtract, the `-` operator...
python|numpy|scipy-optimize|scipy-optimize-minimize
0
369,813
66,922,933
numpy arrays slicing using reshape
<p>I was learning how to reshape an array. I found several tutorials on the topic. I have confusion after reading all those stuff.</p> <p>Suppose I declared an array using numpy</p> <pre><code>arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) </code></pre> <p>I reshaped it</p> <pre><code>newarr = arr.reshape(4, 3...
<p>arr is unidimensional, then only arr.shape[0] is defined</p> <p>Try printing arr.shape</p>
python|numpy|multidimensional-array|numpy-slicing
0
369,814
66,951,778
Pandas: If NaN show the NaN row as well as the row above
<p>I would like Python Pandas to display not only the row with NaN values but also the row above the respective row with NaN values. I need this because if there is a NaN value in a row I need to delete not only the one with NaN values but also the prior row.</p> <p>Thanks</p>
<p>Take index of all the rows with NaN values in a list. Then create a new index list by subtracting 1 from it. Then delete those indexes.</p> <pre><code>nan_indexes = df[df.row.isnull()].index.tolist() row_above_nan = [x-1 for x in nan_indexes] final_list = nan_indexes + row_above_nan df = df[~df.index.isin(final_lis...
python|pandas|dataframe|nan
0
369,815
67,022,237
KeyError with using get_group in python pandas
<p>I have time series as shown below:</p> <pre><code> date_time system_load date month_year year month day hour load_group 0 2013-01-01 00:00:00 17.2 2013-01-01 2013-01 2013 1 1 0 (15, 20] 1 2013-01-01 01:00:00 16 2013-01-01 2013-01 2013 ...
<p>You must convert the group names to the exact object types which they were stored. Note the <code>dtypes</code> in your <code>df0.info()</code>:</p> <ul> <li><code>month_year</code> is <code>period[M]</code> instead of <code>str</code>.</li> <li><code>load_group</code> is a category column containing <code>pd.Interv...
python-3.x|pandas
1
369,816
66,829,994
Can't open Anaconda Prompt(anaconda3) due to white spaces in user name
<p>Recently, I upgraded to Windows 2004 and since then getting the following message on opening Anaconda Prompt.</p> <blockquote> <p><a href="https://i.stack.imgur.com/eCgsE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eCgsE.jpg" alt="enter image description here" /></a></p> </blockquote> <p>Tried...
<p>This is still a problem without a patch resulting from the <code>Windows 8.3</code> filename convention Where <code>Windows</code> creates a short name of each <code>path</code> after being created, and this short name often has a space which anaconda refusses to pick up. Before you can do any of this you must reins...
python-3.x|windows|tensorflow|keras|anaconda
0
369,817
67,180,564
How to create column in dataframe with list of headings affected by condition, apply a cap and then exclude not respecting condition headings
<p>I'm struggling to solve this issue. Help would be very much appreciated.</p> <p>Note: <strong>bold</strong> in the text refers to the columns i need to create.</p> <p>I have a data set in which I count the values of the row that are different than nan, and it's represented in column [count]. In column <strong>[incl_...
<p>This should work:</p> <pre><code>import pandas as pd import numpy as np non_value_columns = [&quot;index&quot;, &quot;incl_count&quot;, &quot;excl&quot;, &quot;lim&quot;, &quot;count&quot;] max_lim = 3 entries = [] df = pd.read_excel('your.xlsx') for entry in df: if entry not in non_value_columns: print...
python|pandas|dataframe|conditional-statements
0
369,818
66,799,610
Write dataframe to an existing excelfile without destrying it
<p>ive got a problem.</p> <p>I want to write a dataframe to an existing Excel-List which contains formulas. When i Open a workbook and use a writer with pandas, it always says there is unreadable content in it and i need to repair it when i open the Excel-List.</p> <p>Do you know how to resolve this?</p> <p>Here is my ...
<p>have a look at this: <a href="https://stackoverflow.com/a/38075046/14367973">https://stackoverflow.com/a/38075046/14367973</a></p> <p>If i understood your question, you want to append more rows to a <code>.xlsx</code> file. The new rows are from a dataFrame that have the same number of columns than the excel file. I...
python|excel|pandas|dataframe
0
369,819
66,837,752
ffill with limit in numpy
<p>For performance reasons I'd like to use Numpy to do the same kind of forward fill I can get with Pandas like so:</p> <pre class="lang-py prettyprint-override"><code>s = pd.Series([1, 2, nan, nan, nan, 7, 8, nan, nan, nan, nan, nan, nan, nan, nan]) s.ffill(limit=7) </code></pre> <p>which results in:</p> <pre><code>ar...
<p>Basically combined solutions from these two sources:</p> <ul> <li><a href="https://stackoverflow.com/questions/41190852/most-efficient-way-to-forward-fill-nan-values-in-numpy-array">Most efficient way to forward-fill NaN values in numpy array</a></li> <li><a href="https://stackoverflow.com/questions/24885092/finding...
python|numpy
1
369,820
66,871,116
Converting multiple lists into DataFrame
<p>I created those lists to store things i generate over a for loop which is shown a bit further down.</p> <pre><code>neutralScore = [] lightPosScore = [] middlePosScore = [] heavyPosScore = [] lightNegScore = [] middleNegScore = [] heavyNegScore = [] </code></pre> <p>Here comes the loop</p> <pre><code>score = float co...
<p>It is not entirely clear from question how you want your final dataframe to look like. But I would do something like:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; data = np.random.normal(0, 1, size=10) &gt;&gt;&gt; df = pd.DataF...
python|pandas|list
0
369,821
66,952,988
Look up in DataFrame
<p>I have a data frame as below:</p> <pre><code>index name col1 col2 count &quot;there is some values&quot; col1 : is the index of a value in df col2 : is the index of a value in df </code></pre> <p>I want find the name related to index in col 1 and col 2 and put them in the match 1 and match 2. I want...
<p>If I understood the question correctly, I believe this will get you there:</p> <pre><code>df = pd.DataFrame([ ['x1', 5, 3, 2, 'x5', 'x3'], ['x2', 4, 6, 3, 'x4', 'x6'], ['x3', np.nan, np.nan, 7, ], ['x4', np.nan, np.nan, 1, ], ['x5', np.n...
python|pandas|dataframe
1
369,822
66,871,925
Generating a probability distribution P(y) from another probability distribution P(x) such that highest probability in P(x) is least likely in P(y)
<p>So the problem at hand is that I have some values in a dictionary with counters, let's say</p> <pre><code>dict = {&quot;cats&quot;:0, &quot;dogs&quot;:0, &quot;lions&quot;:0} </code></pre> <p>I want to randomly select the keys from this dictionary and increment the counters as I select the particular keys.</p> <p>...
<p>There are <strong>many</strong> ways of solving this, but as an alternative I'd be tempted to calculate the probabilities as:</p> <pre><code>def iweight(k, *, alpha=1): p = 1/(alpha + np.array(k)) return p / np.sum(p) </code></pre> <p>which could be used as:</p> <pre><code>counts = [0, 0, 0, 20] for _ in ran...
python|random|probability|probability-distribution|numpy-random
2
369,823
66,804,489
age calculation in pandas data frame
<p>My data frame looks like -</p> <pre><code>id dob 1 13/01/1978 2 03/08/1957 3 22/12/1977 </code></pre> <p>I want to calculate age based on 'dob' column.</p> <pre><code>id dob age 1 13/01/1978 43 2 03/08/1957 64 3 22/12/1976 44 </c...
<p>Here is a solution:</p> <pre><code>d = { 'Id': [1,2,3], 'dob': ['13/01/1978', '03/08/1957', '22/12/1977'] } df = pd.DataFrame(d) df['dob']= pd.to_datetime(df['dob']) now = datetime.datetime.now() df['age'] = df['dob'].apply(lambda x: now.year - x.year) #Output: Id dob age 0 1 1978-01-13 43...
python|pandas|scikit-learn
1
369,824
67,043,448
Local TFJS Model (Transfer Learning MobileNet) returns wrong predictions
<p>I use transfer learning with MobileNet to solve an image problem. I loaded the images with ImageDataGenerator <code>(rescale=1./127.5)</code>.</p> <p>After training I converted it with:</p> <pre><code>tensorflowjs_converter --input_format=tf_saved_model --weight_shard_size_bytes 10000000000 model tmp </code></pre> <...
<p>Solved it with this normalization:</p> <pre><code>const normalized = imageTensor.toFloat().sub(127).div(128); </code></pre>
tensorflow|expo|tensorflow.js
0
369,825
66,890,904
Python calculated Timedelta 50 years in future, should be same day
<p>This is a follow up to <a href="https://stackoverflow.com/questions/66683405/calculating-new-column-value-in-dataframe-based-on-next-rows-column-value">Calculating new column value in dataframe based on next rows column value</a></p> <p>The solution in the previous question worked for a column holding hh:mm:ss value...
<p>The solution to this was easy, and staring me in the face.</p> <p>The offending code:</p> <pre><code>s = pd.to_timedelta(df.start_time).shift(-1).sub(pd.offsets.Second(1)) </code></pre> <p>The <strong>correct</strong> way to create an end_time off of a timestamp type series/column:</p> <pre><code>s = pd.to_timestamp...
python|pandas|timestamp|timedelta
0
369,826
67,029,716
Turn dictionary into dataframe
<p>I'm new to Python. I have this kind of dictionary, from a geodesic output and i wonder if i can turn this into DataFrame or matrix? here's an example data, but what i'm working right now has more than 8000 data</p> <pre><code>{(0, 0): 0.0, (0, 1): 1.3128088339744233, (1, 0): 1.3128088339744233, (1, 1): 0.0} </cod...
<p>Try this -</p> <blockquote> <p>I have added additional entries to show how this approach scales to more rows and column indexes, and handles missing row, column indexes as well.</p> </blockquote> <pre><code>d = {(0, 0): 0.0, (0, 1): 1.3128088339744233, (1, 0): 1.3128088339744233, (1, 1): 0.0} df = pd...
python|pandas
3
369,827
66,831,480
"Importing tensorflow module not found" Only on jupyter notebook but not jupyter lab or terminal
<p>I launch the powershell anaconda prompt and activate an environment for a new project. Then I install tensorflow using the command provided by the tensorflow website <code>pip install tensorflow</code>.</p> <p>To validate that the installation was successful, I open python from within the terminal and import tensorf...
<p>Follow these steps install Tenosrflow on Virtual environment with PIP</p> <pre><code>#Install virtualenv sudo pip3 install virtualenv #Create virtual environment name: venv virtualenv venv #Activate venv source venv/bin/activate #Install tensorflow venv$ pip3 install tensorflow #Install Jupyter notebook venv$ pip3 i...
python|tensorflow|jupyter-notebook|anaconda
0
369,828
66,977,408
PIL: How to draw shapes given a set of unordered outline dimensions
<p>I am using Python version 3.8.7 and the PIL library.</p> <p>I have a DataFrame full of dimensions of various elements of a blueprint. The two main elements are lines (composing the outline), and the labels (colored rectangles). Using PIL I was able to draw the below image.</p> <p><a href="https://i.stack.imgur.com/x...
<p>If this is the expected result:</p> <p><a href="https://i.stack.imgur.com/ByPXo.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ByPXo.jpg" alt="enter image description here" /></a></p> <p>You can use this pseudo-code:</p> <pre><code>for thisColour in list of blob colours (1) generate list of ne...
python-3.x|pandas|dataframe|python-imaging-library|shapes
1
369,829
66,886,187
Python dictionary, how can I create a key with a string and the actual key combined?
<p>I hope this is a quite easy question, but for me without a lot of python background I can't find an answer.</p> <pre><code>df = pd.DataFrame( {'Messung': ['10bar','10bar','10bar','20bar','20bar'], 'Zahl': [1, 2, 3, 4, 5], 'Buchstabe': ['a','b','c','d','e']}) </code></pre> <p>There is a DataFrame ...
<p>While trying your solution I noticed, I can even delete the line with key=item[0:2] and directly build my key with 'RP_' and the item[0:2]</p> <pre><code>d={} for row, item in enumerate(df['Messung']): key = &quot;RP_&quot;+item[0:2] d.setdefault(key, []).append(df.iloc[row]) </code></pre>
python|pandas|dictionary|key|notin
0
369,830
47,418,871
how can I normalize n different set of data using a provided method which can only normalize a set of data
<p>I have n set of changing data, and I want to normalize every set of data using the <a href="https://stats.stackexchange.com/questions/43159/how-to-calculate-pooled-variance-of-two-groups-given-known-group-variances-mean">running mean method</a>, since every set has its own mean and std, I have to keep n different mo...
<p>Create an array of Scalar instances. If you have different <code>obs_dim</code> for each dataset, you can do <code>[Scalar(obs_dim) for obs_dim in obs_dims]</code>. If you have one <code>obs_dim</code>, use <code>[Scalar(obs_dim) for i in range(N)]</code> where <code>N</code> is the number of datasets. You can then ...
python|numpy|machine-learning|deep-learning
2
369,831
47,272,523
Update inventory stock csv file with python
<p>I have a stock inventory file in csv format like this:</p> <pre><code>sku nome prezzo qty codice 1 uno 10 1 11111 2 due 10 1 22222 3 tre 10 1 33333 4 quattro 10 1 44444 5 cinque 10 1 55555 10 dieci 10 1 101010 </code></pre> <p>The only column...
<p>IIUC:</p> <pre><code>In [52]: r = b.set_index('sku') \ ...: .reindex(pd.Index(a['sku']).union(pd.Index(b['sku']))) \ ...: .combine_first(a.set_index('sku').assign(qty=0, prezzo=0)) \ ...: .reset_index() ...: In [53]: r[['prezzo','qty','codice']] = r[['prezzo','qty','codice']].asty...
python|pandas|csv|python-3.6
1
369,832
47,491,865
i want to install tensor flow in anaconda but it shows error :
<p>i tried many ways to install tensor flow on my windows system with anaconda 5.0 and python 3.6</p> <p>pip3 install --upgrade <a href="https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.0.0-py3-none-any.whl" rel="nofollow noreferrer">https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.0.0-py3-...
<p>Finally , Solved my problem by reinstalling the anaconda and python 3.5. and after the re-installation i install tensor-flow by anaconda navigator and it worked for me.</p>
python-3.x|tensorflow|installation|anaconda
0
369,833
47,344,577
How to query a pandas DataFrame using an array of tuples ?
<p>I have a pandas DataFrame with the following structure:</p> <p><a href="https://i.stack.imgur.com/XQk6i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XQk6i.png" alt="sample data frame image"></a></p> <p>And I have an array of tuples</p> <p><code>arr_tuples = [(0,3),(1,1),(1,3),(2,1)]</code></...
<p>You can use <code>pd.DataFrame.lookup</code> with some <code>zip</code> and unpacking trickery</p> <pre><code>df.lookup(*zip(*arr_tuples)) array([ 4, 5, 7, 12]) </code></pre> <hr> <ul> <li><p><code>list(zip(*arr_tuples))</code> creates two tuples out of the list of tuples</p> <pre><code>[(0, 1, 1, 2), (3, 1, ...
python|pandas|numpy|dataframe|indexing
8
369,834
47,319,291
How to parse String output of a tensorflow model
<p>Created a model using the code here : <a href="https://gist.github.com/gaganmalhotra/1424bd3d0617e784976b29d5846b16b1" rel="nofollow noreferrer">https://gist.github.com/gaganmalhotra/1424bd3d0617e784976b29d5846b16b1</a></p> <p>To get the predictions of the probabilites in java it can be done using below code:</p> ...
<p>The <code>DT_STRING</code> typed TensorFlow tensors contain <a href="https://www.tensorflow.org/api_docs/java/reference/org/tensorflow/DataType" rel="nofollow noreferrer">arbitrary byte sequences</a> as elements, not Java <code>String</code>s (sequence of characters).</p> <p>Thus, what you want is something like th...
java|python|tensorflow|tensorflow-serving
2
369,835
47,395,119
Center datetimes of resampled time series
<p>When I resample a Pandas time series to reduce the number of data points, the timestamp of each resulting datapoint is at the start of each resampling bin. When overplotting graphs with different resampling rates, this causes an apparent shift of the data. How can I "center" the timestamp of the resampled data in it...
<p>I don't know how to use the midpoint in general. There is the <code>label</code>-parameter, but that only has the options <code>right</code> and <code>left</code>. However, in a concrete case as this you can explicitly offset the resampled timestamp with the <code>loffset</code>-parameter:</p> <pre><code>d.resample...
python|pandas
3
369,836
47,214,979
concatenate two matrices with interleaved columns
<p>I have two 2-D arrays and I would like to concatenate them interleaving the columns </p> <p>Initial arrays (with shape (3, 8) each):</p> <pre><code>array([[ 107, 115, 132, 138, 128, 117, 121,135], [ 149, 152, 151, 143, 146, 149, 149,148], [ 152, 142, 146 , 141, 143, 148, 149, 153]])...
<p>You can column stack the two arrays, then reshape:</p> <pre><code>np.column_stack((a, b)).reshape(-1, a.shape[1]) #array([[107, 115, 132, 138, 128, 117, 121, 135], # [ 25, 28, 28, 25, 23, 21, 20, 18], # [149, 152, 151, 143, 146, 149, 149, 148], # [ 3, 3, 2, 2, 10, 12, 12, 1], #...
python|numpy|matrix
3
369,837
47,356,011
how do i make labels list manually for my imported images in tensorflow
<pre><code>fq=glob.glob("*.jpg") # ['0.jpg','1.jpg','2.jpg','3.jpg','4.jpg'],labels for images=[1,1,1,0,0] loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=onehot)) </code></pre> <p>assuming that there is just <strong>2 classes</strong> and <strong>batch size is 2</strong> and <...
<p>If your input array is a NumPy array, you can use <code>np.eye</code>:</p> <pre><code>label_array = np.array([1, 1, 1, 0, 0]) onehot_array = np.eye(2)[label_array] </code></pre> <p>The result is: [[ 0. 1.], [ 0. 1.], [ 0. 1.], [ 1. 0.], [ 1. 0.]]</p>
tensorflow
0
369,838
47,325,413
Pandas calling partial row data
<p>I have the following data in a column:</p> <pre><code>Company Name Company Name\Cortana Place\rBaton Rouge, LA 70815 Some Product Company\r1Highway 21\rMadis df = pd.read_csv(csv_cropped_tabula, encoding = "ISO-8859-1") </code></pre> <p>when I call <code>df['Company Name'][0]</code> or <code>df['Company Name'][1...
<p>It's parsing the embedded commas as separators, it looks like you only have a single column so you can tell it to only load that column and pass <code>lineterminator='\n'</code>:</p> <pre><code>In[86]: t="""Company Name Company Name\Cortana Place\rBaton Rouge, LA 70815 Some Product Company\r1Highway 21\rMadi""" df ...
python|python-3.x|pandas|python-3.6
0
369,839
47,196,719
Pandas: Convert fractional months to datetime
<p>I have some monthly data with a date column in the format: YYYY.fractional month. For example:</p> <pre><code>0 1960.500 1 1960.583 2 1960.667 3 1960.750 4 1960.833 5 1960.917 </code></pre> <p>Where the first index is June, 1960 (6/12=.5), the second is July, 1960 (7/12=.583) and so on.</p> <p>...
<p>I think you need a bit maths:</p> <pre><code>a = df['date'].astype(int) print (a) 0 1960 1 1960 2 1960 3 1960 4 1960 5 1960 Name: date, dtype: int32 b = df['date'].sub(a).add(1/12).mul(12).round(0).astype(int) print (b) 0 7 1 8 2 9 3 10 4 11 5 12 Name: date, dtype: int32 c =...
python|pandas|datetime
3
369,840
47,316,783
Python Dataframe: Remove duplicate words in the same cell within a column in Python
<p>Below shows a column with data I have and another column with the de-duplicated data I want. </p> <p><a href="https://i.stack.imgur.com/bHyD1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bHyD1.png" alt="enter image description here"></a></p> <p>I honestly don't even know how to start doing this in Py...
<p>If you're looking to get rid of consecutive duplicates <em>only</em>, this should suffice:</p> <pre><code>df['Desired'] = df['Current'].str.replace(r'\b(\w+)(\s+\1)+\b', r'\1') df Current Desired 0 Racoon Dog Racoon Dog 1 Cat Cat Cat 2 Dog Dog Dog Dog ...
python|string|pandas|dataframe
21
369,841
47,341,519
json_normalize for dicts within dicts
<p>I have been trying to <code>normalize</code> a very nested json file I will later analyze. What I am struggling with is how to go more than one level deep to normalize.</p> <p>I went through the <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.io.json.json_normalize.html" rel="nofollow ...
<pre><code>In [23]: lst = [l for l in raw['hits']['hits'] if l['_source'].get('authors')] In [24]: json_normalize(lst, [['_source', 'authors']], ['_id', ['_source', 'journal'], ['_source', 'title']]) Out[24]: affiliations author_id author_name ...
python|json|pandas
2
369,842
47,417,537
Pandas: Cascading Partition over multiple keys
<p>I have a dataframe that looks something like this:</p> <pre><code>nodename ip &lt;otherfields&gt; amelia 192.168.23.8 &lt;...&gt; boris 10.8.45.3 &lt;...&gt; boris 192.168.67.4 &lt;...&gt; clyde 192.168.45.3 &lt;...&gt; darwin 192.168.67.4 &lt;...&gt; el...
<p>For posterity:</p> <p>I ended up looping through my dataset using the following algorithm:</p> <pre><code>1. Select first unmatched row currently in the dataset and use that to initialise sets of search keys. 2. Iteratively select all rows matching the keys, and rebuild the sets of search keys. 3. When the sets ...
python|pandas
0
369,843
47,502,981
tf.decode_raw and tf.reshape using different image size
<p>I'am using the following code to generate tfrecords file.</p> <pre><code> def generate_tfrecords(data_path, labels, name): """Converts a dataset to tfrecords.""" filename = os.path.join(args.tfrecords_path, name + '.tfrecords') writer = tf.python_io.TFRecordWriter(filename) for index, data in enu...
<p>Use <a href="https://www.tensorflow.org/api_docs/python/tf/image/decode_jpeg" rel="noreferrer">decode_jpeg</a> instead of decode_raw</p>
tensorflow|tensorflow-datasets
7
369,844
47,108,856
g2p-seq2seq error: 'module' object has no attribute 'core_rnn_cell'
<p> I'm trying to get g2p-seq2seq to work as per github instructions: <a href="https://github.com/cmusphinx/g2p-seq2seq" rel="nofollow noreferrer">https://github.com/cmusphinx/g2p-seq2seq</a></p> <p>However I get the following error when I try to validate the installation with <code>$ g2p-seq2seq --interactive --model...
<p>I had to downgrade the tensorflow version to 1.0 to make this work.</p>
tensorflow|cmusphinx
1
369,845
47,145,311
Transform 1-D numpy array into 3D RGB array
<p>What is the best way to transform an 1D array that contains rgb data into a 3D RGB array ?</p> <p>If the array was in this order, it would be easy, (a single reshape)</p> <blockquote> <p>RGB RGB RGB RGB...</p> </blockquote> <p>However my array is in the form,</p> <blockquote> <p>RRRR...GGGG....BBBB</p> </blo...
<p>Reshape to <code>2D</code>, transpose and then reshape back to <code>3D</code> for <code>RRRR...GGGG....BBBB</code> form -</p> <pre><code>a1D.reshape(3,-1).T.reshape(height,-1,3) # assuming height is given </code></pre> <p>Or use reshape with <code>Fortran</code> order and then swap axes -</p> <pre><code>a1D.resh...
python|arrays|numpy|rgb
3
369,846
47,243,021
Numpy: subtract matrix from all elements of another matrix without loop
<p>I have two matrices X,Y of size (m x d) and (n x d) respectively. Now i want to subtract the whole matrix Y from each element of the matrix X to get a third matrix Z of size (m x n x d). Using loops it would look this:</p> <pre><code>Z = [(Y-x) for x in X] </code></pre> <p>but i want to avoid loops and use numpy o...
<p>If i understand correctly, here is a small demo:</p> <pre><code>In [81]: X = np.arange(6).reshape(2,3) In [82]: Y = np.arange(12).reshape(4,3) In [83]: X Out[83]: array([[0, 1, 2], [3, 4, 5]]) In [84]: Y Out[84]: array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]) In [85]...
python|numpy|matrix
2
369,847
47,359,743
How to make Min-plus matrix multiplication in python faster?
<p>So I have two matrices, A and B, and I want to compute the min-plus product as given here: <a href="https://en.wikipedia.org/wiki/Min-plus_matrix_multiplication" rel="nofollow noreferrer">Min-plus matrix multiplication</a>. For that I've implemented the following:</p> <pre><code>def min_plus_product(A,B): B = n...
<p>Here is an algo that saves a bit if the middle dimension is large enough and entries are uniformly distributed. It exploits the fact that the smallest sum typically will be from two small terms.</p> <pre><code>import numpy as np def min_plus_product(A,B): B = np.transpose(B) Y = np.zeros((len(B),len(A))) ...
python|performance|numpy|matrix
4
369,848
47,166,372
Jupyter Pandas DataFrame - reading column values
<p>I have a snippet of python code that reads the values for SQL columns for a given row. The snippet below simply iterates thru columns within a DataFrame context and appends the numeric values to an array.</p> <p>If i print out the value of each column, the output looks correct. However, if I print out the final arr...
<p>I think you need convert values to <code>numpy array</code>, transpose and convert to <code>list</code>:</p> <pre><code>df = pd.DataFrame({ 'A': ['a','e','g'], 'B': list(range(3)) }) print (df) A B 0 a 0 1 e 1 2 g 2 L = df.values.T.tolist() print (L) [['a', 'e', 'g'], [0, 1, 2]] </code></pre> <p...
python|pandas|dataframe
2
369,849
47,167,670
Mixed precision not enabled with TF1.4 on Tesla V100
<p>I was interested in testing my neural net (an Autoencoder that serves as a generator + a CNN as a discriminator) that uses 3dconv/deconv layers with the new Volta architecture and benefit from the Mixed-Precision training. I compiled the most recent source code of Tensorflow 1.4 with CUDA 9 and CudNN 7.0 and cast al...
<p>Based on <a href="http://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html#tensorflow" rel="nofollow noreferrer">NVIDIA documentation</a> I run benchmark with FP16 (TensorCore). For that I modyfied <code>alexnet_benchmark</code> delivered by tensorflow: <a href="https://gist.github.com/melgor/946b...
tensorflow|tesla
3
369,850
47,492,387
Python Linear Regression input values
<p>I have a Excel sheet with 2 colums and 1000 rows. I want to give this as inputs to my Linear Regression Fit command using the sklearn. / when I want to create a dataframe using panda how can I give the inputs? like <code>df_x=pd.dataFrame(...)</code></p> <p>I used without dataframe sucessfully as:</p> <pre><code>n...
<p>I think you can convert a pandas dataframe to a numpy array by <code>np.array()</code></p> <p>This is discussed here: <a href="https://www.quora.com/How-does-python-pandas-go-along-with-scikit-learn-library-Has-anyone-doing-data-analysis-using-pandas-and-then-then-fit-models-using-scikit-learn" rel="nofollow norefe...
python|pandas
0
369,851
47,272,971
Pytorch: how to convert data into tensor
<p>I am a beginner for Pytorch. I was trying to write CNN code referring Pytorch tutorial. Below is a part of the code, but it shows error "RuntimeError: Variable data has to be a tensor, but got list". I tried to cast input data to tensor but didn't work well. If anybody know the solution, please help me out...</p> <...
<p>If my guess is correct, you are probably getting error in the following line.</p> <pre><code># wrap them in Variable images_batch, labels_batch = Variable(images_batch), Variable(labels_batch) </code></pre> <p>It means, <code>images_batch</code> and/or <code>labels_batch</code> are lists. You can simple convert th...
python|machine-learning|deep-learning|pytorch
10
369,852
11,249,427
Display a live numpy array
<p>In APL, you can trivially bring up a window that shows the contents of a variable whilst your program is running and watch it update live.</p> <p>This is illustrated by the classic <a href="http://www.youtube.com/watch?v=a9xAKttWgP4" rel="nofollow">Game of Life</a> video at 5 minutes in.</p> <p>Is there any simila...
<p>Have you looked at the python debugger? (<a href="http://docs.python.org/library/pdb.html" rel="nofollow">pdb</a>)</p> <p>It's not graphical but it is completely portable. Depending what IDE you're using, there might be a visual debugger built in.</p>
python|numpy|debugging|inspector
1
369,853
11,286,864
Is there a way to check if NumPy arrays share the same data?
<p>My impression is that in NumPy, two arrays can share the same memory. Take the following example:</p> <pre><code>import numpy as np a=np.arange(27) b=a.reshape((3,3,3)) a[0]=5000 print (b[0,0,0]) #5000 #Some tests: a.data is b.data #False a.data == b.data #True c=np.arange(27) c[0]=5000 a.data == c.data #True ( S...
<p>You can use the <a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.base.html" rel="nofollow noreferrer">base</a> attribute to check if an array shares the memory with another array:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.arange(27) &gt;&gt;&gt; b = a.reshape((3,3,3)) ...
python|numpy
38
369,854
68,383,634
CUDA error: CUBLAS_STATUS_INVALID_VALUE error when training BERT model using HuggingFace
<p>I am working on sentiment analysis on steam reviews dataset using BERT model where I have 2 labels: positive and negative. I have fine-tuned the model with 2 Linear layers and the code for that is as below.</p> <pre><code> bert = BertForSequenceClassification.from_pretrained(&quot;bert-base-uncased&quot;, ...
<p>I suggest trying out couple of things that can possibly solve the error.</p> <p>As shown in this <a href="https://discuss.pytorch.org/t/runtimeerror-cuda-error-cublas-status-invalid-value-when-calling-cublassgemm-handle-opa-opb-m-n-k-alpha-a-lda-b-ldb-beta-c-ldc/124544" rel="nofollow noreferrer">forum</a>, one possi...
python|pytorch|sentiment-analysis|bert-language-model
2
369,855
68,447,264
Pytorch: mat1 and mat2 shapes cannot be multiplied
<p>I have set up a toy example for my first pytorch model:</p> <pre><code>x = torch.from_numpy(np.linspace(1,100,num=100)) y = torch.from_numpy(np.dot(2,x)) </code></pre> <p>I have built the model as follows:</p> <pre><code>class Net(nn.Module): def __init__(self): super(Net,self).__init__() self.fc...
<p>There are four issues here:</p> <ol> <li><p>Looking at the model's first layer, I assume your batch size is 100. In that case, the correct input shape should be <code>(100, 1)</code>, not <code>(100,)</code>. To fix this you could use <a href="https://pytorch.org/docs/stable/generated/torch.unsqueeze.html" rel="nofo...
python|pytorch
2
369,856
68,039,160
Join Table in python Pandas (like Vlookup based on two columns value similarity)
<p>it should be easy but I don't find the solution. I want to join two data frames using pandas, joined like V loop Up style when comparing values of two columns from two data frames. See example</p> <pre><code> df1_test = pd.DataFrame({'X_mm': [1,2,3,4,5], 'Y_mm': [2,5,6,7,9], ...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>print(df1_test.merge(df2_test, on=[&quot;X_mm&quot;, &quot;Y_mm&quot;])) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> X_mm Y_mm Measurement_from_df1 Measurement_from_df2 0 1 2 18.3 ...
python|pandas|dataframe|join
0
369,857
68,244,304
pandas: instead of applying the function to df get the result as a list from the function
<p>I have a dataframe like the following:</p> <pre><code>df = pd.DataFrame({ 'text':['the weather is nice though', 'How are you today','the beautiful girl and the nice boy'], 'pos':[&quot;['DET', 'NOUN', 'VERB','ADJ', 'ADV']&quot;,&quot;['QUA', 'VERB', 'PRON', 'ADV']&quot;, &quot;['DET', 'ADJ', 'NOUN','CON','DET', 'ADJ...
<p>Here's how you could use the function to get a list back, based on your DataFrame:</p> <pre class="lang-py prettyprint-override"><code>from typing import List df = pd.DataFrame({ 'text':['the weather is nice though', 'How are you today','the beautiful girl and the nice boy'], 'pos':[['DET', 'NOUN', 'VERB','ADJ', 'A...
python|pandas|append|refactoring
2
369,858
68,055,535
check for value in pandas Dataframe cell which has a list
<p>I have the following df:</p> <pre><code>df = pd.DataFrame(columns=['Place', 'PLZ','shortName','Parzellen']) new_row1 = {'Place':'Winterthur', 'PLZ':[8400, 8401, 8402, 8404, 8405, 8406, 8407, 8408, 8409, 8410, 8411], 'shortName':'WIN', 'Parzellen':[]} new_row2 = {'Place':'Opfikon', 'PLZ':[8152], 'shortName':'OPF', '...
<p>try with boolean masking and <code>map()</code> method:</p> <pre><code>df[df['PLZ'].map(lambda x:8405 in x)] </code></pre> <p>OR</p> <p>via boolean masking and <code>agg()</code> method:</p> <pre><code>df[df['PLZ'].agg(lambda x:8405 in x)] #you can also use apply() in place of agg </code></pre> <p>output of above co...
python|pandas|dataframe
2
369,859
68,164,092
Filtering rows in a data frame based on value in the last column
<p>I want to remove any rows in a data frame if a cell in the last column is empty(Nan). More columns will be added to the data overtime so I just want it to look at the last column.</p> <p>Here is the dataframe 0 1 2 3 4 aa bb cc dd 1 ae we df gh Nan wr th fg rg Nan</p> <p>And the expected result 0...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with test if no missing value in last column by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.notna.html" rel="nofollow noreferre...
python|pandas
0
369,860
68,416,878
How to sort multiindex column month names?
<p>I have this multiindex <code>df</code>:</p> <pre><code> YEARS_TMAX TMAX YEARS_TMAX TMAX YEARS_TMAX MONTH April April August August December ..... CODE NAME 000130 RICA PLAYA 21.0 31.5 21.0 21.5 ...
<p>Use a <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html" rel="nofollow noreferrer">CategoricalDtype</a> by creating an ordered dtype from <a href="https://docs.python.org/3/library/calendar.html#calendar.month_name" rel="nofollow noreferrer">calendar.month_name</a> this will ensure th...
python|pandas
1
369,861
68,074,556
Changing column based on multiple conditions and previous rows values pandas
<p>I have this dataframe. I need to replace NaNs in column <strong>rank</strong> to a value based on multiple conditions. If column <strong>min</strong> is higher than 3 previous rows of <strong>max</strong> column then <strong>rank</strong> equals to <strong>min</strong>. Otherwise, I need to copy the previous value o...
<p>IIUC, here's one way:</p> <pre><code>df['rank'].mask(pd.concat([df['min'].shift(i) for i in range(3)], 1).apply( lambda x: x &lt; df['min']).all(1), df['min']).ffill() </code></pre> <h5>OUTPUT:</h5> <pre><code> max min rank 0 128.20 117.87 117.87 1 132.72 122.29 122.29 2 138.07 124.89 124.89...
python|pandas|dataframe
1
369,862
68,268,987
Splitting dataframe by date periods
<p>I wonder if you could point me in the right direction?</p> <p>I have a dataframe with a dateindex and corresponding values:</p> <hr /> <h2>date|value</h2> <p>2010-10-16 | 485</p> <p>2010-10-17 | 486</p> <p>... ...</p> <p>2013-10-12 | 8588</p> <p>2013-10-12 | 8589</p> <hr /> <p>and I want to split this dataframe ...
<p>I prefer here dictionary of DataFrames:</p> <pre><code>start_date = df['date'].min() end_date = df['date'].max() months = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month) </code></pre> <hr /> <pre><code>dfs = {f'period_{i+1}': df[df['date'].between(start_date + pd.DateOffset(months=i), ...
python|pandas|dataframe|date|time
0
369,863
68,176,249
Pandas. Check if any of the split strings from one column are in another
<p>I have a data frame with 2 columns with strings comma-separated.<br /> I'm trying to make speed-efficient solution to calculate 3-d column indicating if any of split strings from column <code>A</code> present in column <code>B</code>.<br /> For example:</p> <pre><code>df = pd.DataFrame({'A':['apple', 'cucamber', 'to...
<p>One idea with lsit comprehension and <code>any</code> for test if match at least one string:</p> <pre><code>df['C'] = [any(z in y for z in x.split(',')) for x, y in df[['A','B']].to_numpy()] df['C'] = df['C'].astype(int) print (df) A B C 0 apple apple,banana 1 1 ...
python|pandas
2
369,864
68,272,050
dataframe value diagonal shift row
<p>I would like to have left shift for each row in <code>df</code>, like a diagonal shift. I have df like that:</p> <pre><code> a1 a2 a3 a4 row1 1 5 5 3 row2 0 4 1 4 row3 0 0 7 6 row4 0 0 0 2 </code></pre> <p>and would like to have it like:</p> <pre><code> a1 a2 a3 ...
<p>IIUC, here's one way:</p> <pre><code>df1 = df.mask(df.eq(0)).apply(lambda x: pd.Series(sorted(x, key=pd.isnull)), axis = 1).fillna(0, downcast='infer') df1.columns = df.columns </code></pre>
python|pandas|dataframe|shift
1
369,865
68,388,894
Value Error with numpy when installed TensorFlow
<p>I am running into this error when i import this</p> <p><code>from gensim.models import KeyedVectors</code></p> <p>the error is</p> <pre><code> File &quot;c:\Users\frase\eg1.py&quot;, line 11, in &lt;module&gt; from gensim.models import KeyedVectors File &quot;C:\Users\frase\AppData\Local\Programs\Python\Pytho...
<p>Solutions.</p> <ol> <li><p>Downgrade python environment to 3.8/3.7</p> </li> <li><p>uninstall Numpy and upgrade to Latest NumPy version</p> </li> </ol> <p>Reference- <a href="https://stackoverflow.com/questions/66060487/valueerror-numpy-ndarray-size-changed-may-indicate-binary-incompatibility-exp">ValueError: numpy...
python|numpy|tensorflow|keras|neural-network
0
369,866
68,028,490
Android Studio: import org.tensorflow.Operation does not seem to work
<p>I am using the latest Android Studio to create an image recognition project. I am using a .pb file downloaded from Github.</p> <p>I have added &quot;<code>implementation 'org.tensorflow:tensorflow-android:1.5.0'</code>&quot; in build.gradle file.</p> <p>When I go to the java file, the following two import statements...
<p>Please ignore this question. I misunderstood what &quot;unused&quot; means.</p>
android-studio|tensorflow|image-recognition
0
369,867
68,446,439
How can I scrape multiple pages with scrapy in my python code?
<p>So I am currently making a scraper project for this one website: <a href="https://www.datacenters.com/locations?page=1&amp;per_page=40&amp;query=&amp;withProducts=false&amp;showHidden=false&amp;nearby=false&amp;radius=0&amp;bounds=&amp;circleBounds=&amp;polygonPath=" rel="nofollow noreferrer">https://www.datacenters...
<p>If you view the page in a browser, and log your network traffic while clicking through the result pages, you'll notice an XHR HTTP GET request being made to a REST API endpoint, the response of which is JSON and contains a lot of information for all warehouse locations for a given page of 40 results. You can imitate...
python|pandas|web-scraping|scrapy|web-crawler
0
369,868
68,360,411
Pandas data frame column containing list of dicts
<p>Hi I have the following pandas data frame:</p> <pre><code>df = pd.DataFrame({'info':[1.4,3.6,6.5], 'new':[[{'score':0.998, 'letters':'C', 'temp':1}, {'score':1.343, 'letters':'B', 'temp':0}, {'score':2.323, 'letters':'F', 'temp':1}], [{'score':2.532, 'letters':'D', 'temp':1}, {'score':2.123, 'letters':'G', 'temp':1}...
<p>Use list with dict comprehension for new columns names with <code>enumerate</code>:</p> <pre><code>d = [{f'{k}{i}': v for i,y in enumerate(x, 1) for k,v in y.items()} for x in df['new']] df = pd.DataFrame(d, index=df.index).sort_index(axis=1) print (df) letters1 letters2 letters3 score1 score2 score3 temp1 t...
python|pandas
2
369,869
68,206,280
Split tuple of two elements and add to pandas dataframe
<p>I have a list of tuple in python:<code>[(3, 0), (3, 6), (9, 6), (9, 9), (13, 10), (13, 1), (16, 8), (12, 17), (20, 18), (10, 21), (24, 17), (8, 25), (28, 25), (18, 31), (32, 8), (19, 33), (29, 33), (34, 37), (34, 19), (33, 37), (35, 40), (40, 24), (40, 50), (46, 40), (40, 40), (11, 43), (43, 47), (43, 26), (35, 46),...
<pre><code>data = [(3, 0), (3, 6), (9, 6), (9, 9), (13, 10), (13, 1), (16, 8), (12, 17), (20, 18), (10, 21), (24, 17), (8, 25), (28, 25), (18, 31), (32, 8), (19, 33), (29, 33), (34, 37), (34, 19), (33, 37), (35, 40), (40, 24), (40, 50), (46, 40), (40, 40), (11, 43), (43, 47), (43, 26), (35, 46), (42, 49), (52, 44), (46...
python|pandas|dataframe|tuples
2
369,870
68,075,343
Python - How to export monthly data into excel based on month?
<p>I have dataframe that contain two columns. Date from 2018 until now and Orders with order count for each day.</p> <pre><code>Date Orders 0 2018-01-01 57 1 2018-01-02 324 2 2018-01-03 54 3 2018-01-04 677 4 2018-01-05 234 5 2018-01-06 54 6 2018-01-07 234 7 2018-01-08 65 8 2018-01-09 234 9...
<p>You might want to have a look <a href="https://stackoverflow.com/a/59604826/12661819">here</a>. You can use simple integers to address the month, so you should be able to iterate like this (not tested):</p> <pre><code>for month in range(1, 13): df_per_month = df[df['Date'].dt.month == month] df_per_month.to_...
python|python-3.x|pandas
1
369,871
68,395,571
Pandas Series - force dtype in Series constructor
<p>I have this very simple series.</p> <pre><code>pd.Series(np.random.randn(10), dtype=np.int32) </code></pre> <p>I want to force a dtype, but pandas will overrule my initial setup:</p> <pre><code>Out[6]: 0 0.764638 1 -1.451616 2 -0.318875 3 -1.882215 4 1.995595 5 -0.497508 6 -1.004066 7 -1.641371 8 ...
<p>You can use this:</p> <pre><code>&gt;&gt;&gt; pd.Series(np.random.randn(10).astype(np.int32)) 0 0 1 1 2 1 3 1 4 0 5 0 6 -1 7 0 8 0 9 0 dtype: int32 </code></pre> <p>Pandas infers data type correctly. You can force your datatype with one exception. If your data is <code>float</code> and y...
python|pandas|series
1
369,872
68,060,507
Adding holidays column to pandas dataframe
<p>I have a pandas dataframe object <code>df</code> for the following dates:</p> <pre><code>&gt;&gt; df.index DatetimeIndex(['2015-01-01', '2015-01-02', '2015-01-03', '2015-01-04', '2015-01-05', '2015-01-06', '2015-01-07', '2015-01-08', '2015-01-09', '2015-01-10'], dtype='da...
<p>Try this solution using <code>lambda</code> function:</p> <pre><code>df['hols'] = pd.Series(df.index).apply(lambda x: holidays.CountryHoliday('AUS',prov='NSW').get(x)).values </code></pre> <p>Method <code>get()</code> should receive only one value, not entire index or array. Result when apply to Your data is:</p> <p...
python|pandas|dataframe
2
369,873
68,095,618
Importing JSON-like data into Python
<p>I have a file that is similar to JSON data but isn't formatted fully that I would like to parse into Pandas in Python. I could cycle through and manipulate the data until it's what I need it to be, but I wanted to see if there was a better solution than what I can think of.</p> <p>Sample file:</p> <pre><code>{&quot;...
<p>first remove end comma.use sed to replace comma and write to another file</p> <pre class="lang-sh prettyprint-override"><code>sed -r 's/\S*,\S*$//g' json_file &gt; data.jl </code></pre> <pre class="lang-py prettyprint-override"><code>#use lines True to read json line file. df = pd.read_json(&quot;data.jl&quot;,lines...
python|pandas
0
369,874
68,262,769
Getting the right values from the dictionary without duplication
<p>I am trying to match a random amount of employee records to an auditor. so I made a dictionary, the key being the name of the auditors and the values being the list of the employees' names. However, as the result of this, the dictionary values become cumulative and make duplicates of themselves as iteration for audi...
<p>To use the random sample method. create list of auditors and a list of employees.</p> <pre><code>emps = ['EMP_3201', 'EMP_4617', 'EMP_4332', 'EMP_3999', 'EMP_1386', 'EMP_3357', 'EMP_3584', 'EMP_4698', 'EMP_1484', 'EMP_4268', 'EMP_5368', 'EMP_1969', 'EMP_3398', 'EMP_1874'] auditors = ['auditor_A', 'auditor_B'...
python|python-3.x|pandas|dataframe
0
369,875
68,295,817
Optimal way to acquire percentiles of DataFrame rows
<h2>Problem</h2> <p>I have a <code>pandas</code> DataFrame <code>df</code>:</p> <pre><code>year val0 val1 val2 ... val98 val99 1983 -42.187 15.213 -32.185 12.887 -33.821 1984 39.213 -142.344 23.221 0...
<p>You can get use <code>.describe()</code> function like this:</p> <pre><code># Create Datarame df = pd.DataFrame(np.random.randn(5,3)) # .apply() the .describe() function with &quot;axis = 1&quot; rows df.apply(pd.DataFrame.describe, axis=1) </code></pre> <p>output:</p> <pre><code> count mean std m...
python|pandas|dataframe|percentile
3
369,876
68,444,606
Pandas groupby and count across multiple columns
<p>I have data ordered by ID, Year, and then a series of event flags indicating whether a thing did or did not happen for that ID in that year:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Year</th> <th>x</th> <th>y</th> <th>z</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>.groupby()</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumsum.html" rel="nofollow noreferrer"><code>.cumsum()...
python|pandas|dataframe|counter
0
369,877
68,284,953
How to add 1 to all numbers == to 0 in a pandas dataframe column python
<p>I am currently trying to calculate the length of disasters, measured in days, and then with this column that is the difference between the start date and end date, use groupby ( I think), in order to sum the length of disasters for each year, as my data set is from 1960 to present. Eventually, I'd like to also group...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.days.html" rel="nofollow noreferrer"><code>Series.dt.days</code></a> for convert tiemdeltas to integers and then use <code>replace</code>:</p> <pre><code>df_time['Disaster_Length'] = (df_time.Start_Date_A - df_time.End_Date_A).dt...
python|pandas
3
369,878
68,358,825
How to wright a function to work with dictionary type Serires and a column in Dataframe?
<p>I am trying to wright a function that works with Series and Dataframe.</p> <pre><code>dct= {10: 0.5, 20: 2, 30: 3,40:4} #Defining the function def funtion_dict(row,dict1): total_area=row['total_area'] if total_area.round(-1) in dict1: return dict1.get(total_area.round(-1))*total_area #checking ...
<p>This is the expected behavior because you are trying to use a &quot;Series&quot; as a lookup for a dictionary which is not allowed.</p> <p>From your code,</p> <pre><code>dct= {10: 0.5, 20: 2, 30: 3,40:4} df = pd.DataFrame({ 'total_area': [53, 14.8, 94, 77, 12], 'b': [5, 4, 3, 2, 1], 'c': ['X', 'Y', 'Y', ...
python-3.x|pandas|dataframe|dictionary|series
1
369,879
68,403,286
getting class layer error in Tensorflow model
<p>I am on the last step of training my model, and I am getting the further described error. How can I fix this? (this is an image classification model)</p> <pre class="lang-py prettyprint-override"><code>from tensorflow.python.keras.models import Sequential from tensorflow.python.keras.layers import GlobalMaxPooling2...
<p>I am able to execute code by changing imports as shown below</p> <pre><code>import tensorflow as tf print(tf.__version__) import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import GlobalMaxPooling2D, Dense, Flatten, GlobalAveragePooling2D image_size = 224 #Model definiti...
python|tensorflow|machine-learning|keras|image-classification
0
369,880
68,163,992
Refine duplicate selection with Pandas
<p>I have a dataframe with two columns 'text' and 'lang' and I need to extract the groups (unique) of 'text' values that have the same number N of languages. For example:</p> <p>For the following example dataframe:</p> <pre><code>text lang -------------- text_a en text_b es text_a es text_a it text_c de t...
<h3>Approach 1</h3> <p><code>Query</code> the dataframe to filter the rows where the corresponding language is one of <code>en</code>, <code>es</code>, then group the filtered dataframe on <code>text</code> and transform <code>lang</code> column using <code>nunique</code> to get the counts of unique values, now compare...
python|pandas
1
369,881
68,044,853
pandas readcsv ValueError: header must be integer or list of integers
<p>I'm a very beginning programmer. I've been trying to figure this out for a few days but can't seem to wrap my head around it.</p> <p>I am working with txt files (they are generated by another program). The columns contain no titles (headers?). Values are seperated by tabs.</p> <p>This is the base file:</p> <pre><cod...
<p>You have to replace <code>'none'</code> (a string) by <code>None</code> (object)</p> <pre><code>data = pandas.read_csv(&quot;q658.csv&quot;, sep= '\t', header=None) </code></pre> <p>Read this : <a href="https://docs.python.org/3/library/constants.html#None" rel="nofollow noreferrer">https://docs.python.org/3/library...
python|pandas
1
369,882
68,305,116
alternative way of filtering dataframe
<p>Community! It´s a long explanation but a 'simple' question! I have this following df:</p> <pre><code>d = {'name': ['john', 'mary', 'james'], 'area':[['IT', 'Resources', 'Admin'], ['Software', 'ITS', 'Programming'], ['Teaching', 'Research', 'KS']]} df = pd.DataFrame(data=d) </code></pre> <p><a href="https://i.stack.i...
<p>The problem is that you are returning the first element that is longer than 3. Try this:</p> <pre><code>def f(x): answer = [] for e in x: if len(e)&gt;3: answer.append(e) return answer </code></pre> <p>But even better, trying a more pythonic way:</p> <pre><code>def f(x): return [e...
python|pandas|function|loops
1
369,883
68,154,556
Printing months in the x axis with pyplot
<p>Data I'm working with: <a href="https://drive.google.com/file/d/1xb7icmocz-SD2Rkq4ykTZowxW0uFFhBl/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1xb7icmocz-SD2Rkq4ykTZowxW0uFFhBl/view?usp=sharing</a></p> <p>Hey everyone,</p> <p>I am a bit stuck with editing a plot. Basically, I would lik...
<h3>Option 1 (Most Similar Approach)</h3> <p>Change the index based on month abbreviations using <a href="https://pandas.pydata.org/docs/reference/api/pandas.Index.map.html" rel="nofollow noreferrer"><code>Index.map</code></a> and <a href="https://docs.python.org/3/library/calendar.html" rel="nofollow noreferrer"><code...
python|pandas|date|plot|series
1
369,884
68,371,165
Replace column values using a mapping-logic in pandas (problem with implementing a function)
<p>I have a dataframe as follows. What I would like is to generate another column (<code>freq</code>) where the rows will have values according to this logic:</p> <ul> <li><p>If <strong>Mode</strong> column value starts with a digit <code>m</code>, then fill-in digit <code>n</code> in the <strong>freq</strong> column.<...
<p>Is this what you are after?</p> <p>print(df1)</p> <pre><code> Mode 0 602 1 603 2 700 3 100 4 100 5 100 6 802 7 100 8 100 9 100 10 100 c=[df1['Mode'].astype(str).str.startswith('8'),df1['Mode'].astype(str).str.startswith('7'),df1['Mode'].astype(str).str.startswith('6'),df1['Mode...
python|pandas|dataframe|numpy|numpy-ndarray
1
369,885
68,050,242
How to multiply batches of image? N-D matrix multiplication of shape [batch, height, width] (dot product)
<p>Let us suppose I have a matrix with batch of 2 images or a matrix of 2 sentences where words are vectored for last dimension.</p> <p>image = <code>[batch, width, height, channel]</code></p> <p>words = <code>[batch, no of words in each sentence, vector length of each word]</code></p> <p>What is the best way to multip...
<p>If I get your question right, you want to reduce two tensors of fixed orders but arbitrary shapes that agree only in their first dimension (the batch dimension).</p> <p>The consistent way of doing so is the <a href="https://en.wikipedia.org/wiki/Einstein_notation" rel="nofollow noreferrer">Einstein summation notatio...
python|numpy|machine-learning|math|deep-learning
0
369,886
68,234,760
Find all groups of contiguous timestamp and assigns a unique id to each group in a data frame
<p>I want to write a function that assigns a unique ID to all groups of contiguous timeframe, where 'contiguous' means all the observation within the group are no more that 'max_time_gap' seconds apart.</p> <p>e.g: def assign_groups(df, max_time_gap, group_col_name):</p> <p>Where df is the input data as a pandas data f...
<p>You can do it this way:</p> <p><strong>1) Convert the column <code>timestamp</code> to datetime format if not already in that format</strong></p> <pre><code>df['timestamp'] = pd.to_datetime(df['timestamp']) </code></pre> <p><strong>2) Define the function as follows:</strong></p> <p>Use <a href="https://pandas.pydata...
python|pandas|datetime|pandas-groupby
1
369,887
68,261,345
Pandas drop and update rows and columns based on column value
<p>Here is sample csv file of cricket score:</p> <pre><code>&gt;&gt;&gt; df venue ball run extra wide noball 0 a 0.1 0 1 NaN NaN 1 a 0.2 4 0 NaN NaN 2 a 0.3 1 5 5.0 NaN 3 a 0.4 1 0 NaN NaN 4 a 0.5 1 1 NaN 1.0 5 a 0.6 2 1 NaN...
<p>Alrighty. This was a fun one.</p> <p>(I tried to add comments for clarity.)</p> <p><strong>Note</strong>: &quot;ball,&quot; &quot;run,&quot; &quot;extra,&quot; &quot;wide,&quot; and &quot;noball&quot; are all <em>numeric</em> fields.</p> <p><strong>Note</strong> <strong>Note</strong>: This all assumes your initial ...
python|pandas|dataframe|csv
1
369,888
68,283,274
python round numbers to specific value
<p>I would like to write a specif rounding logic.</p> <pre><code>number = x if x &lt; 950: # round number to and in steps of 50 elif x &lt; 9000: # round number to and in steps of 100 elif x &lt; 100000: # round number to and in steps of 250 else: # round number to and in steps of 1000 </code></pre> <p...
<p>Mostlikely not the cleanest way to do it but : <code>(x + step/2)//step*step</code> should work.</p> <p>Example : <code>print((880+25)//50*50)</code> returns <code>900</code>.</p>
python|numpy|math|rounding|ceil
3
369,889
68,080,345
ImportError: cannot import name 'LayerNormalization' from 'tensorflow.python.keras.layers.no rmalization'
<p>In running a python project I get the following error. I installed various versions of tensorflow (from 2.2.3 to 2.4.1), but the problem is there... I don't know what I should change or what is the mismatch. It previously was working... please help if you know tensroflow</p> <pre><code>File &quot;/home/pouramini/seq...
<p>I uninstalled <code>tensorflow</code> both by <code>conda remove tensorflow</code> and <code>pip uninstall tensorflow</code> and even removed the folder manually from <code>miniconda3/lib/python3.7/site-packages/</code></p> <p>Then installed tensorflow (I tried 2.3.0) by <code>pip install tensorflow==2.3.0</code></p...
python|python-3.x|tensorflow|keras
1
369,890
68,298,877
parse datetime which stores ms.us
<p>I am attempting to parse some logfiles stored from a piece of test equipment (CANbus logger) Within the exported TSV file they unfortunately store the absolute time in a <code>HH:MM:SS.XXX.YYY</code> format</p> <p>where <strong>XXX is in ms</strong> and <strong>YYY is in µs</strong> eg: <code>13:58.06.286.591</code>...
<p>you can write a simple formatter that removes the rightmost dot, so you can parse with <code>%f</code>.</p> <p><em><strong>Ex:</strong></em></p> <pre><code>formatter = lambda x: x[::-1].replace('.', '', 1)[::-1] s = &quot;13:58.06.286.591&quot; print(formatter(s)) # 13:58.06.286591 </code></pre> <p>Now you could i...
python|numpy|datetime
1
369,891
68,040,059
Conditionally Create Temp Table in SQL from Python
<p>In a large set of queries, I'm trying to create a temp table in SQL, if it doesn't already exist. Obviously, you could remove the 2nd <code>CREATE TABLE</code> statement. However, the queries I'm building are dynamic and may, or may not, have the 1st <code>CREATE TABLE</code> statement present.</p> <p>I can get th...
<p>This is a batch compilation error. When you remove the <code>GO</code>, which you must to to get this to compile, then there are two <code>CREATE TABLE</code> statements for the same temp table, which won't parse and compile. EG this batch generates the same error:</p> <pre><code>CREATE TABLE #temp_sample (id int)...
python|sql|pandas|odbc|temp-tables
0
369,892
68,191,448
Unknown image file format. One of JPEG, PNG, GIF, BMP required
<p>I built a simple CNN model and it raised below errors:</p> <pre><code>Epoch 1/10 235/235 [==============================] - ETA: 0s - loss: 540.2643 - accuracy: 0.4358 --------------------------------------------------------------------------- InvalidArgumentError Traceback (most recent call las...
<p>Some of your files in the validation folder are not in the format accepted by Tensorflow ( <code>JPEG, PNG, GIF, BMP</code>), or may be corrupted. The extension of a file is indicative only, and does not enforce anything on the content of the file.</p> <p>You might be able to find the culprit using the <a href="http...
python|tensorflow
10
369,893
68,381,803
Cumulative sum but conditionally excluding earlier rows
<p>I have a DataFrame like this:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({ 'val_a': [3, 3, 3, 2, 2, 2, 1, 1, 1], 'val_b': [3, np.nan, 2, 2, 2, 0, 1, np.nan, 0], 'quantity': [1, 4, 2, 8, 5, 7, 1, 4, 2] }) </code></pre> <p>It looks like this:</p> <pre><code>| | val_a | val_b | ...
<p>With the help of NumPy:</p> <pre><code># sum without conditions raw_sum = df.groupby(&quot;val_a&quot;, sort=False).quantity.sum().cumsum() # comparing each `val_b` against each unique `val_a` via `gt.outer` sub_mask = np.greater.outer(df.val_b.to_numpy(), df.val_a.unique()) # selecting values to subtract from `qu...
python|pandas|dataframe
2
369,894
68,380,947
Get all rows that have a column "Message" where at least one of the words is in Array
<p>Consider the code:</p> <pre><code>df = pd.read_csv('...csv') array = [.....,....,....] results = df[df.Message.isin(array).fillna(False)] </code></pre> <p>The column <code>Message</code> contains more than one word.</p> <p>How can we get all rows that have the column &quot;Message&quot; where at least one of the wor...
<p>Maybe something like this (in a single line without loops):</p> <pre><code>import pandas as pd data = [['Client','Message','City','Phone'], ['Jackson','I will back soon','Rome',1111], ['Cole','Please try to be patient','Cairo',2222 ], ['Rains','Sure anything you want , anything','Paris',3333 ]] Array = ['try', 'a...
python|python-3.x|pandas|string|dataframe
1
369,895
68,141,489
Failed to convert a NumPy array to a Tensor (Unsupported object type dict)
<p>my method i thought that the problem from it is</p> <pre><code> history = model.fit_generator(train_generator, epochs=epochs, steps_per_epoch=train_steps, verbose=1, callbacks=[checkpoint], validation_data=val_generator, validation_steps=val_steps) def data_generator(descriptions, photos, tokenizer, max_length, img...
<p><strong>This error indicates some values or all values in your data does not have a valid data type to convert.</strong></p> <hr /> <p><strong>Reason</strong>:</p> <p>Common reason for this error is that values of the array are not of given dtype in graph mode. It may be because some values are <code>NaN</code> or <...
python|tensorflow|keras|lstm|tensor
0
369,896
68,332,561
Filtering a pandas data frame
<p>Suppose we have a pandas data frame <code> df </code> with a column <code> id </code> with about 5 rows. In the following code below, why do I still get the length of the filtered data frame to be 5:</p> <pre><code>import pickle import gzip import bz2 import pandas as pd import os import _pickle as cPickle import bz...
<p>I figured it out. The filtered data frame would have the same dimensions as the original one because they are equal. If I had put a different id, then the dimension of the filtered data frame would have been different.</p>
python|pandas
0
369,897
68,314,841
Teradata - An illegally formed character string was encountered during translation
<p>I am fetching tweets via Twitter API in pandas dataframe and writing the data to teradata database. However, unlike other tweets one cell has specific tweet which contains data in bold. When I try to insert it in database, it pops up the following error:</p> <pre><code>OperationalError: [Version 17.0.0.4] [Session 3...
<p>To store or retrieve arbitrary Unicode code points, use the Unicode Pass-Through feature both for loading and querying sessions.</p> <pre><code>SET SESSION CHARACTER SET UNICODE PASS THROUGH ON; </code></pre> <p>For the specific example given, you might find it useful to &quot;normalize&quot; the Unicode text, e.g. ...
python|pandas|twitter|teradata|twitterapi-python
1
369,898
68,122,925
Subtraction of matrices with different dimensions based on the index
<p>I have an array where each element of the array is an array of points given by pairs of coordinates.</p> <p>For example:</p> <pre><code>x = array([[[1, 2], [3, 4]], [[22, 4], [ 9, 10]]]) </code></pre> <p>On the other hand I have a list whose length matches the first dimension of the previous matrix where e...
<p>Your original example has a 2 element array:</p> <pre><code>In [294]: x = np.array([np.array([[1, 2], ...: [3, 4]]), ...: np.array([[22, 4], ...: [ 9, 10], ...: [ 3, 2]])], dtype=object) ...: In [295]: x.shape Out[295]: (2,) In [296]: y = [[1,2],[7,8]] In [297]: len(y) Out[297...
python|numpy
0
369,899
68,393,758
How to shift numpy slices?
<p>I have a class like this</p> <pre class="lang-py prettyprint-override"><code>class A: def __init__(self): self.top_left = (1,2) self.arr = np.reshape(np.arange(100), (10,10)) def __setitem__(self, key, val): return self.arr[shifted(key, self.top_left)] = val </code></pre> <p>I want al...
<p>Numpy array operate on builtin python <code>slice</code> or <code>tuple</code>.</p> <p><code>shifter</code> function decides what kind of index you passed.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np class A: def __init__(self): self.top_left = (1,2) self.arr = np.resh...
python|numpy
0