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
359,900
56,223,953
Issue with understanding numpy array slicing
<p>When slicing a Numpy array, it looks inconsistent to me.</p> <pre class="lang-py prettyprint-override"><code>In[87]: y Out[87]: array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) In[88]: y[0,0] Out[88]: 1 </code></pre> <p><code>y[0,0]</code> is <code>1</code>. That's OK, but when I type</p> <pre class="lang...
<p>Numpy uses the same slicing notation as Python does, i.e. <code>[start:stop:step]</code>.</p> <p>As a convention, the value at index <code>stop</code> is excluded from the resulting sequence.</p> <p>You can find more information at paragraph 3 of <a href="https://machinelearningmastery.com/index-slice-reshape-nump...
python|arrays|numpy|matrix-indexing
0
359,901
56,357,758
Is there a SciPy method to autocrop an image, i. e. trim zeros from a 2d `numpy.ndarray`?
<p>For 1d <code>numpy.ndarray</code> there is <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.trim_zeros.html" rel="nofollow noreferrer"><code>numpy.trim_zeros</code></a>. Which method from <code>numpy</code> or <code>scipy</code> can I use to trim zeros for 2d arrays?</p> <pre><code>&gt;&gt...
<p>You can try a list comprehension with some <code>numpy</code> methods:</p> <pre><code>&gt;&gt;&gt; np.array([sub[~(sub == 0)].tolist() for sub in a if sub[sub != 0].tolist()]) array([[4, 1, 2], [3, 6]], dtype=object) &gt;&gt;&gt; </code></pre>
python|numpy|scipy|crop|trim
2
359,902
56,044,793
How to generate a 3D grid of vectors ? (each position in the 3D grid is a vector)
<p>I want to generate a four dimensional array with dimensions (dim,N,N,N). The first component ndim =3 and N corresponds to the grid length. How can one elegantly generate such an array using python ? </p> <p>here is my 'ugly' implementation:</p> <pre><code>qvec=np.zeros([ndim,N,N,N]) freq = np.arange(-(N-1)/2....
<p>Your implementation looks good enough to me. However, here are some improvements to make it prettier:</p> <pre><code>qvec=np.empty([ndim,N,N,N]) freq = np.arange(-(N-1)/2.,+(N+1)/2.) x, y, z = np.meshgrid(*[freq]*ndim, indexing='ij') qvec[0,...]=x # qvec[0] = x qvec[1,...]=y # qvec[1] = y qvec[2,...]=z ...
python|numpy|vector|grid|numpy-ndarray
0
359,903
56,256,739
Reshape arrays in Python
<p>I need to reshape two arrays into a certain shape</p> <pre class="lang-py prettyprint-override"><code>import numpy as np x = np.array([(1, 2, 3, 4, 5), (6, 7, 8, 9)]) y = np.array([(10, 11, 12, 13, 14), (15, 16, 17, 18)]) </code></pre> <p>I already used np.column_stack(x,y)</p> <pre class="lang-py prettyprint-ove...
<p>Given that you have an array of <code>tuples</code>, what you could do is add them along the first axis:</p> <pre><code>np.sum([x,y], axis=0)[:,None] [[(1, 2, 3, 4, 5, 10, 11, 12, 13, 14)] [(6, 7, 8, 9, 15, 16, 17, 18)]] </code></pre>
python|arrays|numpy
1
359,904
56,099,492
Pandas: How to avoid nested for loop
<p>I have some code that compares actual data to target data, where the actual data lives in one DataFrame and the target in another. I need to look up the target, bring it into the df with the actual data, and then compare the two. In the simplified example below, I have a set of products and a set of locations all wi...
<p>If the target dataframe is guaranteed to have unique locations, you can use a join to make this process really quick.</p> <pre><code>import pandas as pd import numpy as np import time employee_list = ['Joe', 'Bernie', 'Elizabeth', 'Kamala', 'Cory', 'Pete', 'Amy', 'Andrew', 'Beto', 'Jay', 'Kristen'...
python|pandas
1
359,905
56,217,550
Data frame loop stops
<p>I'm trying to loop through a data frame with with conditional statements.</p> <p>I have attempted splitting up the loop and they all work individually; however, when combined, the loop stops after 1 iteration. </p> <pre><code>i=0 stock = 100 cash = 0 for index, row in df2.iterrows(): if df2.iloc[i][3] &gt; ...
<p>Because your print i outside of your <code>for</code> loop you will not get a list of numbers but only the last value of <code>i</code></p> <p>Also maybe it's a copy/paste error but you have an indent before <code>stock = round((cash/df2.iloc[i][3])-0.5)</code> to much.</p> <p>Can you give an example on what is in...
python|pandas|dataframe
0
359,906
56,337,848
Cannot change number of clusters in KMeansClustering Tensorflow
<p>I found this code and it works perfectly. THe idea - split my data and train KMeansClustering on it. So I create InitHook and iterator and use it for training.</p> <pre><code>class _IteratorInitHook(tf.train.SessionRunHook): """Hook to initialize data iterator after session is created.""" def __init__(self...
<p>I found the problem: as you can see I save codebook to <code>parameters/clusters</code>. When it have created tensorflow save graph here too. So default behaviour for tensorflow - DO NOT CREATE new graph if it already exist!</p> <p>So every time I tried to run <code>KMeansClustering</code> it still use graph, loade...
python|tensorflow|batch-processing|k-means
0
359,907
56,032,848
Why does Matlab interp1 produce different results than numpy interp?
<p><strong>EDIT:</strong> Code edited to produce results consistent with Matlab. See below.</p> <p>I am converting Matlab scripts to Python and the linear interpolation results are different in certain cases. I wonder why and if there is any way to fix this?</p> <p>Here is the code example in both Matlab and Python a...
<p>It appears as if Matlab includes an additional equality check in it's interpolation.</p> <p>Linear 1-D interpolation is generally done by finding two x values which span the input value <code>x</code> and then calculating the result as:</p> <pre><code>y = y1 + (y2-y1)*(x-x1)/(x2-x1) </code></pre> <p>If you pass i...
python|matlab|numpy|interpolation
1
359,908
56,271,080
Array won't assign more than 8 characters in python
<p>Array is acting weirdly, I have this code:</p> <pre><code>a=np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt']) </code></pre> <p>And I did this:</p> <pre><code>a[0]="hello there my friend" </code></pre> <p>Result was:</p> <pre><code>array(['hello th', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt...
<p>Change it by using <code>dtype</code> parameter to a very big number (e.g. <code>100</code>):</p> <pre><code>&gt;&gt;&gt; a=np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'],dtype='&lt;U100') &gt;&gt;&gt; a[0] = "hello there my friend" &gt;&gt;&gt; a array(['hello there my friend', 'gulf', 'egypt'...
python|arrays|numpy|numpy-ndarray
1
359,909
56,240,508
storing numpy object array of equal-size ndarrays to a .mat file using scipy.io.savemat
<p>I am trying to create .mat data files using python. The matlab code expects the data to have a certain format, where two-dimensional ndarrays of non-uniform sizes are stored as objects in a column vector. So, in my case, there would be k numpy arrays of shape (m_i, n) - with different m_i for each array - stored in ...
<p>I'm not quite clear about the problem. Let me try to recreate your case:</p> <pre><code>In [58]: from scipy.io import loadmat, savemat In [59]: A = np.empty((2,1), object) In [61]: A[0,0]=np.arange(4).reshape(2,2) In [62]: A[1,0]=np.arange(6)....
python|arrays|matlab|numpy|scipy
0
359,910
56,285,042
Write dataframe to csv
<p>I have a problem to save the printed datum. In below picture, all of data was calculated, and I tried to save the results to CSV file. However, only the last line was saved. In this case, what shall I do? Do I have to use the loop method? Could give me some hints or solutions?</p> <pre><code>r = 2 while r &lt; 5:...
<p>How are there multiple lines? Perhaps this is due to your console having line-wrapping but not your text editor.</p>
python|pandas|numpy
0
359,911
55,629,790
How does this regularization code affect loss?
<p>I have seen some learning with convolution neural network code. I do not understand the next part of this code.</p> <pre class="lang-py prettyprint-override"><code>loss = tf.reduce_sum(tf.nn.l2_loss(tf.subtract(train_output, train_gt))) for w in weights: loss += tf.nn.l2_loss(w)*1e-4 </code></pre> <p>T...
<p>This is the formula that you have:</p> <p><a href="https://i.stack.imgur.com/Qzxme.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qzxme.png" alt="enter image description here"></a></p> <ol> <li><code>tf.subtract(train_output, train_gt)</code> does element-wise subtraction between two tensors <c...
python|tensorflow|deep-learning|regularized
2
359,912
55,808,539
Transfer values between 2 dataframes based on time granularity
<p>I have one dataframe, <code>df_60</code> that is of 60 minute time granularity. And another with 30 minute granularity, <code>df_30</code>. I want to move the values from a column on <code>df_60</code> to a column in <code>df_30</code>, and maintain the duration of when the value appears. </p> <p>So say I had a dat...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.reindex.html" rel="nofollow noreferrer"><code>Series.reindex</code></a> with <code>ffill</code>:</p> <pre><code>df = df_60.reindex(df_30.index, method='ffill') print (df) val 2011-01-05 00:00:00 0 2011-01-05...
pandas|python-2.7|datetime
2
359,913
55,647,248
merging two pandas dataframes where new column is created
<p>I have two python dataframes: One df which contains information on sites where some survey has occured:</p> <pre><code>sites = pd.DataFrame(np.array([['A1', 2, 3], ['B3', 5, 6], ['B5', 8, 9]]), columns=['Site_ID', 'SomeVal1', 'SomeVal2']) sites.set_index('Site_ID') </code></pre> <p>A second df wit...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>DataFrame.pivot</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.add_prefix.html" rel="nofollow noreferrer"><code>DataFrame.add_prefix...
python|pandas|dataframe|merge
0
359,914
55,601,155
Tensorflow: Sigmoid cross entropy loss does not force network outputs to be 0 or 1
<p>I would like to learn image segmentation in TensorFlow with values in {0.0,1.0}. I have two images, <code>ground_truth</code> and <code>prediction</code> and each have shape <code>(120,160)</code>. The <code>ground_truth</code> image pixels only contain values that are either 0.0 or 1.0.</p> <p>The prediction image...
<p>Solved it. The problem was that the <code>tf.nn.sigmoid_cross_entropy_with_logits</code> runs the logits through a sigmoid which is of course not used at validation time since the loss operation is only called during train time. The solution therefore is:</p> <p>make sure to run the network outputs through a <code>...
python|tensorflow|image-segmentation|loss-function
3
359,915
55,928,354
Pandas - DateTime groupby to structured dict
<p>I have a dataset which contains a DateTime field. I need to group by <code>hours</code> and dispatch each group to a dictionary with the following structure:</p> <pre><code>{year_1: {month_1: {week_1: {day_1: {hour_1: df_1, hour_2: df_2} } }, {...
<p>You need <a href="https://docs.python.org/3/library/stdtypes.html#dict.setdefault" rel="nofollow noreferrer"><code>dict.setdefault</code></a></p> <pre><code>result = {} for to_unpack, df_hour in df.groupby(['year','month','day','week','hour']): year, month, week, day, hour = to_unpack result.setdefault(yea...
python|pandas
4
359,916
55,643,217
What is the cleanest way to create a new column based on a conditional of an existing column?
<p>In pandas I currently have a data frame containing a column of strings: {Urban, Suburban, Rural}. The column I would like to create is conditional of the first column (i.e. Urban, Suburban, Rural are associated with the corresponding colors) {Coral, Skyblue, Gold}</p> <p>I tried copying the first column and then us...
<p>You can do </p> <pre><code> merge_table['New col']=merge_table["color"].replace({'Urban': 'Coral', 'Suburban': 'Skyblue', 'Rural': 'Gold'}) </code></pre>
pandas|calculated-columns
1
359,917
55,779,554
Reindexing missing dates in pandas but receiving NaN values
<p>In pandas, I'm creating a dataframe like:</p> <pre><code> df = pd.read_csv(file_path)[['timestamp', 'close']] df['close'] = df['close'].astype(float) df = df.set_index('timestamp') </code></pre> <p>The data looks like:</p> <pre><code> close timestamp 2019-04-18 ...
<p>Your index should not be datetime format , if you just using read_csv and does not pass <code>parse_dates</code> </p> <pre><code>df = df.set_index('timestamp') df.index=pd.to_datetime(df.index) </code></pre> <p>After convert it , you should be fine with <code>reindex</code></p> <hr> <p>Another solution will be ...
python|pandas
2
359,918
55,677,222
omit groups in pandas groupby based on a condition
<p>This is my dataframe:</p> <pre><code>df = pd.DataFrame({'sym': list('aaaaaabb'), 'key': [1, 1, 1, 1, 2, 2, 3, 3], 'x': [100, 100, 90, 100, 500, 500, 700, 700]}) </code></pre> <p>I group them by <code>key</code> and <code>sym</code>:</p> <pre><code>groups = df.groupby(['key', 'sym']) </code></pre> <p>Now I want t...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.SeriesGroupBy.nunique.html" rel="nofollow norefer...
python|pandas
3
359,919
55,641,125
Minimum required hardware component to install tensorflow-gpu in python
<p>I'm tried many PC with different hardware capability to install tensorflow on gpu, they are either un-compatible or compatible but stuck in some point. I would like to know the minimum hardware required to install tensorflow-gpu. And also I would like to ask about some hardware, Is they are allowed or not: Can I use...
<p>TensorFlow (TF) GPU 1.6 and above requires cuda compute capability (ccc) of 3.5 or higher and requires AVX instruction support.<br> <a href="https://www.tensorflow.org/install/gpu#hardware_requirements" rel="nofollow noreferrer">https://www.tensorflow.org/install/gpu#hardware_requirements</a>. <a href="https://www.t...
python|tensorflow|gpu|cpu
3
359,920
55,616,994
Pandas: How to read a DataFrame from excel-file where multiple rows are sometimes separated by line break (\n)
<p>I am trying to read some excel files in pandas. In some files, the table of interest is not perfectly formatted, i.e. multiple rows are formatted as a single row but each such row has multiple lines. So the data appears fine when you view the excel file. Also when parsing it using pandas, there is indeed a newline c...
<p>After <code>split</code> you can check with <a href="https://stackoverflow.com/questions/53218931/how-do-i-unnest-explode-a-column-in-a-pandas-dataframe/53218939#53218939">unnesting</a></p> <pre><code>yourdf=unnesting(df.apply(lambda x : x.str.split(r'\\n')),['Name','Price']) yourdf Out[50]: Name ...
python|excel|pandas|dataframe|parsing
5
359,921
55,955,280
How to combine connected strings within pandas groupby
<p>I'm trying to figure out how to count a given combination of 2 strings regardless of which string is first / second. </p> <p>Here is my code:</p> <pre><code>import pandas as pd mylist = [[('Smith JR', 'Kim YY'), ('Smith JR', 'Ron AA'), ('Kim YY', 'Ron AA')], [('Kim YY', 'Smith JR')], [('Smith JR', 'Ron...
<p>Sort the two columns together before adding to the dataframe so that you are guaranteed that a pair will only appear in a certain order. Only then apply your counting method. Using the method from <a href="https://stackoverflow.com/questions/51182228/python-delete-duplicates-in-a-dataframe-based-on-two-columns-combi...
python|pandas|pandas-groupby
5
359,922
55,917,803
Renaming column values in Pandas in alphabetical order
<p>I have a large data set with a column that contains personal names, totally there are 60 names by <code>value_counts()</code>. I don't want to show those names when I analyze the data, instead I want to rename them to <i>participant_1, ... ,participant_60</i>. </p> <p>I also want to rename the values in alphabetica...
<p>If need replace values in column in alphabetical order use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Categorical.codes.html" rel="nofollow noreferrer"><code>Categorical.codes</code></a>:</p> <pre><code>df = pd.DataFrame({ 'names':list('bcdada'), }) df['new'] = [f"participan...
python|pandas
3
359,923
55,715,009
I am trying to convert deeply nested JSON into pandas dataframe
<p>I am trying to convert a json returned from the API call into pandas dataframe. Ideally I would like to extract only 'Type','Name' and 'SUPPLY'.</p> <p>I have tried multiple things, such as <code>flatten()</code>, <code>json_normalize()</code> and so on, but couldn't make it to work.</p> <pre><code>def get_cryptoc...
<p><a href="https://github.com/jmespath/jmespath.py" rel="nofollow noreferrer">Jmespath</a> could help here with nested paths - basic summary is if u encounter a list, represent it with a bracket(<code>[]</code>), if it is a key, access it wih dot notation (<code>.</code>) : </p> <pre><code>import requests url = "http...
python|json|pandas
1
359,924
55,682,718
module 'tensorflow._api.v2.train' has no attribute 'GradientDescentOptimizer'
<p>I used Python 3.7.3 and installed tensorflow 2.0.0-alpha0,But there are some problems。such as module 'tensorflow._api.v2.train' has no attribute 'GradientDescentOptimizer' Here's all my code</p> <pre><code>import tensorflow as tf import numpy as np x_data=np.random.rand(1,10).astype(np.float32) y_data=x_data*0....
<p>You are using Tensorflow 2.0. The following code will be helpful:</p> <pre><code>import tensorflow.compat.v1 as tf tf.disable_v2_behavior() </code></pre>
python|tensorflow
18
359,925
55,979,324
how to construct Time based EWMA
<p>I am calculating the time-based EWMA, as defined:</p> <p><img src="https://latex.codecogs.com/gif.latex?%5Cinline&space;%5Cmu_%7Bn&plus;1%7D&space;=&space;c_%7Bn&plus;1%7D&space;%5Ccdot&space;%5Cmu_n&space;&plus;&space;(1-c_%7Bn&plus;1%7D)%5Ccdot&space;x_%7Bn&plus;1%7D" title="\mu_{n+1} = c_{n+1} \cdot \mu_n + (1-c...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shift.html" rel="nofollow noreferrer">shift()</a></p> <p>Essentially you need time[x] and time[x-1] to solve your problem, if I'm reading this right. </p> <p>Simply create a new column: </p> <pre><code>df['time_prev'] = df['t...
python-3.x|pandas|moving-average
0
359,926
55,643,864
How to cast only few columns in a pandas dataframe
<p>I have a dataframe of 39 columns. I need to cast the type to int of the columns from 5(name=1980) to 39(2013). how do i do that?</p> <p>d[1980:2013].astype(int) <a href="https://i.stack.imgur.com/Qo0ih.png" rel="nofollow noreferrer">dataframe</a></p>
<p>df.loc[:,1980:2013].astype(int)</p>
python|pandas
1
359,927
55,986,614
Rounding/formatting decimals using pandas, reading from columns of a csv file
<p>Need to read a csv file and have it output the min, max, range, and standard deviation for each of the 3 columns in the file. This isn't the problem I'm having. What I'm having trouble with is something that I feel like should be relatively simple, getting the outputs to round to 2 decimal places. While it's not rea...
<p>Here you are trying to format the output for the print function, not actually the dataframe values.</p> <p>So, you can format the output like this:</p> <pre><code>print("%.2f" % df.Ease.min()) </code></pre> <p>the <code>"%.2f"</code> indicates you want to print 2 digits after the dot for a float type value</p>
pandas|csv|formatting|rounding
0
359,928
55,886,235
How to use the pandas Series.interpolate to insert data into NAN
<p>I have some data, some of them have Nan. The problem is I can't insert data into Nan when it is at top or bottom area by using pandas.Series.interpolate, even by method od fillna. I want to know if there is any better to replace NAN by the proper data? Here is the problem as below shown by photo: <a href="https://i....
<p>Set <code>limit_direction</code> to <code>"both"</code>.</p> <p>Demo data</p> <pre><code>data = pd.Series([None,1,None,5,None]) print(data) 0 NaN 1 1.0 2 NaN 3 5.0 4 NaN dtype: float64 </code></pre> <p>Result</p> <pre><code>data.interpolate(limit_direction="both") 0 1.0 1 1.0 2 3.0 3 ...
python|pandas
0
359,929
55,866,348
Where do the parameters in keras layers apply?
<p>I'm trying to get to grips with the basics of neural networks and am struggling to understand keras layers. </p> <p>Take the following code from tensorflow's tutorials:</p> <pre><code>model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation=tf.nn.relu), ...
<p>Basically you have two types of API in Keras: Sequential and Functional API <a href="https://keras.io/getting-started/sequential-model-guide/" rel="nofollow noreferrer">https://keras.io/getting-started/sequential-model-guide/</a></p> <p>In Sequential API, you don't explictly refers an <strong>Input Layer</strong> <...
python|tensorflow|keras|keras-layer|tf.keras
0
359,930
55,934,033
Use a different dataframe to replace value of text in dataframe
<p>I have a simple dataframe (df1) where I am replacing values with the replace function (see below). Instead of always having to change the names of the items I want to replace in the code, I would like this to be done from an excel sheet, where either the columns or rows give the different names that should be replac...
<p>Use:</p> <pre><code>df2 = pd.DataFrame({'Tartlet':['Tart', 'Tart2', 'Cookie'], 'Sandwich': ['Ham and Cheese Sandwich', 'Chicken Focaccia', 'another']}) #swap key values in dict #http://stackoverflow.com/a/31674731/2901002 d1 = {k: oldk for oldk, oldv in df2.items() for k in oldv} print (d1) {'T...
python|python-3.x|pandas|dataframe
1
359,931
55,868,472
How to combine strings in one DataFrame
<p>I am processing inbound user data. I receive <code>DataFrame</code> <code>h</code> that is supposed to contain all <code>float</code> but has some strings:</p> <pre><code>&gt;&gt;&gt; h = pd.DataFrame(np.random.rand(3, 2), columns=['a', 'b']) &gt;&gt;&gt; h.loc[0, 'a'] = 'bad' &gt;&gt;&gt; h.loc[1, 'b'] = 'robot' &...
<p>You can convert non necessary values to <code>NaN</code>s by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html" rel="noreferrer"><code>DataFrame.where</code></a>, join together with <code>string</code>s and last replace original values:</p> <pre><code>m = hh.isna() df = ...
python|python-3.x|pandas|dataframe
5
359,932
55,941,034
Getting the count of items under diagonal in numpy
<p>I have a correlation matrix, and I want to get the count of number of items below the diagonal. Preferably in numpy.</p> <pre><code>[[1, 0, 0, 0, 0], [.35, 1, 0, 0, 0], [.42, .31, 1, 0, 0], [.25, .38, .41, 1, 0], [.21, .36, .46, .31, 1]] </code></pre> <p>I want it to return 10. Or, to return...
<p><strong><em>Setup</em></strong></p> <pre><code>a = np.array([[1. , 0. , 0. , 0. , 0. ], [0.35, 1. , 0. , 0. , 0. ], [0.42, 0.31, 1. , 0. , 0. ], [0.25, 0.38, 0.41, 1. , 0. ], [0.21, 0.36, 0.46, 0.31, 1. ]]) </code></pre> <hr> <p><a href="https...
numpy|mean|diagonal
2
359,933
55,831,642
Assign singleton array to element of array with Numba
<p>I am trying to assign a singleton array to a specific element in a Numpy array using Numba's <code>nopython</code> mode but I get a <code>TypeError</code> and I can't figure out why. It works just fine without Numba. My MCVE is below.</p> <pre><code>import numpy as np from numba import jit @jit(nopython=True) def...
<blockquote> <p>It works just fine without Numba</p> </blockquote> <p>Yes, but numba is about making trade-offs. You sacrifice some options and convenience for speed.</p> <blockquote> <p>I can't figure out why.</p> </blockquote> <p>Because (currently) there's no conversion (or overload) that supports setting a s...
python|numpy|error-handling|runtime-error|numba
1
359,934
56,000,098
About locally weighted linear regression problem
<p>One problem with linear regression is that it tends to underfit the data and one way to solve this problem is a technique known as locally weighted linear regression. I have read about this technique in <a href="http://cs229.stanford.edu/notes/cs229-notes1.pdf" rel="nofollow noreferrer">CS229 Lecture notes by Andrew...
<p>In the loop, <code>i</code> is a list, e.g. <code>[1.0, 1.0]</code>. You need to decide what value to take from the list to multiply <code>slope*i</code>. For instance:</p> <pre><code>best_fit = [] for i in xArr: best_fit.append(slope*i[0]+y_intercept) </code></pre> <p>The first element in the list seems to al...
python|tensorflow|machine-learning
0
359,935
55,917,564
Is there a more efficient way to convert a multiple line of string to a numpy array?
<p>I am converting a multiple line of string to an numpy array, like this:</p> <pre><code>names = """ 1 2 1 1 1 0 0 1 1 """ names_list = names.splitlines() tem = [] for i in [row for row in names_list if row]: tem.append([col for col in list(i) if col != ' ']) np.array(tem, dtype=np.int) </code></pre> <p>This pi...
<p>One answer was flagged as being low quality for not explaining itself. But none of the other three do that, and they are just replicas of each other.</p> <pre><code>In [227]: names = """ ...: 1 2 1 ...: 1 1 0 ...: 0 1 1 ...: """ In [238]: np.genfromtxt(StringIO(names), dtype=int) ...
python|numpy
3
359,936
55,594,969
How to visualise filters in a CNN with PyTorch
<p>I'm new to deep learning and Pytorch. I want to visual my filter in my CNN model so that I can iterate layer in the CNN model that I define. But I meet error like below.</p> <p><strong>error: 'CNN' object is not iterable</strong></p> <p>The CNN object is my model.</p> <p>My iteration code is like below:</p> <pre><co...
<p>Essentially, you will need to access the features in your model and transpose those matrices into the right shape first, then you can visualise the filters</p> <pre class="lang-py prettyprint-override"><code> import numpy as np import matplotlib.pyplot as plt from torchvision import utils def visTen...
deep-learning|pytorch
12
359,937
55,876,049
How to correct error when saving dask dataframe to csv?
<p>I keep getting an error when I try and save a dask dataframe to csv. In short, I have a pandas df that is made up of 10 columns and 20 rows, and then I loaded a dask df that is 350 columns and 6+ million rows (~6GB). I needed to do a rather simple left join onto the pandas df. After doing that join, I look at the da...
<p>You're passing dtype=str, but I think that perhaps you should pass dtype=object, which is what Pandas uses to represent really any non-numeric data.</p> <p>The dask.dataframe.read_csv function is giving you an error message encouraging you to use dtype=object. It's actually giving you the full <code>dtype={...}</c...
python|pandas|dataframe|dask
1
359,938
55,922,162
Recommended cudf Dataframe Construction
<p>I'm interested in recommended and fast ways of creating cudf DataFrames from dense numpy objects. I have seen many examples of splitting out columns of a 2d numpy matrix to tuples then calling <code>cudf.DataFrame</code> on a list of tuples -- this is rather expensive. Using <code>numba.cuda.to_device</code> is qu...
<p><code>cudf.DataFrame</code> is a dedicated columnar format and performs best with data that is very tall instead of wide. However, we have some important zero-copy functions that allow you to move data between <code>numba/cupy/cudf</code> inexpensively. At this point in time, as far as I know, the best way to get a ...
python|numpy|rapids|cudf
1
359,939
55,940,018
How to create time series plot with a timestamp format: MM/DD/YYYY HH:MM
<p>I have a decently sized table that I'm reading from a .csv file. I would like to create a time plot of the values.</p> <pre><code>file = 'test.csv' names = ['id', 'siteid', 'machineid', 'tag', 'value', 'ts', 'year', 'month', 'day', 'min', 'max', 'avg', 'std'] dataset = pandas.read_csv(file) dataset.columns = names ...
<p>I guess you already have solved the problem with the data format and struggling to plot the "value" column against the "ts" column. If I have interpreted your problem wrong then I am sorry. To plot two columns in pandas dataframe (I hope you are using pandas dataframe) you can use the following code snippet: </p> <...
python-3.x|pandas|matplotlib|data-science
0
359,940
55,796,455
Why Inception V3 retrained using tensorflow and keras on same dataset shows different accuracy?
<p>I am trying to retrain Inception V3 pretrained on ImageNet dataset. </p> <p>******* Keras (Using Tensorflow backend ) ************</p> <p>I have retrained <strong>Inception V3 using Keras</strong>(tensorflow backend) with following code : </p> <pre><code># SETUP MODEL CLASSES = 3 base_model = InceptionV3(weights=...
<p>There are tons of reasons you might see differences. I think the more important part is looking into some things you might want to learn during your journey here.</p> <p>First you should be checking accuracy every x epochs. If the accuracy doesn't improve after say, 3 epochs you need to end your training.</p> <p...
python|tensorflow|machine-learning|keras|deep-learning
0
359,941
55,608,889
Pandas: Group by with condition
<p>I have to group the transactions (InvoiceNo) that do not contain any <code>SmallSeller</code> product (SellCategory) and I'm not sure on how to proceed.</p> <p>I will finally have to compare the revenue (<code>Quantity*UnitPrice</code>) generated by both types of transactions (the ones containing a <code>SmallSelle...
<pre><code>df_pivot=df.pivot_table(index='InvoiceNo',columns='SellCategory',values='Revenue',aggfunc='sum').reset_index() </code></pre>
python|pandas|group-by|transactions
0
359,942
55,699,046
Filling specific missing value in Python
<p>I have two columns which are <code>PREVAILING_WAGE</code> and <code>JOB_TITLE</code> in my dataset. </p> <p><code>JOB_TITLE</code>:</p> <pre><code>ANALYST, BRAND DEVELOPMENT ANESTHESIOLOGIST ANESTHESIOLOGIST BUSINESS INTELLIGENCE ANALYSTS CIVIL ENGINEER CIVIL ENGINEER COMPUTER PROGRAMMER COMPUTER PROGRAMMER ANALYS...
<p>First I create some random data with <code>NaN</code> - so I can test code.</p> <pre><code>job_title = '''ANALYST, BRAND DEVELOPMENT ANESTHESIOLOGIST ANESTHESIOLOGIST BUSINESS INTELLIGENCE ANALYSTS CIVIL ENGINEER CIVIL ENGINEER COMPUTER PROGRAMMER COMPUTER PROGRAMMER ANALYST COMPUTER SYSTEM ANALYST COMPUTER SYSTEM ...
python|pandas|scikit-learn
1
359,943
55,957,474
Use Artificial Intelligence to predict next number (n+1) in a sequence
<p>The AI must predict the next number in a given sequence of incremental integers using Python, but so far I haven't gotten the intended result. I tried changing the learning rate and iterations but so far without any luck.</p> <p>The next number is supposed to be predicted based on this <em>PATTERN</em>:</p> <p><em...
<p>I think there is no necessity to use AI, the linear regression model is good enough for this task.</p> <pre><code>Input=[('scale',StandardScaler()),('model',LinearRegression())] # Standardizes the data pipe=Pipeline(Input) # perform prediction using a linear regression model using the features Z and targets y pipe....
python|numpy|machine-learning|artificial-intelligence
0
359,944
55,647,184
Joining python string from list by using .join function is not outputing wanted result
<p>EDIT: to clarify I changed list name for this question and I don't call it "list" in my code. It's called for what it represents, but that is not important in this topic.</p> <p>I have the following list:</p> <pre><code>[['ab', 'cd', 'ef', 'gh', 'ij', 'kl'], ['ab', 'cd', 'ef', 'gh', 'ij', 'kl'], ['ab', 'cd', 'ef...
<p>Your code should work, anyway here you have a comprehension achieving the same:</p> <pre><code>&gt;&gt;&gt; l = [['ab', 'cd', 'ef', 'gh', 'ij', 'kl'], ... ['ab', 'cd', 'ef', 'gh', 'ij', 'kl'], ... ['ab', 'cd', 'ef', 'gh', 'ij', 'kl'], ... ['ab', 'cd', 'ef', 'gh', 'ij', 'kl'], ... ['ab', 'cd', 'ef', 'gh', 'ij', ...
python|string|pandas
1
359,945
55,738,163
Find when the values of a pandas.Series change by at least x
<p>I have a time series s stored as a pandas.Series and I need to find when the value tracked by the time series changes by at least x.</p> <p>In pseudocode:</p> <pre><code>print s(0) s*=s(0) for all t in ]t, t_max]: if |s(t)-s*| &gt; x: s* = s(t) print s* </code></pre> <p>Naively, this can be co...
<p>I don't know if I am understanding you correctly, but here is how I interpreted the problem:</p> <pre><code>import pandas as pd import numpy as np # Our series of data. data = pd.DataFrame(np.random.rand(10), columns = ['value']) # The threshold. threshold = .33 # For each point t, grab t - 1. data['value_sh...
python|pandas|numpy|bigdata
1
359,946
55,762,759
How to fix "module 'tensorflow' has no attribute 'estimator' " error
<p>I'm using conda (env created via YAML) + pip to set up a Tensorflow v1.13.1 environment on my Linux Mint box. After setup, whenever I try to import <code>tf.estimator</code> I receive the <code>AttributeError</code> described in the title:</p> <pre><code>AttributeError: module 'tensorflow' has no attribute 'estimat...
<p>Finally found the issue. I had some local (non-Conda) Tensorflow packages still installed, which were higher priority in the python environment, I guess.</p> <p>This link solved my issue: <a href="https://github.com/tensorflow/tensorboard/issues/2067" rel="nofollow noreferrer">https://github.com/tensorflow/tensorbo...
python|tensorflow|tensorflow-estimator
2
359,947
64,823,773
Trying to use tf-nightly-gpu with RTX 30 card
<ul> <li>Windows 10</li> <li>RTX 3070</li> <li>CUDA 11.1</li> <li>cuDNN 8.0.5 (for CUDA 11.1)</li> <li>python 3.8.5</li> <li>tf-nightly-gpu 2.5.0.dev20201113</li> <li>using Anaconda environment</li> </ul> <p>My program worked fine before upgrading to a 3070 however, I was using normal tensorflow-gpu beforehand. Im gett...
<p>Turn memory growth on for your GPU.</p> <pre><code>for device in tf.config.experimental.list_physical_devices(&quot;GPU&quot;): tf.config.experimental.set_memory_growth(device, True) </code></pre>
python-3.x|tensorflow|visual-studio-code
1
359,948
64,766,246
violin plots for all columns of two dataframes with each side of a violin showing the same column but from another dataframe
<p>I have two pandas dataframes named <code>train_df</code> and <code>test_df</code>. They both have columns with same names and <code>test_df</code> doesn't have only one column that <code>train_df</code> does. I now want to plot violin plots showing distribution(like box plot) of each column of my dataframe(s) in eac...
<p>You will have to combine your two dataframe in one, with a column setting the origin of each line:</p> <pre class="lang-py prettyprint-override"><code># create fake data tips = sns.load_dataset('tips') train_df = tips.loc[tips['smoker']=='Yes'] test_df = tips.loc[tips['smoker']=='No'] # concatenate both dataframe d...
python|pandas|matplotlib|seaborn|violin-plot
1
359,949
64,777,868
pandas barchart color the bar to matching column data
<p>I have a graph where values are the number of colors ( 4 red, 5 blue, 1 white) etc. How do I color the bars to match the data, when I try my code the reds are green , the whites are black for example.</p> <pre><code>def this_family(): data = pd.read_sql('SELECT * FROM toys WHERE Date &gt;= ? ', conn, params=(...
<p>This was solved by ordering the initial database query.</p>
pandas|plot
0
359,950
64,634,279
How to merge 2 Dataframes by datetime of one df has only dates and the other is indexed hourly
<p>i have two dataframes. One is indexed by dates (daily), containing values valid for the whole day and the other is indexed by datetime (hourly) containing values for every hour.</p> <p>DF1</p> <pre><code>date A B C D F 2017-07-01 11:00:00 2505.56 2513.38 2495.12 2509.17...
<p>Use <code>merge_asof</code> here:</p> <pre><code>df1['date'] = pd.to_datetime(df1['date']) df2['date'] = pd.to_datetime(df2['date']) df1.sort_values('date', inplace=True) df2.sort_values('date', inplace=True) df = pd.merge_asof(df1, df2, on='date') print(df) date A B C ...
python|pandas|dataframe|datetime
1
359,951
64,797,644
Efficient method to adjust column values where equal to x - Python
<p>The following multiplies all values in a column where rows are equal to a specific value. Using below, where row is in <code>Item</code> is equal to <code>Up</code>, I want to multiply all other columns by <code>2</code>. I'm passing this to a single column at at time. Is there a more efficient way to process this?<...
<p>You can do:</p> <pre><code>df.loc[df['Item'] == 'Up', ['A','B']] *= 2 </code></pre> <p>Output:</p> <pre><code> Item A B 0 Up 100 120 1 Up 100 140 2 Down 60 60 3 Up 120 100 4 Down 40 50 5 Up 60 120 </code></pre>
python|pandas
2
359,952
64,984,627
The definition of "heads" in MultiheadAttention in Pytorch Transformer module
<p>I am a bit confused about the definition of Multihead.<br> Are [1] and [2] below the same?</p> <p>[1] My understanding about multiplhead is the multiple attention patterns as below.<br> <em>&quot;multiple sets of Query/Key/Value weight matrices (the Transformer uses eight attention heads, so we end up with eight set...
<p>As per your understanding, multi-head attention is multiple times attention over some data.</p> <p>But on contrast, it isn't implemented by multiplying the set of weights into number of required attention. Instead, you rearrange the weight matrices corresponding to the number of attentions, that is reshape to the we...
pytorch|transformer-model
1
359,953
64,819,774
How can I replace NaN values in DataFrame from another table?
<p>I have a DataFrame 'df'</p> <p><a href="https://i.stack.imgur.com/SI0TX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SI0TX.png" alt="enter image description here" /></a></p> <p>And the second is 'nan_gdp'</p> <p><a href="https://i.stack.imgur.com/wbppR.png" rel="nofollow noreferrer"><img src="h...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>Series.fillna</code></a> by mapped values from <code>df</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><cod...
pandas|join|replace|nan|fillna
1
359,954
65,002,724
Add a part of string in a column based on the values of another column (Python Pandas)
<p>I have a dataframe like this</p> <pre><code>Anno | Mese ___________ 2018 | Gennaio 2019 | Febbraio 2020 | Aprile </code></pre> <p>If the values of Mese are: Gennaio, Febbraio, Marzo --&gt; i want Anno to be year_Q1 If the values of Mese are: Aprile, Maggio, Giugno, --&gt; i want Anno to be year_Q2 If the values of M...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> by dictionary with chnged dictionary and add to <code>anno</code> column:</p> <pre><code>d = {'Q1': ['Gennaio', 'Febbraio', 'Marzo'], 'Q2': ['Aprile', 'Maggio', 'G...
python-3.x|pandas|dictionary
1
359,955
64,893,444
How to add an empty column to a dataframe? - followup
<p>This question was answered <a href="https://stackoverflow.com/a/16327135/8443371">here</a>. Yet, having the following input:</p> <pre><code>print(type(df1)) df1['x'] = np.nan </code></pre> <p>I got the following output:</p> <pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt; C:\ProgramData\Anaconda3\lib\site-pack...
<p>The true reason for this warning is likely a few lines of code back, when you create <code>df1</code>. If you have something like this:</p> <pre class="lang-py prettyprint-override"><code>df1 = another_df[['col1', 'col2']] </code></pre> <p>Sometimes you get a slice of the original data frame, other times you get a c...
python-3.x|pandas|dataframe|jupyter
1
359,956
64,795,941
How do I forward fill na's with condition of 2 other cells being equal in pandas?
<p>I have customer transaction data where some invoice numbers are missing. I would like to fill the missing invoice numbers with the preceding row value if both the customer id's are equal in the rows and the transaction amounts are equal. Date is not important.</p> <p>An example of what the data looks like is:</p> <p...
<p>Update: Add a specific column to ffill, thanks to @David Erickson's comment.</p> <p>You can use <code>groupby</code> and <code>ffill</code>.</p> <pre><code>df['invoice'] = df.groupby(['customer', 'amount'])['invoice'].ffill() </code></pre>
python|pandas|missing-data
4
359,957
64,804,288
Is there a way to pull only one column of csv file with pandas?
<p>I only need the first column</p> <pre><code>index A B C &quot;11.08.2001 11:00:00&quot; 12345 1234521 128984 &quot;11.08.2001 12:00:00&quot; 82345 1345216 432898 &quot;11.08.2001 13:00:00&quot; 52345 1234521 228984 &quot;11.08.2001 14:00:00&quot; 13345 ...
<p>You sample set doesn't say if it is a csv or not. If it is, this should do the trick:</p> <pre><code>pd.read_csv(r&quot;file.csv&quot;,usecols=[0]) </code></pre>
python|pandas|dataframe|csv|file
1
359,958
64,911,900
How to convert 1D array into single column 2D array
<p>I have an 1D array.</p> <pre><code>my_array([1330.4286, 1330.1406, 1333.7192, 1333.5702, 1328.096]) </code></pre> <p>can you please tell me how to convert this 1D array into single column 2D array like this_</p> <pre><code>my_array([[1330.4286 ], [1330.1406 ], [1333.7192 ], ...
<p>List comprehension:</p> <pre><code>d2 = [[a] for a in d1_list] </code></pre> <p>in numpy:</p> <pre><code>d2 = d1_list.reshape((d1_list.shape[0],1)) </code></pre> <p>reshape in 2d accept a tuple defining the shape where <code>(rows,cols)</code></p>
python|arrays|numpy-ndarray
0
359,959
64,909,903
How to use Tensorboard in AWS Sagemaker
<p><strong>I am referring to the links below to use Tensorboard in Sagemaker Script Mode method.</strong></p> <p><a href="https://www.tensorflow.org/tensorboard/get_started" rel="nofollow noreferrer">https://www.tensorflow.org/tensorboard/get_started</a></p> <p><a href="https://levelup.gitconnected.com/how-to-use-tenso...
<p>Your tensorboard <code>logdir</code> is not <code>logs/fit</code>.. but there is the current date appended. Try using a <code>logs/fit</code> as <code>log_dir</code> and see if it's working.</p> <p>EDIT</p> <p>If you want to use tensorboard locally you have to send tensorboard logs to S3 and read from there. In orde...
amazon-web-services|amazon-s3|tensorflow2.0|tensorboard|amazon-sagemaker
1
359,960
64,741,704
Assigning values to numpy cells in one go
<p>Suppose I have a 2D numpy array of zeros. I want to assign 1 to multiple cells. How do I do this?</p> <p>So for example:</p> <pre><code>arr = np.zeros((5,3)) idx = [0,1,2,2,0] </code></pre> <p>Here, <code>idx</code> is the column indices of the cells I want changed.</p> <p>So my desired output is:</p> <pre><code>1 ...
<p>Try advanced indexing:</p> <pre><code>arr[np.arange(len(arr)), idx] = 1 </code></pre>
python|numpy
3
359,961
64,689,805
Merge or concat df's with uneven rows - python
<p>I have three separate data frames. I'm hoping to merge or concat these together. I have a reference value in each data frame. I have labelled them <code>ValueX, ValueY, ValueZ</code>. But they don't have unique values to merge on. They almost always contain the same number of corresponding values though.</p> <p>Usin...
<p>You can use <code>itertools.zip_longest</code> to align the groups:</p> <pre><code>from itertools import zip_longest g1 = df1.groupby('ValueX') g2 = df2.groupby('ValueY') g3 = df3.groupby('ValueZ') dfs = [] for (_, a), (_, b), (_, c) in zip_longest(g1, g2, g3, fillvalue=('', pd.DataFrame())): dfs.append( ...
python|pandas|merge|concat
1
359,962
65,052,807
Strip index as Pandas column
<p>I have a table with a single index column looking like this:</p> <pre><code> 1 2 3 Monday_0 NaN NaN NaN Monday_1 NaN NaN NaN Tuesday_2 NaN NaN NaN Tuesday_3 NaN NaN NaN </code></pre> <p>I want to keep the index, but want the first part of the index into a new column. In other words, it sho...
<p>Try <code>str.split</code></p> <pre><code>df['Day']=df.index.str.split('_').str[0] df Out[219]: 1 2 3 Day Monday_0 NaN NaN NaN Monday Monday_1 NaN NaN NaN Monday Tuesday_2 NaN NaN NaN Tuesday Tuesday_3 NaN NaN NaN Tuesday </code></pre>
python|python-3.x|pandas|dataframe
3
359,963
64,886,253
How can I remove string after last underscore in python dataframe?
<p>I want to remove the all string after last underscore from the dataframe. If I my data in dataframe looks like.</p> <pre><code>AA_XX, AAA_BB_XX, AA_BB_XYX, AA_A_B_YXX </code></pre> <p>I would like to get this result</p> <pre><code>AA, AAA_BB, AA_BB, AA_A_B </code></pre>
<p>You can do this simply using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.join.html" rel="nofollow noreferrer"><co...
python|pandas|dataframe
3
359,964
64,771,656
how to detach list of pytorch tensors to array
<p>There is a list of PyTorch's Tensors and I want to convert it to array but it raised with error:</p> <blockquote> <p>'list' object has no attribute 'cpu'</p> </blockquote> <p>How can I convert it to array?</p> <pre><code>import torch result = [] for i in range(3): x = torch.randn((3, 4, 5)) result.append(x) ...
<p>You can stack them and convert to NumPy array:</p> <pre class="lang-py prettyprint-override"><code>import torch result = [torch.randn((3, 4, 5)) for i in range(3)] a = torch.stack(result).cpu().detach().numpy() </code></pre> <p>In this case, <code>a</code> will have the following shape: <code>[3, 3, 4, 5]</code>.</p...
python|list|numpy|pytorch|tensor
2
359,965
64,970,363
Open - Edit - Save - Loop csv files in a folder with python
<p>I will receive a folder with 100+ .csv files and I will need to edit them in the same way. Files have the same structure. Folder looks like this: df1.csv df2.csv df3.csv ... df100.csv. I need to open all files - edit them - and then save them as &quot;df1-edited&quot;, &quot;df2-edited&quot; and so on.</p> <p>As per...
<p>For this you can use a module from the standard-library that works with your operating system.</p> <p>Essentially, you need to find all the <code>.csv</code> files in your folder and iterate over them.</p> <p>Let's use <code>pathlib</code>. This is not tested but something like this should work:</p> <pre><code>from ...
python|pandas|csv
0
359,966
65,030,079
create dynamic column names in pandas
<p>I am trying to create multiple dataframes inside a for loop using the below code:</p> <pre><code>for i in range(len(columns)): f'df_v{i+1}' = df.pivot(index=&quot;no&quot;, columns=list1[i], values=list2[i]) </code></pre> <p>But I get the error &quot;Cannot assign to literal&quot;. Not sure whether there is a way...
<p>This syntax</p> <pre><code>f'df_v{i+1}' = df.pivot(index=&quot;no&quot;, columns=list1[i], values=list2[i]) </code></pre> <p>means that you are trying to assign DataFrames to a string, which is not possible. You might try using a dictionary, instead:</p> <pre><code>my_dfs = {} for i in range(len(columns)): my_dfs...
python|pandas
1
359,967
64,946,025
Pytorch math calculation ( only one element tensors can be converted to Python scalars)
<p>What does it mean by only one element tensors can be converted to Python scalars in this case and how do I suppose to debug it?</p> <pre><code>x1 = (max-min)*torch.rand(1, 21) + min x2 = (max-min)*torch.rand(1, 21) + min zipped_list = zip(x1, x2) y = [math.sin(2*x1+2) * math.cos(0.5*x2)+0.5 for (x1, x2) in zipped_li...
<p>You get that error because your torch tensors (x1 and x2) are not a single element tensor.</p> <pre class="lang-py prettyprint-override"><code>t = torch.tensor([10, 20]) print(t.item()) # This will throw an error since the tensor has more than 1 element </code></pre> <pre class="lang-py prettyprint-override"><code>t...
python|numpy|pytorch
0
359,968
65,045,181
Determining the Distance between two matrices using numpy
<p>I am developing my own Architecture Search algorithm using Pythons numpy. Currently I am trying to determine how to develop a cost function that can see the distance between X and Y, or two matrices. I'd like to reduce the difference between the two, to a meaningful scalar value.</p> <p>Ideally between 0 and 1, so t...
<p>There are many ways to calculate a scalar &quot;difference&quot; between two matrices. Here are just two examples.</p> <ol> <li><p>The mean square error:</p> <pre><code>((m1 - m2) ** 2).mean() ** 0.5 </code></pre> </li> <li><p>The max absolute error:</p> <pre><code>np.abs(m1 - m2).max() </code></pre> </li> </ol> <p>...
python-3.x|numpy
1
359,969
64,622,728
How to select columns from different tables based on other facture to create a new dataframe python
<p>I have 2 DataFrames both countain countries 1-first have 183 row 2-the second have 156 row both of them has import information on each other I need one column from the first and one column from the second My goal is to create a single Dataframe contain both columns that I need and name of the contain that both dataf...
<p>You can merge both data frames:</p> <pre><code>newdf=df.merge(df_happy,how='left', left_on='Country', right_on='Country or region') </code></pre> <p>and then drop the extra columns with:</p> <pre><code>newdf.drop(columns=['B', 'C']) </code></pre>
python|pandas|dataframe|data-science|data-analysis
1
359,970
64,783,171
merge multiple lists into one list in python using for loop
<p>I have a code that return the max value of each column in the dataframe until now it returns each value as a seperated list so if i have 3 values it returns 3 list each list contains one item.</p> <p>What i want is to return one list that contains all the items.</p> <pre><code>returned list: [1] [509] [92] [332] [...
<p>You can just define your list before you enter the loop and print it afterwards.</p> <pre><code>mx = [] for x in grouped_df.columns: maxvalue = grouped_df[x].max() mx.append(maxvalue) print(mx) </code></pre> <p>You can also use the builtin <code>max</code> function.</p> <pre><code>print(gr...
python|pandas|list|for-loop
2
359,971
64,885,764
Turning list objects into list names
<p>I have part of a python script that has become redundant and I want to use a for statement to consolidate it. Along with that, I want to make &quot;List&quot; as a list of all the list names that lead to making the lists I want (I hope that makes sense).</p> <p>My current code looks like this...</p> <pre><code>List ...
<p>You mean something like this?</p> <pre><code> list_names = ['List1', 'List2', 'List3'] for name in list_names: info_parsed = info.loc[info['Group'].isin([name])] globals()[name] = info_parsed['Name'].to_list() </code></pre>
python|python-3.x|pandas
1
359,972
64,859,458
Tensorflow automatcly input None in shape?
<p>I'm learning TF. Starting with the mnist dataset. I have 10.000 images of 28*28 pixels. If i input that as a shape</p> <pre><code>from tensorflow import keras from tensorflow.keras.datasets import mnist from matplotlib import pyplot from tensorflow.keras import layers (x_train, y_train), (x_test, y_test) = keras.da...
<blockquote> <p>The None is just a placeholder saying that the network can input more than one sample at the time. None means this dimension is variable. The first dimension in a keras model is always the batch size. ...</p> <p>That's why this dimension is often ignored when you define your model. For instance, when yo...
python|tensorflow|keras
1
359,973
64,623,182
How to scrape data from election website with unusual table
<p>I'm trying to scrape some data from an election website and can't figure out how to pull this data using BeautifulSoup.</p> <p>Texas Election Results <a href="https://results.texas-election.com/contestdetails?officeID=1001&amp;officeName=PRESIDENT%2FVICE-PRESIDENT&amp;officeType=FEDERAL%20OFFICES&amp;from=race" rel=...
<p>First of all, the error you're getting means that you're using <code>BeautifulSoup</code> incorrectly.</p> <p>You need to pass a response from a HTTP client to <code>BeautifulSoup</code> like this:</p> <pre><code>import requests from bs4 import BeautifulSoup url = &quot;https://results.texas-election.com/races&quot...
python|pandas|web-scraping|beautifulsoup
1
359,974
64,684,738
Multiply Two different columns from two different Dataframes with specific condition
<p>I have two different dataframes . They have the same columns but different rows. I need to multiply row from 2020 to 2023 of X DataFrame with percent Y DataFrame.</p> <p>X DataFrame 2020: 300 multiply 0.2 and 40 multiply 0.4.</p> <p>I will apply to like too many columns that is why I need to automate it. Would you p...
<p><code>X.loc[2020:2023] = X.loc[2020:2023] * Y.loc['percent']</code></p>
python|pandas|dataframe
0
359,975
64,756,371
How do I access this variable outside the function?
<p>I am trying to re-use a variable that I defined in a function, but it keeps saying that the specific variable is not defined. How do I use the variable slope inside the function later on? Or how do I make it into a global variable?</p> <pre><code>def linear_fit_detrend(data): slope, intercept, r_value, p_value, ...
<p>Among other solutions : declare the variable in the global scope and use it within your function. Then it will be accessible outside the function :</p> <pre><code>slope = 0 def linear_fit_detrend(data): global slope slope, intercept, r_value, p_value, std_err = stats.linregress(years_trend, data) print(...
python|function|numpy|jupyter
0
359,976
64,749,303
Replace and remove duplicates string elements from one column in Python
<p>Given a small dataset as follows:</p> <pre><code> id room area room_vector 0 1 A-102 world 01 , 02, 03, 04 1 2 NaN 24 A; B; C 2 3 B309 NaN s01, s02 , s02 3 4 C·102 25 E2702-2703,E2702-2703 4 5 E_1089 hello 03,05,06 5 ...
<p>Idea is remove whitespaces, then split by <code>,</code> or <code>;</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</code></a> and then remove duplicates with original order by create dictionary from keys and...
python-3.x|pandas|dataframe|str-replace
1
359,977
64,931,328
Add an additional level using MultiIndex.from_tuples in pandas
<p>I am trying to add an extra level to my multi-level index in python. My data frame looks as following.</p> <p><code>df1=pd.DataFrame(np.array([['A',1, 2, 3], ['B',-4,5 , -6], ['d',7, 0, 9]]), columns=['D','a', 'b', 'c'])</code></p> <p>I used following code to add multi levels</p> <p><code>df1.columns=pd.MultiIndex.f...
<p>Try:</p> <pre><code># cache the original columns columns = df1.columns # force columns to RangeIndex df1.columns = np.arange(df1.shape[1]) # rename the columns with the new name df1.columns = pd.MultiIndex.from_tuples([ (x,a,y) for (x,y),a in zip(columns, [1,2,1,3]) ]) </code></pre> <p>Output:</p> <pre><code> ...
python|pandas|header|multi-index
0
359,978
64,780,770
Creating a Keras CNN for image alteration
<p>I'm working on a problem that involves computationally evaluating three-dimensional data of the shape <code>(32, 16, 5)</code> and providing a corrected form of this data also in the shape of <code>(32, 16, 5)</code>. The problem is relatively specific to my field, but it can be viewed as analogous to processing co...
<p>I think you made two mistakes in your code:</p> <ol> <li>Instead of using <code>Conv3D</code>, you need to use <code>Conv2D</code>.</li> <li><code>model.fit(input_img, output_img)</code> should be <code>model.fit(inputs, outputs)</code>.</li> </ol> <p>The reason why you need to use <code>Conv2D</code> is the shape o...
python|numpy|tensorflow|keras|deep-learning
2
359,979
64,895,686
Day and Night time categorizing
<p>I have tried many commands to get the day night time correctly as I defined it in the dictionaries. However, it works partly and return other unexpected results.</p> <p>I have the following dataframe and commands</p> <pre><code>import pandas as pd import numpy as np data = pd.DataFrame({ 'ID': [1, 1, 1, 1, 2, 2, 3,...
<p>You can use <code>.indexer_between_time</code> to check if the index of your dataframe is between a certain timeframe. You only need a <code>date</code> column, so no need to make a seperate <code>time</code> column if you don't need it for any other purposes.</p> <pre><code># Set day &amp; nighttime based your spec...
python|pandas|dataframe
1
359,980
64,952,634
Not getting reproducible results TensorFlow-Keras-Google Collab
<p>I've been trying to create a model that recognizes different singing techniques. I have got good results but I want to do different tests with different optimizers, layers, etc. However, I can't get reproducible results. By running twice this model training:</p> <pre><code>num_epochs = 100 batch_size = 128 history =...
<p>It is a normal situation. Adam optimizer is much more powerful comparing to SGD. Adam implicitly performs coordinate-wise gradient clipping and can hence, unlike SGD, tackle heavy-tailed noise.</p>
python|tensorflow|machine-learning|keras|deep-learning
0
359,981
64,684,692
Combine two geojson state zipcode files?
<p>I am working on a project where I need to use <a href="https://github.com/OpenDataDE/State-zip-code-GeoJSON" rel="nofollow noreferrer">US States Zip Code Data</a>. I want to merge two geojson files while preserving the data in those files. geojson-merge <code>https://github.com/mapbox/geojson-merge</code> does this ...
<p>What about something like this?</p> <pre><code>import json fc = { 'type': 'FeatureCollection', 'features': [] } with open(&quot;mt_montana_zip_codes_geo.min.json&quot;) as json_file: obj = json.load(json_file) fc['features'].extend(obj['features']) with open(&quot;nd_north_dakota_zip_codes_geo.min...
python|json|geojson|geopandas
1
359,982
64,785,323
Python Pandas does not recognize numbers when read from .txt file
<p>I'm using Pandas to write to table from .txt file generated by other C++ program. Python or Pandas do not recognize them as numbers and I'm really clueless what to do. Here is Python code:</p> <pre><code>df = pd.read_csv(r'C:\Users\romea\Desktop\Inżynierka\ER_etap_5\Metropolis_average_path_6_p_0.010000_nodes_100.txt...
<pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv(r'your_file_here.txt', sep='\t', header=0) plt.scatter(df[&quot;iteracja&quot;], df[&quot;variancja&quot;]) plt.show() </code></pre>
python|c++|pandas
1
359,983
65,038,664
How to change only the year in a dataframe column (datetime) if the month is january?
<p>I have a dataframe with some dates in a column. I would like to set the year to 2021 if the month is January, as I have some errors in the Data I am processing with people putting January 2020.</p> <pre><code> Port Of Loading ETA Destination Port 2 Qingdao 2020-01-09 00:00:00 3 Qingdao 2020...
<p>You can try the below code :</p> <pre><code>import pandas as pd csvfile = pd.read_csv(&quot;input.csv&quot;) # Extract dates in separated columns csvfile['Day'] = pd.to_datetime(csvfile['ETA Destination Port']).dt.day csvfile['Month'] = pd.to_datetime(csvfile['ETA Destination Port']).dt.month csvfile['Year'] = pd....
python|pandas
0
359,984
65,030,453
Adding string to the end of each group's last sentence
<p>I'm looking to add string, in this case <em>&quot;&lt;endofsentence&gt;&quot;</em> after each group/id's last sentence.</p> <p>To be precise, what I have now is df2 and i'm trying to get df3 with the following sample code:</p> <pre><code>df2=pd.DataFrame({'id':[1,1,1,2,2,2,3,3,3], 'text':['senten...
<p>Oh, I see what you're saying. This seems to do:</p> <pre class="lang-py prettyprint-override"><code>ids = df2 .id unequal = ids .index[ ids .shift(-1) != ids ] df2 .text .loc[ unequal ] += '&lt;endofsentence&gt;' print( df2 ) </code></pre> <pre><code> id text time 0 1 sen...
python|python-3.x|pandas|dataframe
1
359,985
64,783,772
Python: Convert dataframe with 1 column to specific ndarray
<p>I have a pandas dataframe with 1 column and n rows, for example:</p> <pre><code> 0 0 03110311000311 1 18003130313000313 2 36003120312000312 3 54003110311000311 4 72003100310000310 ... ... [1400 rows x ...
<p>Just select the column first:</p> <pre><code>df['column_index'].to_numpy() </code></pre> <p>Example:</p> <pre><code>df = pd.DataFrame(np.arange(6)) df.to_numpy().shape # (6,1) df[0].to_numpy().shape # (6,) </code></pre>
python|python-3.x|pandas|numpy|numpy-ndarray
0
359,986
64,981,106
concatenate results after multiprocessing
<p>I have a function which is creating a data frame by doing multiprocessing on a df:-</p> <p>Suppose if I am having 10 rows in my df so the function processor will process all 10 rows separately. what I want is to concatenate all the output of the function processor and make one data frame.</p> <pre><code>def processo...
<p>you can use either the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html" rel="nofollow noreferrer">data frame constructor</a> or <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> to solve ...
pandas|multithreading|dataframe|multiprocessing
1
359,987
64,827,793
Python and pandas, groupby only column in DataFrame
<p>I would like to group some strings in the column called 'type' and insert them in a plotly bar, the problem is that from the new table created with groupby I can't extract the x and y to define them in the graph:</p> <pre><code>tipol1 = df.groupby(['tipology']).nunique() tipol1 </code></pre> <p>the outpot gives me ...
<p>By default the method <code>groupby</code> will return a dataframe where the fields you are grouping on will be in the index of the dataframe. You can adjust this behaviour by setting <code>as_index=False</code> in the group by. Then <code>tipology</code> will still be a column in the dataframe that is returned:</p>...
python|pandas|plotly
0
359,988
64,970,293
pandas dataframe, if condition match and index next to each other: add value and delete the row used
<p>I want to drop queried dataframe - rows and replace it with new data when the index are next to each other.</p> <p>basically adding value i-1 to i.</p> <p>is this possible to be done ?</p> <p>please see the example data below: if i have a data frame as above: i want to amend the dataframe as below</p> <pre><code> im...
<p>Try:</p> <pre><code>grp = (~training_data['condition']).cumsum() training_data.query('condition')\ .groupby(grp)\ .agg({'a':'sum','b':'sum','c':'sum','condition':'first'}) </code></pre> <p>Output:</p> <pre><code> a b c condition condition 0 2 2 2 ...
python|pandas|dataframe|drop
1
359,989
65,055,097
Pandas dates wrong when writing to drive
<p>the following code messes up dates in pandas/python3 when writing an excel to the hard drive:</p> <p>(actually, it doesn't, see edit and screenshot below)</p> <pre><code>df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d') df = df.set_index('Date') high = df['High'].resample(&quot;Y&quot;).max() low = df['Low'...
<p>Please see the edit for an answer to posted issue.</p>
python|pandas
0
359,990
64,910,527
Accuracy killed when using ImageDataGenerator TensorFlow Keras
<p>I have already made a post here but the answers have not been quite helpful, probably because I did not phrase the question right. Now I know more about the problem but still cannot find the solution.</p> <p>I tried to build a Convolutional Neural Network in Tensorflow Keras to predict on the CIFAR100 dataset. I man...
<p>The only problem I see is that you've configured shuffle to be off on the generator. Everything else is fine. There is no change in images or labels. Note that by default, model.fit will shuffle input data, but when you use a generator you must configure the generator to shuffle. As such, when you did not provide ...
python|tensorflow|machine-learning|keras
0
359,991
40,001,888
Python - Access column based on another column value
<p>I have the following dataframe in python</p> <pre><code>+-------+--------+ | Value | Number | +-------+--------+ | true | 123 | | false | 234 | | true | 345 | | true | 456 | | false | 567 | | false | 678 | | false | 789 | +-------+--------+ </code></pre> <p>How do I conduct an operation whi...
<p><code>df.loc[df['Value'],'Number']</code> should work assuming the dtype for 'Value' are real booleans:</p> <pre><code>In [68]: df.loc[df['Value'],'Number'] Out[68]: 0 123 2 345 3 456 Name: Number, dtype: int64 </code></pre> <p>The above uses boolean indexing, here the boolean values are a mask against t...
python|pandas
0
359,992
39,895,315
Pandas dataframe creation from a list
<p>Im getting the following error <code>Shape of passed values is (1, 5), indices imply (5, 5)</code>. From what I can tell this suggests that the data set doesnt match the column count, and of course it obviously is correct. Initially I thought it could be due to using a list, but I get the same issue if passing in a ...
<p>you have to pass a 2d dimensional array to <code>pd.DataFrame</code> for the data if you force the shape by passing <code>columns</code></p> <pre><code>data = [['data1', 'data2', 'data3', 'data4', 'data5']] df = pd.DataFrame(data, columns=['column1', 'column2', 'column3', 'column4', 'column5']) </code></pre>
python|pandas
1
359,993
40,088,132
Tensorflow MNIST (Weight and bias variables)
<p>I'm learning how to use Tensorflow with the MNIST tutorial, but I'm blocking on a point of the tutorial.</p> <p>Here is the code provided : </p> <pre><code>from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) x = tf.place...
<p>TensorFlow <a href="https://www.tensorflow.org/versions/r0.11/how_tos/variables/index.html" rel="noreferrer">variables</a> maintain their state from one <code>run()</code> call to the next. In your program they will be initialized to zero, and then progressively updated in the training loop.</p> <p>The code that ch...
python|python-3.x|machine-learning|tensorflow
11
359,994
40,307,103
Get Predicted result from tensorflow
<p>I am doing my first tensor flow example with following code. </p> <pre><code>train_x,train_y,test_x,test_y=create_feature_sets_and_labels('pro.txt','neg.txt') n_nodes_hl1 = 1500 n_nodes_hl2 = 1500 n_nodes_hl3 = 1500 n_classes = 2 batch_size = 100 hm_epochs = 7 x = tf.placeholder('float') y = tf.placeholder('float...
<p>The first argument for <code>session.run()</code> should be tensor you want to get. </p> <p>In your case it should be <code>prediction</code> tensor (so you need to return it from your <code>train_neural_network</code>). Apply argmax to it to obtain predicted label.</p>
python|python-2.7|machine-learning|neural-network|tensorflow
2
359,995
40,099,517
Changing learning rate by external function, do I have to run many sessions?
<p>I have a Function, call it DetermineLearningRate that takes in the accuracy (and other metrics) at each iteration and gives the learning rate to a simple CNN.</p> <p>Workflow</p> <ol> <li>Simple CNN DetermineLearningRate() would take in the accuracy and return a learning rate </li> <li>The TensorFlow Graph of the ...
<p>No it is much simpler than that just create a placeholder for the learning rate <code>LR=tf.placeholder(tf.float32,[])</code> and use the value from your function as a feed_dict argument to your training step. </p> <p><strong>WALKTHROUGH:</strong></p> <p>So suppose you have defined a graph that looks something li...
tensorflow
0
359,996
40,165,477
ValueError: Linkage 'Z' uses the same cluster more than once in Python scipy fcluster
<p>I'm getting <code>ValueError: Linkage 'Z' uses the same cluster more than once.</code> when trying to get flat clusters in Python with scipy.cluster.hierarchy.fcluster. This error happens only sometimes, usually only with really big matrices ie 10000x10000. </p> <pre><code>import scipy.cluster.hierarchy as sch Z = ...
<p>It seems using <a href="https://pypi.python.org/pypi/fastcluster" rel="nofollow noreferrer">fastcluster</a> instead of <code>scipy.cluster.hierarchy</code> solves the problem. In addition, <code>fastcluster</code> implementation is slightly faster than <code>scipy</code>.<br> For more details have a look at <a href=...
python|numpy|scipy|hierarchical-clustering
0
359,997
40,305,692
How to learn multi-class multi-output CNN with TensorFlow
<p>I want to train a convolutional neural network with TensorFlow to do multi-output multi-class classification.</p> <p>For example: If we take the MNIST sample set and always combine two random images two a single one and then want to classify the resulting image. The result of the classification should be the two di...
<p>For nomenclature of classification problems, you can have a look at this link: <a href="http://scikit-learn.org/stable/modules/multiclass.html" rel="nofollow noreferrer">http://scikit-learn.org/stable/modules/multiclass.html</a></p> <p>So your problem is called "Multilabel Classification". In normal TensorFlow mult...
tensorflow|conv-neural-network
3
359,998
40,318,013
numpy.mean on varying row size
<p>The numpy mean function works perfectly fine when the dimensions are the same.</p> <pre><code>a = np.array([[1, 2], [3, 4]]) a.mean(axis=1) array([ 1.5, 3.5]) </code></pre> <p>But if I do it with varrying row size it gives an error</p> <pre><code>a = np.array([[1, 2], [3, 4, 5]]) a.mean(axis=1) IndexError: tuple...
<p>Here's an approach -</p> <pre><code># Store length of each subarray lens = np.array(map(len,a)) # Generate IDs based on the lengths IDs = np.repeat(np.arange(len(lens)),lens) # Use IDs to do bin-based summing of a elems and divide by subarray lengths out = np.bincount(IDs,np.concatenate(a))/lens </code></pre> <p...
python|numpy|mean
2
359,999
40,160,268
How extract dictionary keys and set them as column headers in a Pandas data frame
<p>This question is an offshoot of <a href="https://stackoverflow.com/questions/39928273/how-to-remove-curly-braces-apostrophes-and-square-brackets-from-dictionaries-in">How to remove curly braces, apostrophes and square brackets from dictionaries in a Pandas dataframe (Python)</a>.</p> <p>I have the following data in...
<p>Here is the answer:</p> <pre><code>import ast import pandas as pd fixed_columns = pd.read_csv(StringIO(the_data), names=["Company", "Date", "Value", "Cars_str", "Currency_str"]) cars = fixed_columns["Cars_str"].apply(ast.literal_eval) del fixed_c...
python|pandas|dictionary|dataframe
0