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
15,900
51,248,810
Python: Why would numpy.corrcoef() return NaN values?
<p>Why would <code>numpy.corrcoef()</code> return <code>NaN</code> values? </p> <p>I am working with high dimensional data and it is infeasible to go through every datum to test values. </p> <pre><code># Import from sklearn.preprocessing import StandardScaler import pandas as pd import numpy as np # Delete all zero ...
<p>If you have a column where all rows have the same value, that column's variance is <code>0</code>. <code>np.corrcoef()</code> thus numpy-divides that column's correlation coefficients by <code>0</code>, which doesn't throw an error but only the warning <code>invalid value encountered in true_divide</code> with stan...
python|numpy
2
15,901
48,281,449
Merging DataFrames via Smoothing
<p>I would like to efficiently merge two data frames into one, but one data frame has "more data" than the other. Example:</p> <pre><code>df_A = pd.DataFrame({"Time": [pd.to_datetime("09:11:37.600"), pd.to_datetime("09:11:37.700"), pd.to_datetime("09:11:37.80...
<p>You can use the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow noreferrer"><code>pandas.resample()</code></a> method if you use your times as an index. </p> <p><a href="https://stackoverflow.com/a/17001474/6329629">Here</a> you can find the abbreviation...
python-3.x|pandas|merge
1
15,902
48,284,817
why we not able to print column name which have dtype=='object'
<pre><code>import pandas as pd </code></pre> <p>train =pd.read_csv("<a href="https://datahack.analyticsvidhya.com/media/workshop_train_file/train_gbW7HTd.csv" rel="nofollow noreferrer">https://datahack.analyticsvidhya.com/media/workshop_train_file/train_gbW7HTd.csv</a>")</p> <pre><code>train[train.dtypes=='object'] I...
<p>I think you are looking for <code>.loc</code>. Try this:</p> <pre><code>df.loc[:, df.dtypes == 'object'].head() </code></pre> <p><a href="https://i.stack.imgur.com/JpvCW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JpvCW.png" alt="output"></a></p> <p>Or if you just want the column names:</p>...
python|python-3.x|pandas
1
15,903
48,758,427
Signal frontier analysis in pandas: VIX index
<p>I have a very simple VIX (S&amp;P500 1 month implied volatility index) "regime" code that does the following:</p> <ol> <li>Did vix go above 16.5? If yes, color chart red.</li> <li>Did vix go above 19.5? If yes, color chart green.</li> <li>Did vix go below 19.5? If yes, color chart blue.</li> <li>Did vix go below 1...
<p>Here's some code to get you started. In the future, it helps to pare down your examples to something smaller and isolate exactly what you're trying to do.</p> <p>The way I create regime states below is by using "triggers" rather than "states." The presence of a trigger is dependent upon the level of the VIX on da...
python|pandas|matplotlib|finance
1
15,904
48,448,452
Replacing string in pandas python only if it matches the exact string
<p>I'm having trouble getting a string in pandas to be replaced in the correct manner. I'm not sure if I'm limited to using pandas and there might not be a way to do this with solely using pandas.</p> <p>This is how my dataframe looks:</p> <pre><code> (ID: 10) 247333605 0.0 (ID: ...
<p>If you want to generalise, you can use <code>str.replace</code> with SOL/EOL anchors.</p> <pre><code>df['last_status'].str.replace(r'^(\(ID: \d+\))$', r'Planning: \1') 0 Planning: (ID: 10) 1 Planning: (ID: 20) 2 Planning: (ID: 40) 3 Planning: (ID: 50) 4 Planning: (ID: 60) 5 Planning: (ID: 8...
python|pandas
3
15,905
48,833,614
Creating new column with pieces of 3 columns
<p>I would like to create a new column in a dataframe containing pieces of 3 different columns.I would like the first 5 letters of the last name, after removing non alphabeticals, if it is that long else just the last name, the first 2 letters of the first name and a code appended to the end.</p> <p>The code below doe...
<p>Here is one approach.</p> <p>Use pandas <a href="http://pandas.pydata.org/pandas-docs/version/0.18/generated/pandas.Series.str.slice.html" rel="nofollow noreferrer"><code>str.slice</code></a> instead of trying to do string indexing.</p> <p>For example:</p> <p>import pandas as pd</p> <pre><code>df = pd.DataFrame(...
python|regex|pandas
0
15,906
48,879,587
Using Python (scipy or numpy) how do I calculate the 2.5th and 97.5th percentiles of the Student t distribution with 5 degrees of freedom
<p>Using Python (scipy or numpy) how do I calculate the 2.5th and 97.5th percentiles of the Student t distribution with 5 degrees of freedom</p> <p>In R I can do it using</p> <pre><code>&gt; qt(c(.025, .975), df=5) # 5 degrees of freedom [1] -2.5706 2.5706 </code></pre> <p>In Python I get this using 0.95 not 0...
<p>Use <code>ppf</code> (percent point function) of <code>scipy.stats.t</code></p> <pre><code>&gt;&gt;&gt; from scipy import stats &gt;&gt;&gt; stats.t(df=5).ppf((0.025, 0.975)) array([-2.57058184, 2.57058184]) </code></pre>
python|r|numpy|scipy
4
15,907
48,737,123
Python Pandas can't select multiple columns indexed by negative numbers
<p>I have a DataFrame which looks like this:</p> <pre><code> -300 -298 -296 Time (ms) Fp1 -0.416809 -0.024629 0.352019 Fp2 0.369807 0.402025 0.435756 F7 -0.822426 -0.895215 -0.973714 F3 -1.045553 -1.098616 -1.161518 Fz -0.477956 -...
<p>As <a href="https://stackoverflow.com/users/4492932/dyz">DMZ</a> pointed out, it looks like one cannot use negative numbers for indexing, thus the best way to accomplish my task is to convert indexes to strings:</p> <pre><code> df.columns=[str(x) for x in df.columns] </code></pre> <p>and then use them like this</p...
python|pandas
0
15,908
48,467,027
How to access inner json property value while ignoring outer property key?
<p>Below code :</p> <pre><code>import json j = json.loads(" {\"id123\":{\"test\" : 1} } ") j </code></pre> <p>renders : </p> <pre><code>{'id123': {'test': 1}} </code></pre> <p>I'm attempting to access the property test while ignoring the outer property id. </p> <p>This can be achieved using : </p> <pre><code>j[...
<p><strong>You can try this to avoid outer key and get all values inside inner dict</strong></p> <pre><code>import json j = json.loads(" {\"id123\":{\"test\" : 1} } ") for i in j.values(): for x in i: print (i[x]) #your expected output </code></pre>
python|json|pandas
0
15,909
70,928,858
How to ignore a value that exeed from an Axis in Python
<p>I'm new to python. I'm using python 2.7 and i'm using pandas plot to make a BarChart . here 's my code</p> <pre><code>my_colors = list(islice(cycle(['#AB82FB','#9A958F','#0131CC', '#EA3C00', '#22DC00','#CCC201','#01BECC','#CC6F01','#8F959A','#02E7D1','#01FF00','#FDF505']), None, len(df))) df = pd.read_csv(r&quot;/pa...
<p>Consider the following example.</p> <pre><code>import pandas as pd import random import numpy as np df = pd.DataFrame({'x': [x for x in range(30)], 'y': [random.randint(0, 60) for x in range(30)], }) </code></pre> <p>You can recreate a similar plot to the one you have with the ...
python|pandas|python-2.7|matplotlib|bar-chart
0
15,910
71,040,931
Pytorch CNN script training, but not getting results
<p>I’m just getting started with pytorch. I am trying to do a simple binary classification project with the cats and dogs dataset. After much fumbling around, I was able to get the model to train, but I’m not getting the expected results.</p> <p>First, the loss starts out way too low. To me, that seems to indicate I’m ...
<p>It seems I was passing in the wrong thing to my loss function. I changed this line</p> <pre><code>loss = criterion(outputs, torch.max(labels,1)[1]) </code></pre> <p>to this</p> <pre><code>loss = criterion(outputs, torch.max(labels,1)[0]) </code></pre> <p>and everything seems to be working. I'm able to correctly clas...
python|pytorch|conv-neural-network|pytorch-dataloader
1
15,911
70,780,936
What's the most efficient and/or easy way of exporting and using a TensorFlow model
<p>Ive created a time series forecasting model (RNN) which is heavily based off <a href="https://www.tensorflow.org/tutorials/structured_data/time_series#normalize_the_data" rel="nofollow noreferrer">this tutorial</a>, If I wanted to export this model and use it with, say, a kivy UI in python, where I feed it some new ...
<p>It is easy you saved using the log, checkpoint format where you can save and restore directly but the models you need to be specific by target load model. Do it the easy way you will not headaches later.</p> <pre><code># Callback cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, monitor='val_loss', ...
python|tensorflow
-1
15,912
71,068,739
Remove string from one column if present in string of another column pandas
<p>I feel like I'm close but I am looking for something like this where the new column writes the company name without the city in it:</p> <pre><code> company postal_code name state city \ 2000-01-01 abc gresham co 97080 john mi gresham 2000-01-01 ...
<p>Here's a solution:</p> <pre><code>df = ( df.reset_index() .assign(new_col=df.reset_index() .pipe(lambda x: x.assign(x=x['company'].str.split(' '))) .explode('x') .loc[lambda x: x['x'] != x['city'], 'x'] .groupby(level=0) .agg(list) .str.join(' ') ) .set...
python|pandas|string
1
15,913
51,744,231
Pandas - Working with blank spaces
<p>I have a Dataframe as below that has 3 columns namely id, name and feedback. One of the values for customer_input has a value as below</p> <pre><code>id,name,feedback 201,Robert,"response time is slow " </code></pre> <p>I am having issues working inserting this data into a DB table due to the long text it hold in ...
<p>you can use simple <code>str.replace</code></p> <pre><code>df['feedback'] = df['feedback'].str.replace('\r','') df['feedback'] = df['feedback'].str.replace('\n','') print(df) 201 Robert response time is slow </code></pre>
pandas|insert|newline|amazon-redshift
1
15,914
51,922,313
Convert numpy array to pandas in multiple jumps, or columns
<p>I wrote some simple python code (using Beautiful Soup module) to scrap data off a website. The data I have extracted into a numpy array of the form below</p> <pre><code>array(['Aug 18, 2018', '1.989', '1.989', '1.989', '1.989', '0.81%', 'Aug 17, 2018', '1.973', '2.016', '2.016', '1.967', '-0.20%', 'Au...
<p>Since you know the number of columns, just use <code>reshape</code>:</p> <pre><code>pd.DataFrame(data.reshape(-1, 6), columns=['date', 'start', 'end', 'high', 'low', 'change']) </code></pre> <p></p> <pre><code> date start end high low change 0 Aug 18, 2018 1.989 1.989 1.989 1.989 0.81% ...
python|python-3.x|pandas|numpy|web-scraping
1
15,915
51,789,105
pandas: group and find most recent event from table, then join with existing table?
<p>I have two tables in pandas, a <code>user</code> table and a <code>history</code> table - the latter is essentially a log of all actions taken by users. </p> <p>User table:</p> <pre><code> | user_id | source 0 | 1 | blog 1 | 2 | blog 2 | 3 | organic </code></pre> <p>History tabl...
<p>First sort, drop duplicates and create a series from your history dataframe:</p> <pre><code>s = history.sort_values('t_actioned', ascending=False)\ .drop_duplicates('user_id')\ .set_index('user_id')['action_type'] </code></pre> <p>Then map this to your user dataframe:</p> <pre><code>user['ac...
python|pandas|dataframe
4
15,916
51,879,764
Python - Pandas - GroupBy conditional string addition
<p>Currently I'm having trouble setting up a combination of setting up a list and filtering when grouping a dataframe.</p> <p>Let's say we have a DataFrame of the form:</p> <pre><code> A B C 0 x2 a32cd 1 1 x1 a11aa 0 2 x1 NaN 1 3 x1 d75dd 0 4 x1 a11aa 1 5 x2...
<pre><code>&gt;&gt;&gt; df.dropna().groupby("A")["B"].unique() A x1 [a11aa, d75dd] x2 [a32cd, w22xz] dtype: object </code></pre>
python|string|pandas|group-by
3
15,917
51,588,479
How can I use newton or L-BFGS as optimizer?
<p>I read a example of newton or lbfgs optimizer as follow:</p> <pre><code>optimizer = ScipyOptimizerInterface(loss, options={'maxiter': 100}) with tf.Session() as session: optimizer.minimize(session) </code></pre> <p>but I am confused because it's different from gradient descent optimizer as:</p> <pre><code>opt...
<p><a href="https://www.tensorflow.org/api_docs/python/tf/contrib/opt/ScipyOptimizerInterface" rel="nofollow noreferrer"><code>ScipyOpimizerInterface</code></a> is a wrapper allowing <code>scipy.optimize.minimize</code> to operate in a tensorflow <code>Session</code>. </p> <p>It accepts a <code>method</code> kwarg to ...
python|tensorflow
1
15,918
42,009,190
TensorFlow installation error: Operation not permitted .../_markerlib
<p>Despite using <code>sudo</code>, the <code>pip install</code> command sometimes generates an error similar to the following:</p> <pre> ... Installing collected packages: setuptools, protobuf, wheel, numpy, tensorflow Found existing installation: setuptools 1.1.6 Uninstalling setuptools-1.1.6: Exception: … [Errno 1]...
<p>Try to install using <code>--ignore-installed</code> option:</p> <pre><code>sudo pip install --ignore-installed tensorflow </code></pre> <p>It should work.</p>
tensorflow
0
15,919
41,819,049
Unable to read properly a text file in tensorflow
<p>I have a txt file which has 2000 row and 10 columns, columns data separated by tab. To read file I simply defined a function. </p> <pre><code>def readinfo(path): info = tf.read_file(path) return info </code></pre> <p>and when I am trying to read the file </p> <pre><code>path = os.path.join(datadirectory,'1_t...
<p><code>sess.run(tf.shape(x))</code> returns the shape of x, not the value of x. The content of a file is a scalar string, so its shape is <code>[]</code>, as expected. <code>sess.run(x)</code> OTOH should give you the string value.</p>
python|tensorflow|readfile
0
15,920
64,326,528
Dropping duplicate rows in a Dataframe by column a, while keeping rows that contain values from list in column b
<pre><code> address issue row_1 1 No Issue row_2 1 Value row_3 1 None row_4 2 None row_5 2 Test row_6 2 None row_7 3 Example row_8 4 None row_9 5 None row_10 5 None row_11 5 None row_12 5 None row_13 6 No Issue row_14 6 Example row_15 6 None </code></pre> <p>...
<p>We can chunk it into a couple of steps:</p> <p>Step 1 : Create a boolean for rows that are in the <code>issue_list</code></p> <pre><code>df[&quot;issue_isin_list&quot;] = df.issue.isin(issue_list) </code></pre> <p>Step 2 : Create a grouping for each row and get the sum of the newly created boolean columns:</p> <pre>...
python-3.x|pandas|dataframe
0
15,921
64,270,728
Tensorflow hub issue: Can't load embedding model after last update
<p>This code has been working until last tf_hub update. I think, the problem is in the tensorflow_text module, that I haven't installed. But when I try to execute &quot;pip install tensorflow_text==2.3.0&quot; command (copied from the official tf_hub page) it throws back the error. I also tried to install it manually ...
<p>This code is working fine in <code>Tensorflow 2.7</code> in <code>Anaconda</code> <code>jupyter</code> notebook. Please specify the <code>Tensorflow</code> version you are using while running this code.</p> <pre><code>!pip install tensorflow-hub import tensorflow_hub as hub embed = hub.load(&quot;https://tfhub.dev/...
python|tensorflow|machine-learning|dataset|tensorflow2.0
0
15,922
64,419,031
Time Series Clustering of Numpy Objects
<p>Every idea or suggestion would be appreciated! I have several &quot;the same style&quot; numpy objects(u1,u2,u3...) each of them is :</p> <p>Object 1:</p> <pre><code> [[Timestamp('2004-02-28 00:59:16'), 19.9884], [Timestamp('2004-02-28 01:03:16'), 19.3024], ... [Timestamp('2004-02-28 01:06:16'), 19.1652]]...
<p>(1) Your first error means that <code>Timestamp</code> must be converted into a string or a number. Just convert them to numbers by <code>.value</code>, which means nanoseconds since Unix epoch time (1970-01-01). Operation in lists:</p> <pre><code>u1 = list(map(lambda el: (el[0].value / 1e9, el[1]), u1)) u2 = list(m...
python|pandas|numpy|scikit-learn|cluster-analysis
0
15,923
64,368,857
How to connect different deep learning architectures?
<p>Based on 5 features extracted from a sample of binary files, the idea is to combine different deep learning models each of them processing one feature sample.</p> <p>Or simply is there a way to connect a CNN and a RNN, in a way that the output of the CNN would be the input of the RNN ?</p> <p>Any help or reference w...
<p>The Keras <a href="https://www.tensorflow.org/guide/keras/functional" rel="nofollow noreferrer">Functional API</a> can be used to combine different Deeplearing models.</p> <p>It is much more flexible than the Keras Sequential API, in that it can support multiple input, output pipelines.</p> <p>You can implement non-...
tensorflow|keras|deep-learning
1
15,924
59,029,635
change dtype pandas by column number for multiple columns
<p>I would like to change the dtype of a dataframe which I am going to read in using python pandas. I know that I can change the dtype by the column name like this:</p> <pre><code> df = pd.read_csv("blablab.csv", dtype = {"Age":int} </code></pre> <p>However, I would like to set the dtype by the column number. E.g....
<p>I would recommend building the dtype variable ahead of the import by importing one row for you to make a default dict comprehension of a default type and then modify the columns to special types. I pulled in StringIO just for running a test case below.</p> <pre><code>import pandas as pd import numpy as np from io i...
python|pandas|multiple-columns|dtype
2
15,925
58,685,475
Custom layer needs changing tf.keras.input empty tensor into numpy ndarray - 'Tensor' object has no attribute 'numpy' error
<p>I've written a <code>tf.keras</code> custom layer in which I used some functions that work only with <code>numpy</code> arrays, so when I try to use my layer in a model with tf.keras.Input, the functions raise an error: <code>input data must be a numpy ndarray.</code></p> <p><code>tf.keras.backend.eval(x)</code> an...
<p>I think you can't use numpy function for creating the computation graph in Keras or TensorFlow. and you should use equal built-in functions from tensorflow or keras. can you give the code for your costumeLayer?</p>
python|tensorflow|python-3.7|tensorflow2.0|tf.keras
0
15,926
58,763,270
Keep rows with certain type based on a column pandas
<p>I have a dataframe that i want to clean, i have a column with some integer and some timestamp. I want to remove the rows with the integer value in the columns, and only keep the rows with timestamp. </p> <pre class="lang-py prettyprint-override"><code>df.col.unique() #gives array([Timestamp('2017-05-27 00:00:00'),...
<p>Use this to filter your dataframe</p> <pre><code>df[~df.col.map(lambda x: isinstance(x,int))] </code></pre>
python|pandas|dataframe
2
15,927
70,045,478
python pandas | triple conditional statments
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>volume</th> <th>price</th> <th>datetime</th> </tr> </thead> <tbody> <tr> <td>100</td> <td>3</td> <td>2021-09-29 04:00:00-04:00</td> </tr> <tr> <td>900</td> <td>2</td> <td>2021-09-29 04:30:00-04:00</td> </tr> <tr> <td>900</td> <td>5</td> <td>2021-0...
<p>You can use <code>df.sort_values</code> method to sort on multiple columns. Here is an example:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( { &quot;volume&quot;: [100, 900, 900, 500, 900, 900], &quot;price&quot;: [3, 2, 5, 9, 22, 1], &quot;d...
python|pandas|datetime|conditional-statements
2
15,928
56,120,976
getting elements of array in python with a single line
<p>I need to work with this beautiful np array</p> <pre><code>import numpy as np train_predicteds = np.asarray([ [[0.1, 0.2, 0.3], [0.5, 0.6, 0.7], [0.7, 0.8, 0.9]], [[0.3, 0.1, 0.4], [0.4, 0.5, 0.6], [0.5, 0.6, 0.1]]]) </code></pre> <p>Now I want to get the elements in this fashion:</p> <pre><code>[[0.1, 0.3], [...
<p>The better Pythonic solution</p> <pre><code>&gt;&gt;&gt; train_predicteds[:,0,0] array([0.1, 0.3]) </code></pre>
python|list|numpy
4
15,929
56,258,174
Reshape and pad a tensor given a list of lengths
<p>I have given a 2d tensor <code>in</code> of shape <code>a x b</code> like the following (where <code>a = 9</code> and each of <code>A1</code>, <code>A2</code>, ..., <code>C2</code> represents a <code>b</code>-dimensional vector): </p> <p><a href="https://i.stack.imgur.com/EEdac.png" rel="nofollow noreferrer"><img s...
<p>Here is my implementation using <code>torch.nn.utils.rnn.pad_sequence()</code>:</p> <pre><code>in_tensor = torch.rand((9, 3)) print(in_tensor) print(36*'=') lengths = torch.tensor([3, 4, 2]) cum_len = 0 y = [] for idx, val in enumerate(lengths): y.append(in_tensor[cum_len : cum_len+val]) cum_len += val prin...
pytorch|tensor
2
15,930
56,199,021
Pairwise difference of MultiIndex column DataFrame
<p>I have a DataFrame with MultiIndex columns like the following:</p> <pre><code>columnIdx1 = ["M1", "M2", "M3", "M4"] columnIdx2 = ["pos", "neg"] df = pd.DataFrame(data=np.random.randn(1000, 8), columns=pd.MultiIndex.from_product([columnIdx1, columnIdx2])) </code></pre> <p>Then I calculate the mean of this with <cod...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>Series.unstack</code></a> for reshaping and then subtract columns:</p> <pre><code>df = df.mean().unstack() df['diff'] = df['neg'] - df['pos'] print (df) neg pos dif...
python|pandas
3
15,931
55,583,429
How to remove duplicates based on text similarity across rows in Pandas
<p>I have a dataset of news headlines. I'd like to remove duplicate or highly similar headlines based on textual similarity with headlines of the past ten days. For highly similar headlines, I want to keep the earliest. For example, I will keep <code>"SECTION:BUSINESS; Business; Events; Pg.2"</code> for only the <code>...
<p>Have you looked into the function pandas.Series.unique? It returns an array with no duplicates, and can handle strings. </p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unique.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.S...
python|pandas|pandasql
1
15,932
55,923,937
Concatenate Series in pandas throwing away overlapping indexes
<p>Suppose I have the following three Series with overlapping indexes</p> <pre><code>s1 = pd.Series(data=np.arange(5)) s2 = pd.Series(data=np.arange(5),index=np.arange(2,7)) s3 = pd.Series(data=np.arange(5),index=np.arange(5,10)) </code></pre> <p>I wish concatenate them into one series; however, I wish to have the da...
<p>Idea is use <code>concatenate</code> for flatten indices and values of <code>Series</code> and filter by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.duplicated.html" rel="nofollow noreferrer"><code>Series.duplicated</code></a> with inverted mask by <code>~</code>:</p> <pre><code...
pandas|numpy|dataframe|series
2
15,933
55,909,108
Python Pandas: create rank columns, move orginal column max rank
<p>I need to be able to<br> 1. calculate ranks for each column in all rows,<br> 2. the find the max column label of each row,<br> 3. and then in each row move the max ranked column of the original df. </p> <p>It is trivial to do when working only with the data in the original df. But if different ranking calls are nee...
<p>Iterate the rows and accumulate the values in an array:</p> <pre><code>maxVals = [np.nan]*3 for index, row in df1[pd.notna(df1['maxR'])].iterrows(): maxVals.append(df1.loc[index, row['maxR']]) df1['maxV'] = maxVals </code></pre> <p>Alternative: A less intuitive way might be to index <code>df1</code> usi...
python|pandas|rank
0
15,934
64,981,195
How to convert a Dataframe value stored as an array to a list
<p>I have a dataframe in which all of the values are stored as an array in one of the columns. I want to take this array and do the following:</p> <ul> <li>Remove all carriage returns from each value in the array</li> <li>Split each item in the array into a separate line.</li> </ul> <p>I have a dataframe that looks lik...
<p>For me working <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> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>DataFrame....
python|pandas
2
15,935
64,850,612
Condensing Wide Data Based on Column Name
<p>Is there an elegant way to do what I'm trying to do in Pandas? My data looks something like:</p> <pre><code>df = pd.DataFrame({ 'alpha': [1, np.nan, np.nan, np.nan], 'bravo': [np.nan, np.nan, np.nan, -1], 'charlie': [np.nan, np.nan, np.nan, np.nan], 'delta': [np.nan, 1, np.nan, np.nan], }) print(df)...
<p>We can use <code>DataFrame.melt</code> to un pivot your data, then use <code>sort_values</code> and <code>drop_duplicates</code>:</p> <pre><code>df = ( df.melt(var_name='position') .sort_values('value') .drop_duplicates('position', ignore_index=True) ) </code></pre> <pre><code> position value 0 brav...
pandas
3
15,936
64,663,382
Annormaly long time to do .to_csv
<p>I encounter a problem I never had before.</p> <p>I'm just trying to save a dataframe as a csv with .tocsv but after hours it is still running..</p> <p>My dataframe is all the post from stackoverflow for the last year and the tags associated. I used a neural network : SentenceBert to embedd each posts as vector. The ...
<p>A text CSV file with 1.2 million rows, each containing, say, 512 bytes of other data and a 768-item embedding in text format (assuming each number takes about 12 bytes to print out, delimiters included)</p> <pre><code>&gt;&gt;&gt; (768*12 + 512) * 1194445 11619560960 </code></pre> <p>will be about 11 gigabytes. Writ...
python|pandas
1
15,937
64,900,985
Pandas count number of occurrences of each value between ranges
<p>I have a dataset where I have age as a continuous variable and I want to county the number of occurrences of 1's and 0's in &quot;Mental Health&quot; for a number of age group ranges, e.g. 18-25, 26-33, and so on.</p> <p>A sample code is as below:</p> <pre><code>df = pd.DataFrame([[18, 1], [45, 1], [56, 0], [26, 0],...
<p>You want <code>pd.cut</code>. You can define arbitrary bins (I've used range below). This will cut the passed series, and you can count the distinct &quot;cut&quot; ranges to see how many rows fall therein:</p> <pre><code>df[&quot;age_range&quot;] = pd.cut(df.Age, bins=[0,18,25,33,99], right=False) df2 = df.groupb...
python|pandas|range
2
15,938
65,056,131
How to setup Keras Autoencoder and reshape() to process 224 x 224 jpg images using ImageDataGenerator?
<p>I am trying to apply a <a href="https://www.tensorflow.org/tutorials/generative/autoencoder" rel="nofollow noreferrer">Tensorflow Keras autoencoder implementation</a> to my own dataset of 224 x 224 images belonging to 40 classes, which I have setup like: <br/> <a href="https://i.stack.imgur.com/5DBDE.png" rel="nofol...
<p>The tutorial uses fashion MNIST grayscale images. You might be using rgb images.</p> <p>Since, the error states that it can't squeeze 3 values into 1, your image size should be 224 x 224 x 3. Third dimension denotes 3 values for rgb.</p> <p>Now, if colour is not important, you can preprocess your images to grayscale...
python|tensorflow|image-processing|keras|autoencoder
1
15,939
39,992,411
to_datetime Value Error: at least that [year, month, day] must be specified Pandas
<p>I am reading from two different CSVs each having date values in their columns. After read_csv I want to convert the data to datetime with the to_datetime method. The formats of the dates in each CSV are slightly different, and although the differences are noted and specified in the to_datetime format argument, the o...
<p>You can <code>stack</code> / <code>pd.to_datetime</code> / <code>unstack</code></p> <pre><code>pd.to_datetime(dte.stack()).unstack() </code></pre> <p><a href="https://i.stack.imgur.com/V9daD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/V9daD.png" alt="enter image description here"></a></p> <p><strong...
python|pandas|csv|datetime
23
15,940
39,901,209
Merge two vectors with alternate locations
<p>I have:</p> <pre><code>import numpy as np A = np.asarray([1,3,5,7,9]) B = np.asarray([2,4,6,8,10]) </code></pre> <p>I want to create:</p> <pre><code>C = np.asarray([1,2,3, 4,5,6,7,8,9,10]) </code></pre> <p>Is there a better way to do than to run a for loop</p>
<p>You can the <em>stack</em> arrays vertically using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html#numpy.vstack" rel="nofollow"><code>vstack</code></a>, <em>transpose</em> and then <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.ravel.html" rel="nofollow"><cod...
python|numpy
1
15,941
44,238,913
Showing one label on pie chart pandas
<p>Is there a way of showing just one set of label? At the moment it is looking very messy and I would like to have one set of label please. I did <code>label=None</code> and it turned off all the labels. <a href="https://i.stack.imgur.com/Aqif4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Aqif4.j...
<p>I think you need a bit change <a href="https://stackoverflow.com/questions/34034457/how-to-make-mxn-piechart-plots-with-one-legend-and-removed-y-axis-titles-in-matp">How to make MxN piechart plots with one legend and removed y-axis titles in Matplotlib</a>:</p> <pre><code>df = pd.DataFrame({'beer':[1,2,3], ...
pandas|dataframe|graph|label|pie-chart
3
15,942
41,003,040
TensorFlow - Unable to get Prediction
<p>I am trying to solve the <a href="https://www.kaggle.com/c/titanic" rel="nofollow noreferrer">Titanic Problem on Kaggle</a> and I am unsure of how to get the output for a given test data.</p> <p>I successfully train the network and call the method <code>make_prediction(x, test_x)</code></p> <pre><code>x = tf.place...
<p>I combined your <code>train_neural_network</code> and <code>make_prediction</code> function into one single function. Applying <code>tf.nn.softmax</code> to the model function would make the value range into from 0~1 (interpreted as probability), then <code>tf.argmax</code> extracts the column number with the higher...
python|tensorflow|neural-network|kaggle
1
15,943
66,327,866
How can I iterate over a pandas dataframe so I can divide specific values based on a condition?
<p>I have a dataframe like below:</p> <pre><code> 0 1 2 ... 62 63 64 795 89.0 92.0 89.0 ... 74.0 64.0 4.0 575 80.0 75.0 78.0 ... 70.0 68.0 3.0 1119 2694.0 2437.0 2227.0 ... 4004.0 4010.0 6.0 777 90.0 88.0 88.0 ... 71.0 67.0 ...
<p>I think loops are here slow, so better is use vectorizes solutions - select values greater like <code>1000</code> and divide:</p> <pre><code>df[df.gt(1000)] = df.div(100) </code></pre> <p>Or using <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mask.html" rel="nofollow noreferrer"...
python|pandas
1
15,944
66,008,109
Looping through dataframes
<p>I have 5 dataframes A through E and I'd like to apply the same process to all frames. I've executed a loop but it doesn't overwrite the original dataframes I'd like to change, they result as identical to the frames I've fed to the loop:</p> <pre><code>frames = [A,B,C,D,E] for df in frames: df = df[df.columns.dr...
<p>You can try following:</p> <pre><code>frames = [A,B,C,D,E] def update(df): df = df[df.columns.drop(list(df.filter(regex='Unnamed')))] # Drop columns with &quot;Unnamed&quot; in column name df = df.apply(lambda x: x.astype(str).str.upper()) # Convert columns to caps df['Unique Name'] = df['Name']...
python|pandas|loops
1
15,945
66,295,473
Understanding method build and input input_shape in keras
<p>I'm trying to understand a basic example in <a href="https://keras.io/getting_started/intro_to_keras_for_researchers/" rel="nofollow noreferrer">https://keras.io/getting_started/intro_to_keras_for_researchers/</a> in particular:</p> <pre><code>class Linear(keras.layers.Layer): def __init__(self, units): ...
<p><code>Build</code> is called when the object is created one time , input_shape because so often you dont know the input shape of your tensor in advance neither how much wight your layer needs, its pretty healthy to have it that way cuz the method <code>call</code> would be called everytime a forward propagation happ...
python|tensorflow|keras
0
15,946
52,891,636
Can tflite model implementation on FPGA
<p>I want to quantize the ssd-mobilenet model , then implementation on FPGA, now i use the ssd_mobilenet_v1_quantized_coco model <a href="http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v1_quantized_300x300_coco14_sync_2018_07_18.tar.gz" rel="nofollow noreferrer">http://download.tensorflow.org/mode...
<p>Currently Tensorflow only Supports android, ios and microcontrollers. as you need to synthese Hardware blocks in FPGA, you need to write inference of you network manually in c++ or rtl.</p>
fpga|tensorflow-lite
0
15,947
52,715,754
Maximum of 2 numpy unint8 arrays
<p>I want to get the maximum of 2 numpy uint8 arrays (0 to 255) but I want to exclude the 255 value.</p> <pre><code>x1 = np.array([[0, 1], [2, 255]], dtype=np.uint8) x1 = np.array([[2, 2], [255, 255]], dtype=np.uint8) result: array([[2, 2], [2, 255]], dtype=uint8) </code></pre> <p>How to do that efficiently ?</p>
<p>Here is a simple trick using over- and underflow.</p> <pre><code>&gt;&gt;&gt; np.maximum(x1+1, x2+1)-1 array([[ 2, 2], [ 2, 255]], dtype=uint8) </code></pre>
numpy|max|where
2
15,948
58,564,888
Parse Out Last Sequence Of Numbers From Pandas Column to create new column
<p>I have a dataframe with codes like the following and would like to create a new column that has the last sequence of numbers parse out.</p> <pre><code>array(['K9ADXXL2', 'K9ADXL2', 'K9ADXS2', 'IVERMAXSCM12', 'HPDMUDOGDRYL']) </code></pre> <p>So the new column would contain the following:</p> <pre><code>array([2,2...
<p>Sample data</p> <pre><code>df: codes 0 K9ADXXL2 1 K9ADXL2 2 K9ADXS2 3 IVERMAXSCM12 4 HPDMUDOGDRYL </code></pre> <p>Use <code>str.extract</code> gets digits at the end of string and passing to <code>pd.to_numeric</code></p> <pre><code>pd.to_numeric(df.codes.str.extract(r'(\d+$)')[0], ...
python|pandas
1
15,949
58,501,259
How to use np.where() function based on comparison between values of 2 columns i.e. Total_Summer and Total_Winter columns and 3 arguments?
<p>I tried the following code but it is not working</p> <pre><code>data['Better_Event'] = np.where(data['Total_Summer'], 'Summer', (np.where(data['Total_Winter'], 'Winter', (np.where(data['Total_Summer'], data['Total_Winter'], 'Both'))))) </code></pre> <p>Neither is the following working</p> <pre><code>ata['Better_E...
<p>If you want to do it in one line, you can use <code>pandas apply</code> with:</p> <pre><code>df['Better_Event'] = df.apply(lambda x: 'Both' if x['Total_Summer'] &gt; 0 and x['Total_Winter'] &gt; 0 else ('Summer' if x['Total_Summer'] &gt; 0 else ('Winter' if x['Total_Winter'] &gt; 0 else 'No')), axis=1) </code></p...
python|pandas|numpy
0
15,950
58,177,656
In python, the summarise (dplyr) function analogue
<p>I have a panda dataframe df and I would like group by a variable 'house' and do specific operations in three other variables: 'var1', 'var2' and 'var3'. Suposse the three variables are numeric and 'var1' taking values 1,2,3. </p> <pre><code>data = {'house':['A', 'B', 'A', 'A', 'B', 'B', 'B'], 'var1':[3, 0, 1, 3,4,5...
<p>You can do this using the <code>agg</code> method</p> <pre><code>(df.groupby(['house']).agg({'var1': lambda x: (x==3).sum(), 'var2': 'sum', 'var3': 'sum'}) .rename(columns={"var1": "new_var1", "var2": "new_var2", "v...
python|r|pandas
3
15,951
58,484,719
Tensor type error when federated learning
<p>I tried to use tensorflow federated learning tool for my data. I have two datasets (dataset and dataset2) obtained from csv files where first 15 column are features and the last column is the label. I converted my pandas dataframe to tensorflow dataset. However, at the iterator, there is a strange type error. I am...
<p>Looks like the call to <code>iterative_process.next(state, list)</code> is expecting the list of datasets (<code>list</code>) to be a list of <em>batched</em> datasets. The batch size can even be <code>1</code> if you prefer not to have multiple examples per batch.</p> <pre class="lang-py prettyprint-override"><cod...
python|pandas|dataframe|tensorflow|tensorflow-federated
2
15,952
69,110,475
pandas sort values after certain column
<p>i have following code</p> <pre><code>dataframe = pd.DataFrame(data=records) tabelle=dataframe.copy() print(tabelle[[&quot;date&quot;,&quot;kw_search&quot;,&quot;impressions&quot;]]) </code></pre> <p>with following results</p> <pre><code> date kw_search impressions 0 2021-02-...
<p>got the answer i forgot to set inplace=True code should be:</p> <pre><code>tabelle.sort_values(by=['impressions'],inplace=True) </code></pre>
python|pandas|sorting
1
15,953
69,218,118
Removing observation with min value in a column out of the dataframe one by one using loop in Python
<p>I have a dataframe &quot;data&quot; that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>f1</th> <th>f2</th> <th>f3</th> </tr> </thead> <tbody> <tr> <td>11</td> <td>34</td> <td>a</td> </tr> <tr> <td>14</td> <td>10</td> <td>a</td> </tr> <tr> <td>20</td> <td>12</td> <td>a<...
<p>In my solution ouput is list of DataFrames.</p> <p>If there are always unique values in column <code>f2</code> use loop by index values of sorted column and drop row by minimal value:</p> <pre><code>out = [] data1 = data.sort_values('f2') for i in data1.loc[data1['f3'] == 'a', 'f2'].index: data = data.drop(i) ...
python|pandas|dataframe|loops|min
1
15,954
61,163,971
Scraping Multiple Data Tables at once in Python
<p>I am using the following NCAA stats site and want to scrape data from it:</p> <p><a href="https://stats.ncaa.org/rankings/change_sport_year_div" rel="nofollow noreferrer">https://stats.ncaa.org/rankings/change_sport_year_div</a></p> <p><em>To get to the specific data I want to scrape, click the link, choose the sp...
<p>Inspecting your case, you should make a post request to the given url with some form data as follows:</p> <pre><code>sport_code: MBB academic_year: 2020.0 division: 3.0 ranking_period: 110.0 team_individual: T game_high: N ranking_summary: N </code></pre> <hr> <pre><code>sport_code=MBB&amp;academic_year=2020.0&am...
python|html|pandas|web-scraping|beautifulsoup
0
15,955
61,157,314
RuntimeError: Unknown device when trying to run AlbertForMaskedLM on colab tpu
<p>I am running the following code on colab taken from the example here: <a href="https://huggingface.co/transformers/model_doc/albert.html#albertformaskedlm" rel="nofollow noreferrer">https://huggingface.co/transformers/model_doc/albert.html#albertformaskedlm</a></p> <pre><code>import os import torch import torch_xla...
<p>Solution is here: <a href="https://github.com/pytorch/xla/issues/1909" rel="nofollow noreferrer">https://github.com/pytorch/xla/issues/1909</a> </p> <p>Before calling <code>model.to(dev)</code>, you need to call <code>xm.send_cpu_data_to_device(model, xm.xla_device())</code>:</p> <pre><code>model = AlbertForMasked...
nlp|pytorch|tpu|huggingface-transformers|tensorflow-xla
0
15,956
71,755,103
Create hundreds of TimeSeries & Train-/Testsets with loop or function
<h1>MWE</h1> <p>I have a dataset with a bit more than 1 Mio rows, containing several 100 TimeSeries. Here a simplified MWE of this data:</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;dtime&quot;:[&quot;2022-01-01&quot;, &quot;2022-01-02&quot;, &quot;2022-01-03&quot;, &quot;2022-01-01&quot;, &quot;2022-01...
<p>Did you tried to use a groupby over Type column in a loop :</p> <pre><code>train_list = [] for ts_type, group in df.groupby('Type'): series = TimeSeries.from_dataframe(group, &quot;dtime&quot;, &quot;Value&quot;, freq=&quot;D&quot;, fillna_value=0) train, val = series.split_before(pd.Timestamp(split_date)) ...
python|pandas|time-series
1
15,957
71,625,389
DataFrame contains a column of dates which are having these types: "'5-15-2019'" and 05152021.I want to extract pattern of it
<p>DataFrame contains dates which are having these types: &quot;21-10-2021&quot; and 29052021.I want to extract pattern of it. for example '5-15-2019',it needs to produce '%d-%m-%Y' '05152021' it needs to produce '%d%m%Y'</p> <p>i tried in this way:</p> <pre><code>search6=[] for val in list(df.apply(lambda x:re.search...
<p>You can use the internal pandas method <a href="https://github.com/pandas-dev/pandas/blob/v1.4.1/pandas/_libs/tslibs/parsing.pyx" rel="nofollow noreferrer"><code>pandas._libs.tslibs.parsing.guess_datetime_format</code></a>. Be careful, this is not part of the public API, so the function might change without any warn...
python|pandas|dataframe|date
0
15,958
42,274,756
How to analyse 3d mesh data(in .stl) by TensorFlow
<p>I try to write an script in python for analyse an .stl data file(3d geometry) and say which model is convex or concave and watertight and tell other properties...</p> <p>I would like to use and TensorFlow, scikit-learn or other machine learning library. Create some database with examples of objects with tags and in...
<p>You have to first extract "features" out of your dataset. These are fixed-dimension vectors. Then you have to define labels which define the prediction. Then, you have to define a loss function and a neural network. Put that all together and you can train a classifier.</p> <p>In your example, you would first need t...
python|machine-learning|3d|tensorflow|scikit-learn
2
15,959
42,384,857
How to combine two python matrices numpy
<p>I have this CSV "TEMP2" full of data showed below.</p> <pre><code> 1376460059,4,33.29,33.23,33.23,33.29,33.23,33.29,33.29,33.29,33.33,33.29,33.33,33.29,33.33,33.33,33.37,33.33,33.33,33.33,33.33,33.37,33.37,33.37,33.37 </code></pre> <p>My work so far is this:</p> <pre><code> import csv import numpy as np import ...
<p>for the first part of your question, you just have to create a tab before your first iteration.</p> <pre><code> res = [] for x in range(0, len(data)): tiempo = (((x*1.)/COLUMN_NUM) + 1376460059) tiempo = np.array(tiempo) print tiempo res.append(tiempo) </code></pre> <p>for the second part of...
python|numpy|matrix|concatenation
0
15,960
42,380,317
Tensorflow FIFOQueue '_4_batch_join/fifo_queue' is closed and has insufficient elements
<p>tensorflow version : 1.0.0</p> <pre><code> NUM_THREADS = 4 BATCH_SIZE = 32 csv_file_queue = tf.train.string_input_producer(csv_files, shuffle=False) jpg_file_queue = tf.train.string_input_producer(jpg_files, shuffle=False) data_batch_list = [read_data(csv_file_queue, jpg_file_queue) for _ in rang...
<p>This probably happens when preparing the last batch. Add <code>allow_smaller_final_batch=True</code> to your <code>train.batch_join</code> invocation: from the documentation:</p> <blockquote> <p>If allow_smaller_final_batch is True, a smaller batch value than batch_size is returned when the queue is closed and ...
tensorflow
0
15,961
69,726,595
Null dataframe in statistic function
<p>I'm having an issue with a function to extract main statistics from a dataframe: median, std, kurtosis, etc.</p> <p>It keeps returning null, and i can't figure out why. My code is as below:</p> <pre><code>import pandas as pd df = pd.read_excel(&quot;file.xlsx&quot;) def estatistics_from_df(df): df_stats = pd.D...
<p>Each of your statistics functions returns a series with the index as the column names of the DataFrame. You should therefore set the index in the first line of your function.</p> <p>Try:</p> <pre><code>def estatistics_from_df(df): df_stats = pd.DataFrame(index=df.columns) df_stats['Colunas'] = df.columns ...
python|pandas|dataframe|nan
3
15,962
69,867,311
How to change the structure of a pd DataFrame adding row values to columns?
<p>I have the following data frame</p> <pre><code>df = pd.DataFrame({'Date': ['2020-01-01', '2020-10-01', '2021-01-01', '2021-10-01'], 'ID': [101, 101, 102, 102], 'number': [10, 10, 11, 11]}) # currently looking like this Date ID number 0 2020-01-01 101 10 1 2020...
<p>We can use <a href="https://pandas.pydata.org/docs/user_guide/groupby.html#named-aggregation" rel="nofollow noreferrer">Named Aggregation</a> with <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.aggregate.html" rel="nofollow noreferrer">Groupby aggregate</a> to get the <cod...
python|pandas|dataframe
3
15,963
69,863,785
Only keep the top N values of each row in dataframe and set other to zero
<p>I am trying to keep the top 3 values for each date/row and set every other value to zero.</p> <p>I created a sample dataframe:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({ 'Date':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04'], '01K W':[0, 1.2, 0.3, 2], '02K W':[0.5, 2, 1.4, 3], ...
<h2><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rank.html" rel="nofollow noreferrer"><code>DataFrame.rank</code></a></h2> <p>Rank the rows along the columns axis in descending order, then <code>mask</code> the values which have rank <code>&gt; 3</code></p> <pre><code>df1.mask(df...
python|pandas|apply
2
15,964
43,306,291
Find the nearest nonzero element and corresponding index in a 2d NumPy array
<p>Let's say I have a 2d array named <code>array</code> and a 2d index:<code>(x,y)</code> and I want to get the nearest nonzero element to <code>(x,y)</code>, and get the corresponding index of the element in <code>np.nonzero(array)</code></p>
<p><strong>Approach #1 :</strong> Here's one approach -</p> <pre><code>def nearest_nonzero_idx(a,x,y): idx = np.argwhere(a) # If (x,y) itself is also non-zero, we want to avoid those, so delete that # But, if we are sure that (x,y) won't be non-zero, skip the next step idx = idx[~(idx == [x,y]).all(1)...
python|numpy
6
15,965
72,449,311
Compute number of missing values by group on another dataframe column based on conditions
<p>Let's say I have the following data:</p> <pre><code>df=pd.DataFrame({&quot;id&quot;:[1,1,1,2,2,3,4], &quot;date&quot;:[2019,2019,2020,2020,2020,2020,2021], &quot;subgroup&quot;:[&quot;con&quot;,&quot;ind&quot;,&quot;ind&quot;,&quot;con&quot;,&quot;ind&quot;,&quot;ind&quot;,&quot;ind&quot;],...
<pre class="lang-py prettyprint-override"><code>df['counter'] = 0 df.loc[(df.subgroup=='ind') &amp; (df.value.isna()), 'counter'] = 1 df['goal'] = df.groupby([&quot;id&quot;,&quot;date&quot;])['counter'].transform('sum') df = df.drop(columns='counter') </code></pre> <p>but as Alollz pointed out your sample code does n...
python|pandas|dataframe|group-by
1
15,966
72,253,547
Data type preference for training CNN?
<p>I originally was using input data of int8 type ranging from 0-255 before learning that standardizing and normalizing should increase learning speeds and accuracy. I attempted both, with and without a mean of zero, and none of these methods improved learning speed or accuracy for my model relative to 0-255, int8 appr...
<p>You should always normalize/standardize your images before training. There are many post about this topic. Here are a few</p> <p><a href="https://stats.stackexchange.com/questions/185853/why-do-we-need-to-normalize-the-images-before-we-put-them-into-cnn">normalize-the-images-before-we-put-them-into-cnn</a></p> <p><a...
python|tensorflow|conv-neural-network|training-data|efficientnet
0
15,967
45,347,275
What is the difference between tf.gradients and tf.train.Optimizer.compute_gradient?
<p>It seems that <code>tf.gradients</code> allows to compute also Jacobians, i.e. the partial derivatives of each entry of one tensor wrt. each entry of another tensor, while <code>tf.train.Optimizer.compute_gradient</code> only computes actual gradients, e.g. the partial derivatives of a scalar value wrt. each entry o...
<p><a href="https://www.tensorflow.org/api_docs/python/tf/gradients" rel="noreferrer"><code>tf.gradients</code></a> does not allow you to compute Jacobians, it aggregates the gradients of each input for every output (something like the summation of each column of the actual Jacobian matrix). In fact, there is no "good"...
tensorflow
5
15,968
62,712,989
update pandas dataframe with adding new rows - how?
<p>Let we have two Python pandas dataframes</p> <p>df1:</p> <pre><code>key1 key2 volume1 volume2 111 bbb fff ggg 222 bbb hhh hhh 333 aaa fff hhh </code></pre> <p>df2:</p> <pre><code>key1 key2 volume1 volume2 222 bbb hhh HHH 333 aaa fff GGG 444 ccc ggg hhh </code></pre> <p>How t...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> to <code>outer</code> merge the dataframes <code>df1</code> and <code>df2</code> on columns <code>key1, key2</code>, then use <a href="https://pandas.pydata....
python|pandas|dataframe|join
0
15,969
62,608,902
Replace not working for multiple strings replacement when each row is a list
<p>I am trying to build a function which replaces <code>http</code>, <code>https</code>, <code>com</code> and <code>www</code> from my dataframe.</p> <p><strong>df</strong></p> <pre><code>content Col2 Col3 Col4 [www,roger, that,com, http, great, hi, www] ...
<p>You can do a simple list comprehension on the column:</p> <pre><code>rep = ['http', 'https', 'www', 'com'] df['col2'] = df['col1'].apply(lambda x: [i for i in x if i not in rep]) col1 col2 0 [www, roger, that, com, http, great, hi, www] [roger, that...
python|pandas
1
15,970
62,726,958
create new columns on pandas based on one column elements
<p>I have a dataframe with column like this:</p> <pre><code> column_1 0 0.25 / 0 / 0.25 / -0.25 1 -0.25 / 0 /1 2 0 / -0.5 / -0.25 3 1/ 0.25 / -0.75 </code></pre> <p>each row is made of chain of consecutive numbers (separated by /) I want to cr...
<p>Assuming <code>column_1</code> has data in string datatype</p> <pre><code>df['new_column_1st_element'] = df.apply(lambda row: row['column_1'].split('/')[0], axis = 1) </code></pre> <p>Similarly this can be done for the <code>new_column_last_element</code></p>
python|pandas|dataframe
1
15,971
54,295,812
np.vectorize and np.apply_along_axis passing same argument twice to mapping function
<p>I want to map a function <code>f</code> over an array of strings. I construct a vectorized version of <code>f</code> and apply it to my array. But the first element of the array gets passed twice:</p> <pre><code>import numpy as np def f(string): print('called with', string) a = np.array(['110', '012']) fv = ...
<p>From the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>The data type of the output of <em>vectorized</em> is determined by calling the function with the first element of the input. This can be avoided by specifying the <...
python|numpy
4
15,972
71,289,824
Using custom trained Keras model with Sagemaker endpoint results ModelError: An error occurred (ModelError) when calling the InvokeEndpoint operation:
<p>I am trying to predict by loading pre-trained model in sagemaker, but I am getting the below error</p> <blockquote> <p>ModelError: An error occurred (ModelError) when calling the InvokeEndpoint operation: Received client error (400) from primary with message &quot;{ &quot;error&quot;: &quot;Session was not created ...
<p>Is all of this code in a notebook? You want to make sure you are properly tarring your model artifacts and inference code. Make sure that you have your metadata for your saved model stored properly and also if you have an inference script with inference functions (handling pre and post processing) this should be wra...
amazon-web-services|tensorflow|amazon-s3|keras|amazon-sagemaker
0
15,973
71,374,103
Fill null and next value with avarge value
<p>i work with customers consumptions and sometime didn't have this consumption for month or more so the first consumption after that need to break it down into those months example</p> <pre><code>df = pd.DataFrame({'customerId':[1,1,1,1,1,1,1,2,2,2,2,2,2,2], 'month':['2021-10-01','2021-11-01','2021-...
<p>You can try something like this:</p> <pre><code>df = pd.DataFrame({'customerId':[1,1,1,1,1,1,1,2,2,2,2,2,2,2], 'month':['2021-10-01','2021-11-01','2021-12-01','2022-01-01','2022-02-01','2022-03-01','2022-04-01','2021-10-01','2021-11-01','2021-12-01','2022-01-01','2022-02-01','2022-03-01','2022-04-...
python-3.x|pandas|dataframe
1
15,974
71,294,473
Python: Two Concenctric Circles - check if inside
<p>Let's say I have a system of two concenctric circles and a numpy array with some coordinates. I now want to check if the coordinates are inside the ring and if so I want to print the respective values for example [6, 0], yes? How can I do this? This is what I have done so far but this leads to the following error: T...
<p>Your solution was going in the right direction till you passed the points as scalars and they were actually 2D numpy arrays. I have rewritten your code with some modifications and clarifications as to what does what.</p> <pre><code>import math import numpy as np # points to check positions = np.array([[2.5, 8], [3...
python|python-3.x|numpy
2
15,975
52,440,585
Panda pivot table margins only on row
<p>Anyone knows how to do margins on panda pivot table only on row? current setting will calculate both row and column margin Thanks !</p>
<p>You can remove them by indexing with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="noreferrer"><code>DataFrame.iloc</code></a>:</p> <pre><code>df = pd.DataFrame({ 'A': ['a','b','a','a'], 'B': ['a','d','d','b'] }) df = pd.crosstab(df['A'], df['B'], margins=T...
python|pandas|pivot
5
15,976
60,658,894
TensorFlow strange memory usage
<p>I'm on an Ubuntu 19.10 machine (with KDE desktop environment) with 8GB of RAM, an i5 8250u and an MX130 gpu (2GB VRAM), running a Jupyter Notebook with tensorflow-gpu. </p> <p>I was just training some models to test their memory usage, and I can't see any sense in what I'm looking at. I used KSysGUARD and NVIDIA S...
<p>Tensorflow by default allocates all available VRAM in the target GPU. There is an experimental feature called memory growth that let's you control that, basically stops the initialization process from allocating all VRAM and does it when there is a need for it. </p> <p><a href="https://www.tensorflow.org/api_docs/...
deep-learning|tensorflow|gpu|memory
1
15,977
60,387,748
How to set n consecutive elements with a non-zero cumulative sum to one and the rest to zero in numpy?
<p>I have a 1D numpy array of 1's and 0's. I need to change it to an array according to these conditions.</p> <ol> <li>If the number of 0's between two 1's is less than 3, all of those 0's should be set to 1.</li> <li>In the resulting array, if the number of consecutive 1's are less than 4, all of those 1's should be ...
<p>If you use core Python?</p> <pre><code>l = [0,1,1,1,0,0,0,1,1,0,0,1,1,0,0,0,0,1,0] def split(l): res = [] subres = [l[0]] for i in range(len(l) - 1): if l[i] == l[i + 1]: subres.append(l[i + 1]) else: res.append(subres) subres = [l[i + 1]] res.ap...
python|arrays|python-3.x|numpy
1
15,978
72,761,882
Pandas: changing cell value to np.nan changes from categorical data to float
<p>I'm trying to convert some cells in a categorical column to NaN, but when I do it the column type changes to float. How can I keep the column as a categorical data?</p> <p>Here is a working code:</p> <pre><code>import numpy as np import pandas as pd from pandas.api.types import CategoricalDtype s = pd.Series([1, 2, ...
<p>You can do it if you use a vectorial approach to change the data. Also to be able to compare the values, the categorical must be ordered:</p> <pre><code>import numpy as np import pandas as pd from pandas.api.types import CategoricalDtype s = pd.Series([1, 2, 2, 3, 2]) cat_type = CategoricalDtype(categories=[1, 2, 3]...
python|pandas|series|categorical-data
1
15,979
72,693,295
Access a pandas group as new data frame
<p>I am new to data analysis with pandas/pandas, coming from a Matlab background. I am trying to group data and then process the individual groups. However, I cannot figure out how to actually access the grouping result.</p> <p>Here is my setup: I have a pandas dataframe <code>df</code> with a regular-spaced DateTime i...
<p>Expand your groups into a dictionary of dataframes:</p> <pre><code>data = dict(list(df.groupby(df.index.date.astype(str)))) </code></pre> <pre><code>&gt;&gt;&gt; data.keys() dict_keys(['2021-01-01', '2021-01-02']) &gt;&gt;&gt; data['2021-01-01'] value timestamp 2021-01-01...
python|pandas|dataframe|pandas-groupby
2
15,980
59,550,804
melt column by substring of the columns name in pandas (python)
<p>I have dataframe:</p> <pre><code> subject A_target_word_gd A_target_word_fd B_target_word_gd B_target_word_fd subject_type 1 1 2 3 4 mild 2 11 12 ...
<p>Here is my way using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html" rel="nofollow noreferrer"><code>melt</code></a> and <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...
pandas|dataframe|data-science|melt|data-munging
1
15,981
61,758,066
Best way to iterate over rows in large csv file in python, write to new one
<p>I am a relative python newbie trying to efficiently look through a large csv file of ~8 million rows. </p> <p>I have a csv of 6 columns:</p> <pre><code>+-------+-------+--------+-------+--------+----------+ | Gene1 | Start | End | Gene2 | Start | End | +-------+-------+--------+-------+--------+----------...
<p>Many Pandas operations are vectorized. It would be difficult to write something yourself, quickly, that would be more performant:</p> <pre><code>df = pd.read_csv('large.csv') Gene1 Start End Gene2 Start.1 End.1 0 gyrA 33 193 dnaB 844 965 1 rpoS 152 190 ldh 200 264 2 gbpC 456...
python|pandas|loops|csv
0
15,982
54,858,623
How to down sample an array in python without a for loop
<p>Is there a <em>'pythonic'</em> way to cleanly down-sample without multiple for loops? </p> <p>This example below is the type of for loop I wish to get rid of.</p> <h1>Minimum working example:</h1> <pre><code>import numpy as np unsampled_array = [1,3,5,7,9,11,13,15,17,19] number_of_samples = 7 downsampled_array = ...
<p>If you want "real" downsampling, where each value is the mean of k values, you can use </p> <pre><code>unsampled_array.reshape(-1, k).mean(1) </code></pre> <p>Make sure unsampled_array is a np.array. In your case, k=2. That will give you:</p> <blockquote> <p>[ 2. 6. 10. 14. 18.]</p> </blockquote> <p><strong>...
python|arrays|numpy|downsampling
3
15,983
54,728,956
How do I iterate through a list within a list and then create a csv at the end?
<p>I have a code that produces scraped data and puts it in 4 lists of data but I want to put them all together as a data frame and output the final result as a csv. Also the guest column contains multiple people so how do I iterate through that list? Not sure why my current code isn't working but its probably something...
<p>You have a few errors. Here is a fixed version of your code.</p> <pre><code>import requests import pandas as pd from bs4 import BeautifulSoup import numpy as np df = pd.DataFrame(columns=(['NoInSeason', 'Guests', 'Winner', 'OriginalAirDate'])) page = requests.get("https://en.wikipedia.org/wiki/List_of_QI_episodes"...
python|pandas|dataframe|web-scraping|beautifulsoup
1
15,984
54,710,099
Understanding Sparse Data Structures in Pandas
<p>I'm having to handle dataframes that are bigger than the RAM on my local machine. I'm therefore looking at using sparse data structures.</p> <p>The need initially came about when creating dummy variables and from the manual, I noticed that pd.get_dummies() has a <code>sparse = True</code> option and so I used that ...
<p>As I can see in the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sparse.html" rel="nofollow noreferrer">pandas.DataFrame</a> documentation. You have to specify the value to omit in the representation with <code>fill_value</code>. By default <code>fill_value = None</code>.</...
python|pandas
3
15,985
49,502,634
How to save parsed dates pandas dataframe?
<p>I'm reading a CSV file and parsing dates.</p> <pre><code>train = pd.read_csv('sales_train.csv', parse_dates=['date']) date 2015-10-10 2015-09-10 2015-10-14 2015-10-22 2015-03-10 </code></pre> <p>At this point the dataframe is correctly parsed. If I need to access to same dataframe another day I don't want to pa...
<p>Could you post some of your code and example data?</p> <p>If you're running something like <code>pd.to_datetime(df['date'])</code> but not saving it anywhere, try:</p> <pre><code>df['date'] = pd.to_datetime(df['date']) </code></pre>
pandas|csv|dataframe
0
15,986
73,196,737
Model does not train properly when explicitly applying the gradients
<p>I’m trying to constrain the weight of my model by explicitly applying the gradients; shower, this is not working and I can’t figure out why.</p> <p>I’m defining the model with the following function:</p> <pre><code>def init_model(num_hidden_layers=2, num_neurons_per_layer=64): model = tf.keras.Sequential() m...
<p>Finally, I found that expanding the dimension of the targets as follows:</p> <pre><code>u_train = tf.expand_dims(u_train,axis=-1) u_test = tf.expand_dims(u_test,axis=-1) </code></pre> <p>the model training properly and the loss functions are correctly evaluated. <code>u_train</code> and <code>u_test</code> previousl...
python|keras|tensorflow2.0|model-fitting
0
15,987
67,526,433
Caused by: java.lang.IllegalArgumentException: Label number 6 mismatch the shape on axis 1 afted deploying my own model
<p>Hello I am trying to build an android image classification project with tflite model to classify chess pieces. I have trained my model and deployed the tflite model as well as the label map in the assets folder in my android project but I get this error: <code>Caused by: java.lang.IllegalArgumentException: Label num...
<p>Can you double check the 4 outputs in your model (<a href="https://www.pastefile.com/a44ydg" rel="nofollow noreferrer">https://www.pastefile.com/a44ydg</a>) to see if shapes match the 6 labels?</p> <p>I use <code>netron</code> to inspect your <a href="https://github.com/lutzroeder/netron" rel="nofollow noreferrer">m...
android|tensorflow|tensorflow2.0|tensorflow-lite
1
15,988
60,063,797
Not understanding the data flow in UNET-like architetures and having problems with the output of the Conv2DTranspose layers
<p>I have a problem or two with the input dimensions of modified U-Net architecture. In order to save your time and better understand/reproduce my results, I'll post the code and the output dimensions. The modified U-Net architecture is the MultiResUNet architecture from <a href="https://github.com/nibtehaz/MultiResUNe...
<p>U-Net family of models (such as the MultiResUNet model above) follow an encoder-decoder architecture. <strong>Encoder</strong> is a down-sampling path with feature extraction whereas the <strong>decoder</strong> an upsampling one. Feature maps from encoder are <strong>concatenated</strong> at the decoder through <em...
tensorflow|keras|deep-learning|concatenation|conv-neural-network
5
15,989
65,335,024
Trying to understand PyTorch SmoothL1Loss Implementation
<p>I have been trying to go through all of the loss functions in PyTorch and build them from scratch to gain a better understanding of them and I’ve run into what is either an issue with my recreation, or an issue with PyTorch’s implementation.</p> <p>According to Pytorch’s documentation for SmoothL1Loss it simply stat...
<p>The description in the documentation is correct. Your implementation wrongly applies the case selection on the <em>mean</em> of the data. It should be an element-wise selection instead (if you think about the implementation of the vanilla L1 loss, and the motivation for smooth L1 loss).</p> <p>The following code giv...
python|machine-learning|pytorch
2
15,990
65,088,194
numpy reshape function - Type-error: order must be str, not int
<p>I met this type of error:</p> <pre><code>Traceback (most recent call last): File &quot;BoxMuller.py&quot;, line 34, in &lt;module&gt; y = boxmuller(1000) File &quot;BoxMuller.py&quot;, line 31, in boxmuller y = np.reshape(str(y),2*str(n),1) File &quot;&lt;__array_function__ internals&gt;&quot;, line 5,...
<p>Order is the third parameter in the <code>numpy.reshape</code>. I think what you are trying to do is pass the shape tuple as second argument. See <a href="https://numpy.org/doc/stable/reference/generated/numpy.reshape.html#numpy-reshape" rel="nofollow noreferrer">doc</a>. Try this <code>y = np.reshape(y,(2*n,1))</co...
python|string|numpy
3
15,991
64,162,962
Multiply many columns by one column in dask
<p>I want to multiply roughly 50,000 columns with one other column in a large dask dataframe (<code>6_500_000 x 50_002</code>). The solution, using a for loop, works but is painfully slow. Below I tried two other appraoches that failed. Any advice is appreciated.</p> <p><strong>Pandas</strong></p> <pre><code>import pan...
<p>You basically had it for pandas, just <code>multiply()</code> isn't inplace. I also changed to using <code>.loc</code> for all but one column so you don't type 50,000 column names :)</p> <pre><code>import pandas as pd df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9]}) df.loc[:, df.columns != 'c']=df.loc[:, d...
pandas|dask
1
15,992
64,173,248
How does the `tfds.features.text.SubwordTextEncoder` create word encoding?
<p>I'm currently doing a tensorflow transformer <a href="https://www.tensorflow.org/tutorials/text/transformer" rel="nofollow noreferrer">tutorial</a> for sequence to sequence translation. At the beginning of the tutorial the class <a href="https://www.tensorflow.org/datasets/api_docs/python/tfds/features/text/SubwordT...
<p>I have added one more statement <code>len(tokenizer_en.decode([ts])</code> in the <code>print</code> statement to see length and I tried the below example -</p> <p><strong>Example:</strong></p> <pre><code>sample_string2 = 'is is is is is is' tokenized_string2 = tokenizer_en.encode(sample_string2) print(tokenized_str...
python|tensorflow|deep-learning|token
1
15,993
63,937,543
TypeError: unhashable type: 'numpy.ndarray' - Tensor Flow - Numpy
<pre><code>import matplotlib.pyplot as plt x_arr = np.arange(-2, 4, 0.1) g2 = tf.Graph() with tf.Session(graph = g2) as sess: new_saver = tf.train.import_meta_graph( &quot;./trained-model.meta&quot;) new_saver.restore(sess, &quot;./trained-model&quot;) y_arr = sess.run(&quot;y_hat:0&quot;, ...
<p>You need to convert <code>x_arr</code> into a tensor type. You can do this by <code>tf.convert_to_tensor(x_arr)</code>.</p> <p>Source: <a href="https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor" rel="nofollow noreferrer">convert_to_tensor documentation</a></p>
python|numpy|tensorflow
0
15,994
64,028,921
Plot images from numpy.ndarray data
<p>I have a column['signal'] which composed of 500 ndarray data in each row. The length of each row is same. I would like to pick one row and plot it into picture. I tried something like data.reshape((1,-1)), but it did not work. I found many solutions on the net, but more error messages appeared. So how can I:</p> <o...
<p>Your data seems to be in string format, so try to convert before reshaping:</p> <pre><code>import numpy as np data = [' 19.35983', ' 19.33365', ' 19.30945', ' 19.3211'] lst = [float(item) for item in data] array = np.reshape(lst, (2,2)) </code></pre>
python|pandas|matplotlib|image-processing|numpy-ndarray
1
15,995
63,062,741
Pytorch and Torchvision are compiled different CUDA versions
<pre><code>RuntimeError: Detected that PyTorch and torchvision were compiled with different CUDA versions. PyTorch has CUDA Version=10.2 and torchvision has CUDA Version=10.1. Please reinstall the torchvision that matches your PyTorch install. </code></pre> <p>I am trying to run YOLACT on my Google Colab and found this...
<p>You need to upgrade your <code>torchvision</code> to one compiled with CUDA 10.2:</p> <pre><code>pip install --upgrade torchvision&gt;=0.6.0 </code></pre> <p>or, if you're using Conda:</p> <pre><code>conda install pytorch torchvision cudatoolkit=10.2 -c pytorch </code></pre> <p>Check <a href="https://github.com/pyto...
pytorch|torchvision
1
15,996
63,098,174
Split and create new dataframe based on WeekDays from existing dataframe
<p>I need to split the dataframe based on weekdays,<br /> The actual dataframe looks like this,</p> <pre><code>df = pd.DataFrame({'values': [10,5,30,44,52,6,7,85,9,1,1,1,13,14,1,16]}) df['weekdays'] = ['Monday','Tuesday','Wednesay','Thursday','Friday','saturday','sunday', 'Tuesday','Wednesay','Thursday','Friday...
<p>Create a grouper <code>grp</code> using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift.html" rel="nofollow noreferrer"><code>Series.shift</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>Se...
python|pandas|pandas-groupby|data-science
3
15,997
62,948,525
Change default weights on pretrained models
<p>I am working on a MobileNet model pretrained on imagenet weights, I would like to run it on coco weights. How can I change the default weights on pretrained models?</p>
<p>Most of the pre-trained model when you apply transfer learning comes with an argument e.g. <code>--weights</code> to run the model, just look for it and pass the coco weights as parameter</p>
tensorflow|machine-learning|keras|deep-learning
0
15,998
61,568,665
TF2: Compute gradients in keras callback in non-eager mode
<p>TF Version: 2.2.0-rc3 (in Colab)</p> <p>I am using the following code (from <a href="https://stackoverflow.com/questions/59313711/tf-keras-get-computed-gradient-during-training">tf.keras get computed gradient during training</a>) in a callback to compute gradients for all parameters in a model.</p> <pre><code>def ...
<p>Here is the end-to-end code to capture the gradient using the keras backend. I have called the gradient capturing function from callbacks of model.fit to capture the gradient after end of every epoch. <strong>This code is Compatible in both tensorflow 1.x and tensorflow 2.x versions and also I have ran it in colab.<...
tensorflow|google-colaboratory|tensorflow2.0
2
15,999
61,368,851
How to rotate seaborn barplot x-axis tick labels
<p>I'm trying to get a barplot to rotate it's X Labels in 45° to make them readable (as is, there's overlap).</p> <p><code>len(genero)</code> is 7, and <code>len(filmes_por_genero)</code> is 20</p> <p>I'm using a MovieLens dataset and making a graph counting the number of movies in each individual genre. Here's my code...
<ul> <li>Data from <a href="http://files.grouplens.org/datasets/movielens/ml-25m.zip" rel="nofollow noreferrer">MovieLens 25M Dataset</a> at <a href="https://grouplens.org/datasets/movielens/" rel="nofollow noreferrer">MovieLens</a></li> </ul> <pre class="lang-py prettyprint-override"><code>import pandas as pd import m...
python|pandas|matplotlib|seaborn
15