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
365,900
55,515,194
Can't access Oracle database using sqlalchemy
<p>I'm aware that this one has been asked several times - particularly in <a href="https://stackoverflow.com/questions/48951981/sqlalchemy-fails-to-connect-but-cx-oracle-succeeds">this question</a>, but I have not managed to solve my problem. Both snippets below have cx_Oracle and sqlalchemy installed</p> <pre><code>i...
<p>Your plain cx_Oracle connect string is different from the one for sqlalchemy. Note that sqlalchemy uses <code>cx_Oracle.makedsn()</code>. So if you have this connect syntax with plain cx_Oracle:</p> <pre><code>cx_Oracle.connect('myuser/mypassword@myhost:myport/myservice') </code></pre> <p>you would need this synta...
python-3.x|pandas|oracle11g|sqlalchemy|cx-oracle
0
365,901
55,549,214
how to set the index as character for pandas
<p>I am trying to create a pandas df like this <a href="https://stackoverflow.com/a/50274029/11074017">post</a>.</p> <p><a href="https://i.stack.imgur.com/uurUO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uurUO.png" alt="enter image description here"></a></p> <pre><code>df = pd.DataFrame(np.ara...
<p>Use <code>df.index</code>:</p> <pre><code>df.index=['A', 'B', 'C'] print(df) 1 2 3 A 0 1 2 B 3 4 5 C 6 7 8 </code></pre> <p>A more scalable and general solution would be using list-comprehension</p> <pre><code>df.index = [chr(ord('a') + x).upper() for x in df.index] print(df) 1 2 3 A 0 1 2...
python|pandas
0
365,902
55,144,904
How to do backprop in Pytorch (autograd.backward(loss) vs loss.backward()) and where to set requires_grad=True?
<p>I have been using Pytorch for a while now. One question I had regarding backprop is as follows:</p> <p>let's say we have a loss function for a neural network. For doing backprop, I have seen two different versions. One like:</p> <pre><code>optimizer.zero_grad() autograd.backward(loss) optimizer.step() </code></pre...
<p>so just a quick answer: both <code>autograd.backward(loss)</code> and <code>loss.backward()</code> are actually the same. Just look at <a href="https://pytorch.org/docs/master/_modules/torch/tensor.html#Tensor.backward" rel="nofollow noreferrer">the implementation</a> of <code>tensor.backward()</code> (as your loss ...
neural-network|deep-learning|pytorch|backpropagation
1
365,903
55,439,420
Is there an efficient way to select multiple rows in a large pandas data frame?
<p>I am working on a large pandas adatframe with about 100 million rows and 2 columns. I want to iterate over the dataframe and efficiently set a third column depending on the values of col1 and col2. This is what I am currently doing -</p> <pre><code>df[col3] = 0 for idx, row in df.iterrows(): val1 = row[col1] ...
<p>My solution would be to merge the frame to itself (merging column 2 to column 1) and then checking if the other two columns would be identical: that would mean the reverse also exists:</p> <pre><code>df2 = df.merge(df, how='left', left_on='col2', right_on='col1') df['rev_exists'] = (df2['col1_x'] == df2['col2_y'])....
python|pandas|numpy|dataframe
1
365,904
55,261,132
Assign values to python list specific position
<p>I am newbie in Python and maybe my problem is very simple.</p> <p>I have created a list of 250 zeros called <em>x</em>, <code>x = np.zeros(250)</code>, and I have a loop where I perform some calculations, at each iteration I produce two x's for example in the first iteration the x[0] and x[1] and so on in a list ca...
<p>As mentioned in @IAmVisco's answer, chained assignment will work.</p> <p>However, to go into the reason your code doesn't:</p> <p>When you type something like <code>x[i, i+1]</code>, Python understands the value in the square brackets as a <code>tuple</code>, and therefore actually attempts to execute <code>x[(i, ...
python|list|numpy
1
365,905
55,502,523
How to add header/columns to already existing pandas script
<p>How do I add headers to the script below, using pandas? Headers/columns = Date,B1,B2,B3.</p> <pre><code>from random import randint import pandas_datareader.data as web import pandas as pd import datetime as dt import itertools as it import numpy as np import csv start = dt.datetime(1996, 12, 16) end = dt.datetime(...
<p>Do you mean changing the column names? Because you can do that by:</p> <pre class="lang-py prettyprint-override"><code>df = df.columns(['Date','B1','B2','B3']) </code></pre> <p>Hope that answers your question.</p>
python|pandas|header
0
365,906
55,246,726
Sort by columns and only keep the first line until next value in column 1
<p>I have a file with roughly 10m lines. Each line is most likely unique, but I'm sorting the file by column 1 then 2 then 3. </p> <pre><code>Column 1 = CODE Column 2 = DATE Column 3 = AMOUNT </code></pre> <p>I only want to keep the first line until the next date and so on. Below is an example of what I have and what...
<p>try groupby and then first:</p> <pre><code>a.groupby([data.columns[0],data.columns[1]], as_index=False).first() </code></pre>
python|pandas|sorting|duplicates
2
365,907
55,266,499
pandas groupby conditional row sum
<p>I have a data frame like below:</p> <pre><code>df = pd.DataFrame({'col_1': [2,2,2,3,3,3,3], 'col_2': [1,2,3,1,2,3,4], 'col_3':['A','A','A','B','B','B','B']}) col_1 col_2 col_3 0 2 1 A 1 2 2 A 2 2 3 A 3 3 1 B 4 3 ...
<p>just do the conditional math ahead of time.</p> <pre><code>In [46]: df = pd.DataFrame({'col_1': [2,2,2,3,3,3,3], : 'col_2': [1,2,3,1,2,3,4], : 'col_3':['A','A','A','B','B','B','B']}) In [47]: df['cond_val'] = (df.col_1 &gt;= df.col_2) * df.col_2 In [48]: df Out[...
python|pandas|apply|pandas-groupby
0
365,908
55,417,868
Keras repeat elements throwing ValueError List argument 'indices' to 'SparseConcat' Op with length 0 shorter than minimum length 2
<p>I am trying to implement the code for Unsupervised Aspect Extraction from the code available <a href="https://github.com/ruidan/Unsupervised-Aspect-Extraction" rel="nofollow noreferrer">here</a>. <a href="https://www.comp.nus.edu.sg/~leews/publications/acl17.pdf" rel="nofollow noreferrer">Link</a> to the paper<br> W...
<p>I used to have this problem</p> <p><code>AttributeError: module 'keras.backend' has no attribute 'image_dim_ordering'</code>,</p> <p>So I have to modify the<br> <code>K.image_dim_ordering() == 'th'('tf') ==&gt; K.image_data_format() == 'channels_first'(channels_last)</code></p> <p>after that, I met the same prob...
tensorflow|keras|unsupervised-learning|aspect|attention-model
0
365,909
55,547,506
How to calculate tfidf score from a column of dataframe and extract words with a minimum score threshold
<p>I have taken a column of dataset which has description in text form for each row. I am trying to find words with tf-idf greater than some value n. but the code gives a matrix of scores how do I sort and filter the scores and see the corresponding word.</p> <pre><code>tempdataFrame = wineData.loc[wineData.variety ==...
<p>In the absence of a full data frame column of wine descriptions, the sample data you have provided is split in three sentences in order to create a data frame with one column named 'Description' and three rows. Then the column is passed to the tf-idf for analysis and a new data frame containing the features and thei...
pandas|tf-idf
3
365,910
55,258,627
How can I create an array of distributions in TensorFlow Probability?
<p>I'm trying to write code using Tensorflow Probability to classify a set of samples (coming from multiple Gaussian distributions) using the EM algorithm.</p> <p>As I want to write this code for any generic problem (I want it to work if the samples come from 2 Gaussian distributions or 8 Gaussian distributions).</p> ...
<p>TFP distributions are batch capable out of the box. Your code should work, and represents a vector of 2 normal distributions, where the first is <code>N(X|20, 8)</code> and the second is <code>N(X|60, 4)</code>.</p> <p>You can query this by <code>true_dist.batch_shape</code> (which will return <code>[2]</code> in t...
python|tensorflow|data-science|tensorflow-probability
1
365,911
55,377,842
Single records to multiple records in pandas
<p>I am new to pandas in python, I have to implement below logic. I know to implement this as a sql query, but needed to know how to implement this in pandas.</p> <p>I have output from a query as below:</p> <pre><code>startdatetime,endatetime,value 2019-03-26 23:00:00.000,2019-03-27 01:00:00.000,37.86 2019-03-27 01:0...
<p>Many ways to do this, just offering my perspective. </p> <p>First let's recreate your data</p> <pre><code>import pandas as pd df = pd.DataFrame([ ('2019-03-26 23:00:00.000','2019-03-27 01:00:00.000','37.86'), ('2019-03-27 01:00:00.000','2019-03-27 03:00:00.000','37.91'), ('2019-03-27 03:00:00.000','201...
python-3.x|pandas
1
365,912
55,386,612
slicing pandas dataframe encounter KeyError: 'n_tokens_content', how to locate the bad rows efficiently?
<p>I am trying to explore this <a href="https://archive.ics.uci.edu/ml/machine-learning-databases/00332/" rel="nofollow noreferrer">dataset</a> with pandas 0.20.3 in Python 3.6.2.</p> <pre><code>%pylab inline import pandas as pd df = pd.read_csv('OnlineNewsPopularity.csv') df['n_tokens_content'][:9] </code></pre> <p>...
<p>I encountered the same problem and it has been solved: <br> input: <code>df.columns</code> output:</p> <pre><code> Index(['url', ' timedelta', ' n_tokens_title', ' n_tokens_content', ' n_unique_tokens', ' n_non_stop_words', ' n_non_stop_unique_tokens', ' num_hrefs', ' num_self_hrefs', ' num_imgs', ' nu...
python|python-3.x|pandas|dataframe
0
365,913
55,287,343
Python performance of native data container vs Pandas DataFrame
<p>I'm wondering if anyone could provide any input concerning the speed/performance of python's native data containers versus a Pandas DataFrame -- namely in performing a substring lookup. </p> <p>Several months ago I posted a question pertaining to the operation (<a href="https://stackoverflow.com/questions/53073475...
<p>Long story short, no, <code>str</code> methods are not vectorised.</p> <p>If we look at the <code>pandas</code> code, we can find that the <code>str</code> methods eventually delegate to <code>pandas._lib.lib.map_infer</code>, which is defined as follows:</p> <pre><code>def map_infer(ndarray arr, object f, bint co...
python|pandas|loops|dataframe|iterator
2
365,914
55,255,846
disregard first row in np.where function
<p>Column 'signal' is populated with 0 or 1, and I want column 'reversal to tell me when there is a change in this column (i.e., from 0 to 1 or 1 to 0).</p> <h2>Issue: the code below gives me this information correctly for all the rows except the first one. The reason is that it tries to look at the value before the fi...
<p>If you are looking for the changes, I'd suggest using diff instead:</p> <pre><code>df_zinc['signal'].diff().fillna(0)!=0 </code></pre> <p>if you prefer it as a int instead of a boolean:</p> <pre><code>bool_s = df_zinc['signal'].diff().fillna(0)!=0 int_s = bool_s.astype(int) </code></pre> <p><strong>Testing:</st...
python|python-3.x|pandas|where
0
365,915
55,541,480
How to append a list to dataframe without using column names?
<p>I want to append a list of four prices <code>[1, 2, 3, 4]</code> to an already existing dataframe using the <code>DataFrame.append()</code>, the already existing dataframe has four columns.</p> <p>Using this</p> <pre class="lang-py prettyprint-override"><code>dataframe = pd.DataFrame(columns=[&quot;open&quot;, &quot...
<p>You can do something like </p> <pre><code>df.loc[len(df)] = [1, 2, 3, 4] </code></pre>
python|pandas|append
4
365,916
55,405,018
How to concatenate sum on apply function and print dataframe as a table format within a file
<p>I am trying to concatenate the 'count' value into the top row of my dataframe.</p> <p>Here is an example of my starting data:</p> <pre><code>Name,IP,Application,Count Tom,100.100.100,MsWord,5 Tom,100.100.100,Excel,10 Fred,200.200.200,Python,1 Fred,200.200.200,MsWord,5 df = pd.DataFrame(data, columns=['Name', 'IP...
<p>It is a bit of a challenge to treat a DataFrame and have it provide summary rows. Generally, the DataFrame lends itself to results that are not dependent on position, such as the last item in a group. Can be done, but better to separate those concerns.</p> <pre><code>import pandas as pd from StringIO import String...
python|python-3.x|pandas
1
365,917
55,355,059
Per class weighted loss for multiclass-multilabel classification
<p>I'm doing multiclass-multilabel classification. Namely, I have <code>N_labels</code> fully independent labels for each example, whereas each label may have <code>N_classes</code> different values (mutually exclusive). More concretely, each example is classified by <code>N_labels</code>-dimensional vector, while each...
<p>I think you need <code>tf.losses.sigmoid_cross_entropy</code> It uses <code>multi_class_labels</code> just as you described, and have functionality to apply weights. <a href="https://www.tensorflow.org/api_docs/python/tf/losses/sigmoid_cross_entropy" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/pyth...
python|tensorflow|classification|loss-function
1
365,918
55,303,138
Change dtypes in Pandas DataFrame cell-by-cell
<p><strong>Problem:</strong></p> <p>I have a Pandas.DataFrame which stores only unicode values. Each column contains values that could be converted to either an integer or float, or left as unicode. (Python version 2.7.15, Pandas version 0.23.0)</p> <pre><code>df = pd.DataFrame({'x':[u'1', u'1.23', u'', u'foo_text'],...
<p>Try using a function along with <code>.apply()</code> which will be a lot faster than three nested for-loops.</p> <p>So something like:</p> <pre><code>def change_dtype(value): try: return int(value) except ValueError: try: return float(value) except ValueError: ...
python|pandas
3
365,919
55,372,407
How can I compute the mean, dropping NaN and outliers from the dataframe in this format?
<p>I have a dataframe in the format below:</p> <pre><code>Original Dataframe | x | value1 | value2 | value3 | value4 ---|-----|----------|----------|----------|----------- 0 | 1 | 1 | NaN | 3 | 1 1 | 2 | 4 | NaN | 1 | NaN 2 | 3 | 2 | 6 ...
<p>You can use:</p> <pre><code>from scipy import stats #reshape to MultiIndex Series for remove NaNs s = df.set_index('x').stack() print (s) x 1 value1 1.0 value3 3.0 value4 1.0 2 value1 4.0 value3 1.0 3 value1 2.0 value2 6.0 value3 1.0 value4 2.0 4 value1 1...
pandas|numpy|scipy
0
365,920
55,455,256
Handling Multidimensional Arrays in Numpy
<p>I've coordinates as groups. All group must be stored as seperated. First I stored them list in list in list like this:</p> <pre><code>PointOne: numpy.array([x, y, z]) GroupOne: numpy.array([PointOne, PointTwo ... PointLast]) All Points : [GroupOne, GroupTwo, GroupThree] </code></pre> <p>I feel that my approach is...
<p>As per the <a href="https://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html" rel="nofollow noreferrer">documentation</a>, you can create N-dimensional arrays as follows:</p> <pre><code>import numpy as np arr = np.ndarray(shape = (5,3)) # 5 Rows by 3 columns </code></pre> <p>What follows below is the shape ...
python|numpy|multidimensional-array
0
365,921
55,243,417
Merge 2 data frames based on 2 condition in pandas
<p>How to replace the NaN values with the values from the first df:</p> <pre><code> country sex year cancer 0 Albania female 2000 32 1 Albania male 2000 58 2 Antigua female 2000 2 3 Antigua male 2000 5 4 Argen female 2000 591 5 Argen male 200...
<p>I am end up using <code>fillna</code> </p> <pre><code>df2.set_index(['country','sex'],inplace=True) df2['cancer']=df2['cancer'].fillna(df1.set_index(['country','sex']).cancer) df2.reset_index(inplace=True) df2 Out[745]: country sex year cancer 0 Albania female 1985 32.0 1 Albania male 1985 5...
python|pandas|dataframe|merge|nan
2
365,922
10,215,259
pandas aggregated data to a numpy array : data structure conversion
<p>I have aggregated data using pandas data frame. Below is some actual data shown and how I aggregated it.</p> <p><code>fdf.groupby(['row',col'])['percent'].sum()</code></p> <p><a href="http://pastebin.com/R8XWpgtU" rel="nofollow noreferrer">http://pastebin.com/R8XWpgtU</a></p> <p>What I would like to do is create...
<p>Try:</p> <pre><code>result = fdf.groupby(['row',col'])['percent'].sum() result.unstack('col').values </code></pre> <p>Alternately:</p> <pre><code>fdf.pivot_table('percent', rows='row', cols='col', aggfunc='sum').values </code></pre>
python|pandas
6
365,923
10,078,470
Sort numpy matrix row values in ascending order
<p>I have this following numpy matrix that I want to sort in ascending order <strong>based on the 3rd column values</strong>. </p> <pre><code>[[ 3.05706500e+06 4.98000000e+01 -2.62500070e+01 -9.38135544e+01] [ 3.05706600e+06 4.98000000e+01 -3.00000056e+01 -9.38135544e+01] [ 3.05706700e+06 4.98000000e+01...
<p>Given your array</p> <pre><code>&gt;&gt;&gt; arr array([[ 3.05706500e+06, 4.98000000e+01, -2.62500070e+01, -9.38135544e+01], [ 3.05706600e+06, 4.98000000e+01, -3.00000056e+01, -9.38135544e+01], [ 3.05706700e+06, 4.98000000e+01, -3.37500042e+01, -9.38135544e+01], ...
python|arrays|matrix|numpy
19
365,924
7,076,691
solve rectangular matrix in python to get solution with arbitrary parameters
<p>I want to solve a rectangular system (with arbitrary parameters in the solution). Failing that I would like to add rows to my matrix until it is square.</p> <pre><code>print matrix_a print vector_b print len(matrix_a),len(matrix_a[0]) </code></pre> <p>gives:</p> <pre><code> [[0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1,...
<p>Here is a simple implementation (with hard coded thresholds), but it gives the solution you are looking for with the test data. </p> <p>It's based on <a href="http://math.lanl.gov/Research/Publications/Docs/chartrand-2008-iteratively.pdf" rel="nofollow">Iteratively Reweighted Least Squares</a>.</p> <pre><code>fr...
python|matrix|numpy|scipy|linear-algebra
3
365,925
56,799,616
How torch.Tensor.backward() works?
<p>I recently study Pytorch and backward function of the package. I understood how to use it, but when I try</p> <pre><code>x = Variable(2*torch.ones(2, 2), requires_grad=True) x.backward(x) print(x.grad) </code></pre> <p>I expect </p> <pre><code>tensor([[1., 1.], [1., 1.]]) </code></pre> <p>because it is a...
<p>Actually, this is what you are looking for:</p> <p>Case 1: when z = 2*x**3 + x</p> <pre><code>import torch from torch.autograd import Variable x = Variable(2*torch.ones(2, 2), requires_grad=True) z = x*x*x*2+x z.backward(torch.ones_like(z)) print(x.grad) </code></pre> <p>output:</p> <pre><code>tensor([[25., 25.]...
pytorch|gradient|torch
1
365,926
56,497,729
Is there a python function for creating a nested JSON file from a DF?
<p>I'm trying to built a dataframe starting from the schema that the final JSON file should have. </p> <p>The schema is the following:</p> <pre><code>[{"plant": , "at": , "products": [{ "product": , "quantity": , }] </code></pre> <p>Plant should be a string, at should be a date ISO8601,...
<p>Use orient = 'records'</p> <pre><code>df2.groupby(['Plant', 'At'])['Product', 'Quantity'].apply(lambda x: x.to_dict('r')).reset_index(name = 'Products').to_json(orient = 'records') </code></pre> <p>You get </p> <pre><code>[{"Plant":"XXX", "At":"2019-05-03", "Products":[{"Product":"Product1","Quantity":4}]}] </cod...
json|pandas|dataframe|nested
0
365,927
56,467,820
How to write to_excel dynamic filename in for loop based on groupby field in PANDAS?
<p>I have a dataset of schools in each state. I want to group the schools by state, run some calculations to create a ranking, and then export each ranking to separate .xlsx files named "state.xlsx". For example, AK school data into ranking_alaska.xlsx, TX schools into ranking_texas.xlsx, etc. </p> <p>Example data her...
<p>The error is telling you a very straightforward explanation of why it is not working -> <code>x</code> <em>is a <strong>tuple</strong> and <strong>not</strong> a <strong>string</em></strong>! Personally I would try printing it and verifying that it is indeed what I want:</p> <pre><code>for x in grouped: print(x...
python|pandas|for-loop|filenames|export-to-excel
1
365,928
56,616,019
Compare master and child dataframe and extract new rows base on two column values only
<p>I have two Dataframes as:</p> <p>Master_DF:</p> <pre><code>Symbol,Strike_Price,C_BidPrice,Pecentage,Margin_Req,Underlay,C_LTP,LotSize JETAIRWAYS,110.0,1.25,26.0,105308.9,81.05,1.2,2200 JETAIRWAYS,120.0,1.0,32.0,96156.9,81.05,1.15,2200 PCJEWELLER,77.5,0.95,27.0,171217.0,56.95,1.3,6500 PCJEWELLER,80.0,0.8,29.0,16120...
<p>You can use right <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> with <code>indicator=True</code> and then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html" rel="nofollow ...
python|python-3.x|pandas|dataframe
1
365,929
56,719,670
Pandas DataFrame cleaning
<p>I have a dataframe with birthday date like '10.10.1990'. Since any method doesn't work with this column, I want to convert it to <code>datetime</code>. It work with first date column, but didn't work with the same second column.</p> <p>I think the problem is with trash date in this columns, but I don't know how to ...
<p>You can pass <code>errors</code></p> <pre><code>data[4] = pd.to_datetime(data[4], errors='coerce',format='%m.%d%.%Y') </code></pre>
pandas
0
365,930
56,834,596
How to make features for serving_input_receiver_fn BERT Tensorflow
<p>I have created a binary classifier with Tensorflow BERT language model. Here is the <a href="https://colab.research.google.com/github/google-research/bert/blob/master/predicting_movie_reviews_with_bert_on_tf_hub.ipynb" rel="nofollow noreferrer">link</a> to sample code. I am able to do predictions. Now I want to expo...
<p>The create_model function present in notebook takes some arguments. Those are the features which will be passed to the model.</p> <p>By updating the serving_input_fn function to following, the serving function works properly.</p> <p>Updated Code</p> <pre><code>def serving_input_fn(): feature_spec = { "inp...
python|tensorflow|nlp|feature-extraction|text-classification
1
365,931
56,595,259
TensorFlow: How to convert DeferredTensor to Tensor during eager execution (to perform group normalization)?
<p>In TensorFlow 1.10 through 1.12 (using eager execution), I have the following snippet of code:</p> <pre><code>tensor = tf.keras.layers.Conv2D(128, (3, 3), padding='same')(tensor) tensor = tf.contrib.layers.group_norm(tensor) </code></pre> <p>However, the call to <code>tf.contrib.layers.group_norm(tensor)</code> gi...
<p>You need to enable eager execution from the outset. It looks like you have a mix of eager and deferred causing the issue so I suspect one of your tensor ops were created before the call to <code>tf.enable_eager_execution()</code> rather than anything specific about the call to <code>tf.contrib.layers.group_norm(tens...
python|tensorflow|keras|tensor
1
365,932
56,720,101
Compare ground truth list of colours to another list of colours
<p>I have 2 arrays/lists of colours. One represents the <em>actual</em> dominant colours in an image, the other represents a list colours an algorithm thinks are the dominant colours in an image.</p> <p>I want to compare the 2 lists to see how *close the algorithm was to the <em>actual</em> ground truth list of colour...
<p>I think the part where you calculate the score is not correct. Your counting the number of elements below 25 globally. But if I understood correctly, you're looking if, for each color in <code>ground_truth</code> there is at least one color in <code>result</code> that is less than 25 points away.</p> <p>If this is ...
python|numpy|opencv|scipy
0
365,933
56,631,754
Apply lambda function on multiple columns
<p>Let's suppose that I have this <code>DataFrame</code> in <code>pandas</code>:</p> <pre><code> year text_1 text_2 0 1999 ['Sunny', 'weather'] ['Foggy', 'weather'] 1 2005 ['Rainy, 'weather'] ['Cloudy', 'weather'] </code></pre> <p>and I want to tranform it to this:</p> <pre><code...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html" rel="nofollow noreferrer"><code>DataFrame.applymap</code></a> if need processing each value element wise:</p> <pre><code>df[['text_1', 'text_2']] = df[['text_1', 'text_2']].applymap(' '.join) print (df) year ...
python|python-3.x|pandas
1
365,934
56,764,044
Scikit: Problem returning Dataframe from imputer instead of Numpy Array
<p>I am trying to impute some missing values in a Dataframe using the <code>scikit-learn</code> <code>IterativeImputer()</code>. The problem is that the imputer will take the <code>pandas</code> dataframe as an input, but will return a <code>numpy</code> array instead of the original dataframe. Here is a simple example...
<p>Yes you can , just assign the values back </p> <pre><code>df[:]= imputer.transform(df) </code></pre>
python|pandas|numpy|dataframe|scikit-learn
18
365,935
56,663,388
tensorboard - error:Trace already enabled - How to solve?
<p>I'm trying to learn and use tensorboard and followed <a href="https://www.tensorflow.org/tensorboard/r2/get_started" rel="nofollow noreferrer">these guideline codes</a> with a few modifications.</p> <p>When I run the code </p> <pre><code>model.fit(x=x_train, y=y_train, epochs=5, va...
<p>I was facing the same issue and even customizing the log_dir option using datetime didn't work. Check this page: <a href="https://github.com/tensorflow/tensorboard/issues/2819" rel="noreferrer">https://github.com/tensorflow/tensorboard/issues/2819</a> which helped me. I just added the 'profile_batch = 100000000' in ...
python|python-3.x|tensorflow|keras|tensorboard
9
365,936
56,608,431
What is the difference between a model and a bunch of stacked layers in TF 2.0?
<p>So, I can create my model by subclassing Keras layers and models, like this:</p> <pre><code>class CNN(tf.keras.models.Model): def __init__(self, **kwargs): super(CNN, self).__init__(**kwargs) self.l1 = tf.keras.layers.Conv2D(64, (4, 4), padding='same') self.l2 = tf.keras.layers.Dense(10,...
<p>From a software perspective <code>Model</code> is a unique python class, likewise as the various layers ( <a href="https://www.tensorflow.org/api_docs/python/tf/keras/models/Model" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/models/Model</a> is from TF 1.13 documentation ). Like for...
tensorflow|keras
1
365,937
56,478,055
How do I convert type int32 to int as it's not JSON serializable
<p>I currently have a pandas DataFrame that contains information in this format:</p> <pre><code> date new builds new houses new homes help to buy 0 2014-06-08 5 29 79 11 1 2014-06-15 5 30 79 11 2 2014-06-22 6 31 ...
<p>Try <code>int(data.loc[x, keyword_list[i]])</code> instead of <code>data.loc[x, keyword_list[i]]</code></p> <hr> <p><code>np.int32</code> is not JSON serializable but python <code>int</code> is, what you have to do is just converting <code>np.int32</code> to python <code>int</code>.</p>
python|json|pandas|numpy|dataframe
2
365,938
56,486,564
How to replace specific words from entire csv file?
<p>I have a large CSV file that has many short words and I need to change them into a full word. I found few posts here such as <a href="https://stackoverflow.com/questions/11033590/change-specific-value-in-csv-file-via-python">1</a>, <a href="https://stackoverflow.com/questions/36157553/how-to-replace-a-word-in-a-csv-...
<p>Read your text file in as a Series that looks like </p> <pre><code>s 0 mag:magnitude 1 shf:shaft 2 gr:gear 3 bat:battery 4 ext:exhaust 5 ml:mileage Name: 0, dtype: object </code></pre> <p>Split on colon and convert the series into a dictionary mapping key to its replacement:</p>...
python|pandas|dataframe
4
365,939
56,792,547
Populate Pandas Series with list
<p>I would like to populate a <code>pd.Series()</code> with a <code>list</code>. </p> <p>I tried doing the following:</p> <pre class="lang-py prettyprint-override"><code>series = pd.Series(index=['a','b','c','d']) series['a'] = 2 series['b'] = [2,3] </code></pre> <p>This is the error that I get. How can I populate t...
<p>This is because the initial dtype is assumed to be float (as the series is filled with NaNs).</p> <pre><code>series.dtype # dtype('float64') </code></pre> <p>Since lists are only supported by <code>object</code> type columns, you'd need to cast before assigning.</p> <pre><code>series = series.astype(object) serie...
python|pandas|list
2
365,940
56,695,491
How to mask an image gray scale using numpy array slicing
<p>I need to replace 8 bits values (0 to 255) indexed set of an image (final image), following a "map values" from another image (second image) gray scale which related map indexes was chosen from a primary image.</p> <p>In fact this is similar thing that MATLAB does with</p> <pre class="lang-matlab prettyprint-ove...
<p>You can do this by using the boolean indexing from A to directly copy the values from C into B (if you don't want to modify the original B, first create a copy using <code>B.copy()</code>).</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; A = np.array([0,0,1,0,0]) &gt;&gt;&gt; B = np.array([1,2,3,4,5]) &...
python|numpy|image-processing|array-broadcasting|numpy-slicing
1
365,941
56,444,496
How to take all combination of a pandas dataframe (choosing 2 at a time) and make a new dataframe with each two combination in a single row?
<p>I have a Input dataframe as shown. Taking two rows at a time there are 4C2 combinations. I want the output to be saved in a dataframe as shown in output dataframe . In the output dataframe for each possible combination columns of two rows are side by side.</p> <p><strong>Input df</strong> </p> <pre><code> A ...
<h1>Method 1</h1> <p>Create an artificial key column, then merge the <code>df</code> to itself:</p> <pre><code>df['key'] = 1 df.merge(df, on='key',suffixes=["", "'"]).reset_index(drop=True).drop('key', axis=1) </code></pre> <hr> <pre><code> A B A' B' 0 0.50 12 0.50 12 1 0.50 12 0.70 16 2 0....
python-3.x|pandas|dataframe|row|combinations
4
365,942
56,849,215
Tensorflow Lite Android for Object Detection in Landscape Orientation
<p>I am trying to run Tensorflow Lite object detection example on Android device. But I need to reconfigure this example to accommodate landscape screen orientation.</p> <p>I have changed screen orientation parameter in AndroidManifest.xml to 'Landscape' but screen preview is keeping in portrait mode. The squared obje...
<p>I faced same issue on my smart glass which is always has landscape screen orientation. You don't necessarily need to change AndroidManifest.xml. I have changed followings to make it work:</p> <p><strong>1. Change rotation angle to 0 CameraActivity.java:200</strong></p> <p>Replace onPreviewSizeChosen(new Size(previ...
android|object|tensorflow|detection|tensorflow-lite
2
365,943
56,485,817
how to find exponential weighted moving average using dataframe.ewma?
<p>Previously I used the following to calculate the ewma</p> <pre><code>dataset['26ema'] = pd.ewma(dataset['price'], span=26) </code></pre> <p>But, in the latest version of pandas pd.ewma has been removed. How to calculate using the new method dataframe.ewma?</p> <pre><code>dataset['26ema'] = dataset['price'].ewma(s...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.ewm.html" rel="nofollow noreferrer"><strong><code>Series.ewm</code></strong></a>:</p> <pre><code>dataset['price'].ewm(span=26) </code></pre> <p>See <a href="https://github.com/pandas-dev/pandas/pull/11603" rel="nofollow noreferre...
python-3.x|pandas
2
365,944
56,792,723
How do I create a new column in a dataframe from an existing column using conditions?
<p>I have one column containing all the data which looks something like this (values that need to be separated have a mark like (c)):</p> <pre><code>UK (c) London Wales Liverpool US (c) Chicago New York San Francisco Seattle Australia (c) Sydney Perth </code></pre> <p>And I want it split into two columns looking like...
<p>Step by step with <code>endswith</code> and <code>ffill</code> + <code>str.strip</code> </p> <pre><code>df['country']=df.loc[df.city.str.endswith('(c)'),'city'] df.country=df.country.ffill() df=df[df.city.ne(df.country)] df.country=df.country.str.strip('(c)') </code></pre>
python|pandas|dataframe|series
10
365,945
56,445,109
Numpy index filtering changing multiple variables
<p>I notice unexpected results when applying index filtering to a numpy array (<code>b[b &lt; 3] = 0</code> ). Any variable that has been assigned from or to the variable that is being filtered will have the same filter applied i.e. if <code>b = a</code>, <code>a</code> will be filtered the same filter as <code>b</code...
<p>It happens because you assign variables a,b,c and d to the same array. Think of the variables as access to this array. If you apply filtering to this array. Then it will affect all variables as they are pointing to this same array. If you want to seperate array based on this one you can use copy method like arr_b = ...
python-3.x|numpy|variable-assignment|matrix-indexing
0
365,946
56,528,221
Extracting string after pattern
<p>I have a series of url</p> <pre><code>www.domain.com/calendar.php?month=may.2019 www.domain.com/calendar.php?month=april.2019 www.domain.com/calendar.php?month=march.2019 www.domain.com/calendar.php?month=feb.2019 ... ... ... www.domain.com/calendar.php?month=feb.2007 </code></pre> <p>I wanted to extract the year ...
<h3>Fix your code</h3> <pre><code>df["urls"].str.extract('(?&lt;=month=).*\.(\d{4})$') </code></pre> <hr> <p>If you can trust that all do have the same pattern, then these should work.</p> <h3><code>split</code></h3> <pre><code>df["urls"].str.rsplit('.', 1).str[-1] </code></pre> <hr> <h3>slice</h3> <pre><code>d...
python|regex|pandas
4
365,947
56,755,299
not able to append row in new dataframe
<p>****Not able to append row in new Data Frame** Any affort would be appriciated**</p> <pre><code>new_df=pd.DataFrame() z=pd.DataFrame() x=input("input number") x=int(x) for i in range(x): y=input("enter srting") z=usda[usda.Description.str.contains("y")] new_df.append(z,ignore_index = True) print(new_...
<p>Try <code>new_df=new_df.append(z,ignore_index = True)</code>. Otherwise the new dataframe is not saved to the variable <code>new_df</code>.</p>
python|pandas
0
365,948
56,480,701
How can I repeat this numpy array within itself?
<p>I have an array <code>z</code> of <code>shape</code> <code>(8,)</code>:</p> <pre><code>&gt;&gt;&gt; z array([-30000. , -30000. , -30000. , -30000. , -27703.12304688, -27703.15429688, -27703.70703125, -27703.67382812]) </code></pre> <p>I would like to copy the values 7 more times ...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html" rel="nofollow noreferrer"><strong><code>np.tile</code></strong></a> with a list to return a a 2D array:</p> <pre><code># tile improvement courtesy OP np.tile(z, [8, 1]) </code></pre> <hr> <p>If you want a read-only view, <a href="h...
python|arrays|numpy
1
365,949
56,833,783
How to subtract data frames with different fill values
<p>I need to subtract two Data Frames with different indexes (which causes 'NaN' values when one of the values is missing) and I want to replace the missing values from each Data Frame with different number (fill value). For example, let's say I have df1 and df2:</p> <p>df1:</p> <pre><code> A B C 0 0 3 0...
<p>One way would be to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> <code>df2</code> setting <code>fill_value</code> to <code>0</code> before subtracting, then subtract and <a href="https://pandas.pydata.org/pandas-...
python|pandas|dataframe
3
365,950
56,462,088
Why doesn't pandas reindex() operate in-place?
<p>From the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="noreferrer">reindex docs</a>:</p> <blockquote> <p>Conform DataFrame to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index. A new object is produced...
<p><code>reindex</code> is a structural change, not a cosmetic or transformative one. As such, a copy is always returned because the operation cannot be done in-place (it would require allocating new memory for underlying arrays, etc). This means you <em>have</em> to assign the result back, there's no other choice.</p>...
python|pandas|dataframe|reindex
15
365,951
56,773,356
calculate the arithmetic mean
<p>I would like to know how to calculate the arithmetic mean for all of two consecutive elements in a python-numpy array, and save the values in another array</p> <pre><code>col1sortedunique = [0.0610754, 0.27365186, 0.37697331, 0.46547072, 0.69995587, 0.72998093, 0.85794189] </code></pre> <p>thank you</p>
<p>If I understood you correctly you want to do something like this:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np arr = np.arange(0,10) &gt;&gt;&gt; array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) </code></pre> <pre class="lang-py prettyprint-override"><code>conse_mean = (arr[:-1]+arr[1:])/2 &gt;&gt;&...
python-3.x|numpy
3
365,952
56,634,458
Pandas plot barh with centered bars (pyramid)
<p>I'm trying to create a plot with pandas.plot(kind='barh') but get centered boxes around the middle of the plots (middle from an X axis perspective).</p> <p>I tried to get something like this : <a href="https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python/#29.-Population...
<p>Plot the positive and negative halves:</p> <pre><code>fig, ax = plt.subplots(figsize=(6, 4)) (df.May2019.T/2).plot(kind='barh', title='Number of customers per revenue slice', width=0.99, ax=ax) (df.May2019.T/-2).plot(kind='barh', width=0.99, ax=ax) ax.set_yticklabels(['6...
python|pandas|matplotlib|charts
1
365,953
56,474,526
How to fix: the python code doesn't work through DAG airflow: pandas.read_csv('gs://x/y.csv') file doesn't exist
<p>the code on my computer runs fine but when I put it in DAG to run through Airflow it doesn't work. I use GCP and composer. The other tasks work fine on the same cloud storage. The composer has all permissions needed. </p> <pre><code>def get_results(): import pandas as pandas df = pandas.read_csv('gs://y/x.c...
<p>GCP composer uses Cloud Storage FUSE which maps your composer dag folder to the <code>Google cloud storage</code> bucket in which you place your DAGs (e.g.: <code>gs://bucket-name/dags</code>).</p> <p>I advise you to place your files that are shared between dags in this folder <code>/home/airflow/gcs/data</code> wh...
python|pandas|google-cloud-storage|airflow|google-cloud-composer
1
365,954
56,470,243
Improving speed of the code when using numpy.apply_along_axis
<p>I have a function which takes a two element array as input. Now I have large data (shape = (360000,2)) and want to evaluate the function at each point by using numpy.apply_along_axis . One of the answers given in the this thread(<a href="https://stackoverflow.com/questions/23849097/numpy-np-apply-along-axis-function...
<p><code>np.sin</code> and <code>*</code> are vectorized operations, so, you can apply them over whole arrays:</p> <pre><code>np.sin(data[:, 0]) * np.cos(data[:, 1]) </code></pre> <p><code>data[:, 0]</code> is the first column and <code>data[:, 1]</code> is the second.</p> <p>Note that this should go really fast :)<...
python|numpy
4
365,955
56,648,504
Pandas Profiling does not work when started from a Java program
<p>I have a simple Python program using pandas_profiling. Here is the source code, which I have stored as c:\temp\pandas_profiling_demo.py:</p> <pre><code>import pandas as pd import pandas_profiling as pp df = pd.DataFrame(data={'x': [1, 2, 3, 4, 5], 'y': [2, 2, 4, 6, 6], 'z': [4, 6, 1, 5, 2]}) print(df.head(10)) prof...
<p>You can find the solutions <a href="https://github.com/pandas-profiling/pandas-profiling/issues/134" rel="nofollow noreferrer">here</a> and <a href="https://stackoverflow.com/questions/55521803/how-to-do-data-profile-to-a-table-using-pandas-profiling">here</a>.</p> <p>In your case:</p> <pre><code>import pandas as ...
java|python|pandas-profiling
1
365,956
56,576,379
Interpolate NaN values over a DataFrame as a ring
<p>I need to interpolate the <code>NaN</code> values over a <code>Dataframe</code> but I want that interpolation to get the first values of the <code>DataFrame</code> in case the <code>NaN</code> value is the last value. Here is an example:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame.from_d...
<p>One possible solution is add first row, interpolate and remove last row:</p> <pre><code>df = df.append(df.iloc[0]).interpolate(method="linear").iloc[:-1] print (df) a b 0 1.0 1.0 1 2.0 2.0 2 3.0 1.5 </code></pre> <p>EDIT:</p> <p>More general solution:</p> <pre><code>df = pd.DataFrame.from_dict({"a"...
python|pandas|numpy
2
365,957
56,557,084
when restoring from a checkpoint, how can I change the data type of the parameters?
<p>I have a pre-trained Tensorflow checkpoint, where the parameters are all of float32 data type.</p> <p><strong>How can I load checkpoint parameters as float16? Or is there a way to modify data types of a checkpoint?</strong></p> <p>Followings is my code snippet that tries to load float32 checkpoint into a float16 g...
<p>Looking a bit into <a href="https://github.com/tensorflow/tensorflow/blob/v1.14.0/tensorflow/python/training/saver.py" rel="noreferrer">how savers work</a>, seems you can redefine their construction through a <code>builder</code> object. You could for example have a builder that loads values as <code>tf.float32</cod...
python|tensorflow|machine-learning
9
365,958
56,716,585
opening csv file in a numpy.txt in python3
<p>I have a csv file and tryng to open it using numpy.loadtxt. if I open it using pandas, the file will look like this small example:</p> <p>small example:</p> <pre><code>Name Accession Class Species Annotation CF330 NaN NaN NaN NaN NaN NaN A2M NM_000014.4 En...
<pre><code>In [19]: txt = '''Name,Accession,Class,Species,Annotation,CF330 ...: ,,,,, ...: A2M,NM_000014.4,Endogenous,Hs,,11495 ...: ACVR1C,NM_145259.2,Endogenous,Hs,,28 ...: ADAM12,NM_003474.5,Endogenous,Hs,,1020 ...: ADGRE1,NM_001256252.1,Endogenous,Hs,,42''' </code></pre> <p>With <code>d...
python-3.x|pandas|csv|numpy
2
365,959
56,794,577
Python - remove first column of 0 in dataframe read from csv
<p>I am reading a csv and the dataframe contains an index of 0's at the beginning. </p> <pre><code>df.drop(df.columns[0], axis=1, inplace=True) </code></pre> <p>This removed the actual second column. The first is some kind of index it seems, but just with 0's</p>
<p>If you don't like your all-zeros Index, then you may <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset</code></a> it:</p> <pre class="lang-py prettyprint-override"><code>df.reset_index(inplace=True, drop=True) </code></pre> ...
python|pandas|dataframe
0
365,960
56,479,931
Pandas - How to count successive appearances in a dataframe?
<p>I have a column A and I want to create another column B that counts the successive appearances of a value in column A, like this:</p> <pre><code> A B ---|--- 1 | 0 0 | 0 0 | 0 1 | 1 0 | 1 0 | 1 1 | 2 0 | 2 0 | 2 -1 | 0 0 | 0 0 | 0 -1 |-1 0 |-1 -1 |-2 0 |-2 0 |-2 1 | 0 0 | 0 1 | 1 0 | 1 1 | 2...
<p>In your case create the group key by using <code>ffill</code> with <code>cumsum</code> , then <code>groupby</code> <code>cumsum</code> subtract the <code>first</code> item of each group </p> <pre><code>g=df.groupby(df.A.mask(df.A==0).ffill().diff().ne(0).cumsum()).A g.cumsum()-g.transform('first') #df['B']= g.cumsu...
python|pandas|dataframe
1
365,961
56,606,583
How Do I Correctly Shape my Data for my NN Model?
<p>I am trying to create a basic neural network model in Keras that will learn to add positive numbers together and am having trouble with shaping the training data to fit the model:</p> <p>I have already tried numerous configurations for the "input_shape" attribute of the first Dense layer, but nothing seems to work....
<p>Got the error. The error was in this line according to the stack traces,</p> <pre><code>print(model.predict([[7,9]])) </code></pre> <p>Now, Keras Sequential model expects inputs in the form of a NumPy array ( <code>ndarray</code> ). In the above line, the model interprets the array as a list on multiple inputs ( w...
python|numpy|tensorflow|keras|reshape
1
365,962
56,845,982
Pandas data frame where each row is a list where blank space needs to be replaced with a comma
<p>I have a pandas data frame read from a <strong>.csv</strong> file where the output is something like this:</p> <pre><code>1 [44 48 50 55 56 57] 2 [49 54 57 61 62 64] 3 [45 51 53 58 59 61] 4 [47 52 54 59 60 62] </code></pre> <p>Each row is to be the list for a separate for loop.</p> <p>I need each ...
<p>Since each value is a string, and you're dealing with a <code>pd.Series</code> object more than a <code>pd.DataFrame</code> object, you should use <code>pd.Series.str.replace</code> (use the <code>squeeze</code> parameter in the pd.read_csv function to force the csv as a <code>pd.Series</code> on read)</p>
pandas|python-2.7
0
365,963
56,482,159
Appending data into csv file
<p>I am appending data from the arrays into csv file with the headers. The headers are appearing after every iteration while they should only appear on the top.</p> <pre><code>x=pd.DataFrame({'1st':U_1, '2nd':U_2, '3rd':U_3, '4th':U_4, '5th':U_5, '6th':U_6, '7th':U_7, '8th':U_8, 'Time Stamp':start}) export_...
<p>Create your csv file with the header only:</p> <pre><code>import numpy as np csvheader = x.columns.values csvheader = csvheader.reshape(1, csvheader.shape[0]) np.savetxt('/home/pi/Frames/q8.csv', csvheader, delimiter='\t', fmt='%s') </code></pre> <p>then append the data with <code>header=False</code>:</p> <pre>...
python|pandas|dataframe|export-to-csv
0
365,964
56,577,529
Is there a way to add constraints to a neural network output but still with softmax activation function?
<p>I am not a deep learning geek, i am learning to do this for my homework. How can I make my neural network output a list of positive floats that sum to 1 but at the same time each element of the list is smaller than a treshold (0.4 for example)?</p> <p>I tried to add some hidden layers before the output layer but th...
<p>What you want to do is add a penalty in case any of the outputs is larger than some specified <code>thresh</code>, you can do this with the <code>max</code> function:</p> <pre><code>thresh = 0.4 strength = 10.0 reg_output = strength * tf.reduce_sum(tf.math.maximum(0.0, outputs - thresh), axis=-1) </code></pre> <p>...
python|tensorflow|neural-network|deep-learning
4
365,965
56,670,850
How to calculate vwap (volume weighted average price) using groupby?
<p>I want to calculate the VWAP value for each month (i.e. for each group created).</p> <pre><code>data['Month'] = pd.DatetimeIndex(data['Date']).month data.head() data['Year'] = pd.DatetimeIndex(data['Date']).year data.head() group = data.groupby(['Month', 'Year']) group.first() data['VWAP'] = (np.cumsum(data['Close...
<p>You forget to write ']' after the data['Close Price'], here is my code</p> <pre><code>df['Month'] = pd.DatetimeIndex(df['Date']).month df['Year'] = pd.DatetimeIndex(df['Date']).year group = df.groupby(['Month', 'Year']) df['VWAP'] = (np.cumsum(df['Close Price'] * df['Total Traded Quantity']) / np.cumsum(df['Total T...
python-3.x|pandas|machine-learning
1
365,966
56,633,576
I want to write a 75000x10000 matrix with float values effectively into a database
<p>thanks for hearing me out.</p> <p>I have a dataset that is a matrix of shape <code>75000x10000</code> filled with float values. Think of it like heatmap/correlation matrix. I want to store this in a SQLite database (SQLite because I am modifying an existing <strong>Django project</strong>). The source data file is ...
<p>SQLite is quite impressive for what it is, but it's probably not going to give you the performance you are looking for at that scale, so even though your existing project is Django on SQLite I would recommend simply writing a Python wrapper for a different data backend and just using that from within Django.</p> <p...
python|sql|django|pandas|bigdata
2
365,967
56,593,223
Iterate over three rows then do linear regression
<p>I want to iterate over three rows in only two columns, then in the function of iteration, I do linear regression in that three rows. So, iterate over three rows, do linear regression, iterate over three rows, do linear regression, so on.</p> <p>I put the data input <a href="https://i.stack.imgur.com/wWSdd.png" rel=...
<p>If you're looking to do a simple linear regression per group of three years, try something like this:</p> <pre><code># Hardcoded input data for clarity #all_years = data_['Year'].values #all_values = data_['Value'].values all_years = np.array([1,2,3, 1,2,3, 1,2,3, ...
python|pandas|loops|linear-regression
1
365,968
56,692,421
delete row with threshold or category and save to multiple CSV in pandas
<p>I am a beginner in python. I have big data looks like this:</p> <pre><code>df Mean id 0.089394 1 0.389394 2 0.047313 3 0.047313 4 0.767004 5 0.767004 6 0.363154 7 0.363154 8 0.098941 9 1.578785 10 0 11 ..... </code></pre> <p>I want to eliminate or delete row mean colum...
<p>Define a function that takes in the mean value and the threshold as the variables:</p> <pre class="lang-py prettyprint-override"><code>def helping_func(value, threshold): return (value &gt; threshold) </code></pre> <p>Use a <code>for</code> loop to perform the conditional check and store into individual csv fi...
python|python-3.x|pandas|csv|numpy
2
365,969
56,859,518
If consecutive dataframe values are equal, edit value of second column
<p>I am trying to identify consecutive column values that are the same, and when they are, edit a second column to give their rows more 'uniqueness'.</p> <p>Given the following dataframe</p> <pre><code>name code Jim G Jim G Bob F Abe Z if df['name'] == df.shift()['name']: num = 1 df['...
<p>Do is as below </p> <pre><code>g=df.groupby('name') df.code=np.where(g.code.transform('count').gt(1),df.code+'_'+g.cumcount().add(1).astype(str),df.code) </code></pre>
python|pandas
4
365,970
56,458,907
Why am I getting an ‘IndexError: string index out of range’ when I use a concatenated dataframe
<p>So basically I use the same code in two separate cases.</p> <p>Case 1: I open and read a csv file using csv module and implement the code on the data taken from that csv file. The code works fine in this case</p> <p>Case 2: I use the same code but this time instead of using csv module I use pandas and glob in orde...
<p>For your case, please recheck your <code>frame</code> data.</p> <p>You can check it by <code>print</code> out data:</p> <pre class="lang-py prettyprint-override"><code>for game in frame: print(game, len(game)) </code></pre> <p>Pretty sure that at least one <code>game</code> will have less than 4 characters in...
python|pandas
0
365,971
25,539,311
Custom transformer for sklearn Pipeline that alters both X and y
<p>I want to create my own transformer for use with the sklearn <code>Pipeline</code>.</p> <p>I am creating a class that implements both fit and transform methods. The purpose of the transformer will be to remove rows from the matrix that have more than a specified number of NaNs.</p> <p>The issue I am facing is <stron...
<p>Modifying the sample axis, e.g. removing samples, does not (yet?) comply with the scikit-learn transformer API. So if you need to do this, you should do it outside any calls to scikit learn, as preprocessing.</p> <p>As it is now, the transformer API is used to transform the features of a given sample into something...
python|pandas|numpy|machine-learning|scikit-learn
17
365,972
25,891,393
Python pandas - get index of rows
<p>I have a dataframe which looks like this:</p> <pre><code>df_raw.head() Ticker FY Periodicity Measure Val Date 0 BP9DL90 2009 ANN CPX 1000.00 2008-03-31 00:00:00 1 BP9DL90 2010 ANN CPX 600.00 2009-03-25 00:00:00 2 BPRTD89 2010 ANN CPX 600.00 20...
<p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.idxmax.html#pandas.Series.idxmax" rel="nofollow"><code>idxmax</code></a>:</p> <pre><code>&gt;&gt;&gt; df['Date'] = pd.to_datetime(df['Date']) # in case `Date` column is string &gt;&gt;&gt; i = df.groupby('Ticker')['Date'].idxmax().valu...
python|pandas
2
365,973
25,570,147
Add new column based on boolean values in a different column
<p>I'm trying to add a new column to a DataFrame based on the boolean values in another column.</p> <p>Given a DataFrame like this:</p> <pre><code>snr = DataFrame({ 'name': ['A', 'B', 'C', 'D', 'E'], 'seniority': [False, False, False, True, False] }) </code></pre> <p>The furthest I've come so far is this:</p> <pre...
<p>You can create a dict and call <code>map</code>:</p> <pre><code>In [176]: temp = {True:'senior', False:'Non-senior'} snr['refined_seniority'] = snr['seniority'].map(temp) snr Out[176]: name seniority refined_seniority 0 A False Non-senior 1 B False Non-senior 2 C False N...
python|pandas
5
365,974
25,826,500
Python eval function with numpy arrays via string input with dictionaries
<p>I am implementing the code in python which has the variables stored in numpy vectors. I need to perform simple operation: something like (vec1+vec2^2)/vec3. Each element of each vector is summed and multiplied. (analog of MATLAB elementwise .* operation). </p> <p>The problem is in my code that I have dictionary whi...
<p>Using <a href="https://github.com/pydata/numexpr">numexpr</a>, then you could do this:</p> <pre><code>In [143]: import numexpr as ne In [146]: ne.evaluate('2*a*(b/c)**2', local_dict=var) Out[146]: array([ 0.88888889, 0.44444444, 4. ]) </code></pre>
python|numpy|scipy
14
365,975
25,556,663
make 1 dimensional array of strings with elements seperated by commas from 2 d array in numpy
<p>I need to make a 1D numpy array from a 2D array, such that the elements within the 2 columns are joined and separated and the data type is a string. I can do the opposite function with <code>np.split</code>, but <code>np.concatenate</code> does not seem to work the way I need it to, and there is no such <code>'join...
<p>Try this. </p> <pre><code>&gt;&gt;&gt; a array([[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]) &gt;&gt;&gt; b array([[4, 5], [6, 7]]) </code></pre> <p>Add an axis so that <code>a</code> can be broadcast onto <code>b</code> and test for equivalancy</p> <pre><code>&gt;&gt;&gt; c = a ==...
python|arrays|numpy|membership
0
365,976
25,859,785
Aggregation of several columns in pandas
<p>I have the following data in dataframe df:</p> <pre><code>VALUE COUNT REGION ID 235 15 LP 139 355 59 LP 102 421 8 LP 127 427 227 LP 90 439 4 LP 133 235 45 UP 139 355 231 UP 102 421 756 UP 127 427 ...
<p>You can tell <code>aggregate</code> to perform multiple actions on multiple columns.</p> <p>You did not mention what you want to do with the <code>ID</code> column, so here I take the first. Columns that can't be summed are usually silently dropped, and so is the case here.</p> <pre><code>In [51]: df.groupby('VALU...
python|pandas
2
365,977
25,725,055
pandas MultiIndex degeneration
<p>I want to make a multiindex with lexsort-depth 7 for a dataframe. But, on several depths of the index I only have the same value. The Pandas multiindex constructor excludes those with the same value. Is there any way I can keep them?</p> <p>for example:</p> <pre><code>import pandas as pd labels = [(0, 0, 5, 0, ...
<p>You need to sort the MI first for it to have full lexsort depth:</p> <pre><code>In [11]: index = index.order() In [12]: index.lexsort_depth Out[12]: 7 </code></pre> <p><em>At the moment it is not sorted past the second level (where 5 is before 4).</em></p>
python|pandas
1
365,978
25,478,528
Updating value in iterrow for pandas
<p>I am doing some geocoding work that I used <code>selenium</code> to screen scrape the x-y coordinate I need for address of a location, I imported an xls file to panda dataframe and want to use explicit loop to update the rows which do not have the x-y coordinate, like below:</p> <pre><code>for index, row in rche_df...
<p>The rows you get back from <code>iterrows</code> are copies that are no longer connected to the original data frame, so edits don't change your dataframe. Thankfully, because each item you get back from <code>iterrows</code> contains the current index, you can use that to access and edit the relevant row of the data...
python|loops|pandas|explicit
196
365,979
25,432,523
How to check if a value is of a NumPy type?
<p>Imagine you have a value that might or might not be one of the NumPy dtypes. How would you write a function that checks which is the case?</p> <pre><code>def is_numpy(value): # how to code? </code></pre>
<p>One way I've found that works was used by Mike T in his answer to <a href="https://stackoverflow.com/questions/9452775/converting-numpy-dtypes-to-native-python-types">Converting numpy dtypes to native python types</a>:</p> <pre><code>def is_numpy(value): return hasattr(value, 'dtype') </code></pre> <p>I'm not ...
python|numpy
2
365,980
25,654,748
How can you turn an index array into a mask array in Numpy?
<p>Is it possible to convert an array of indices to an array of ones and zeros, given the range? i.e. [2,3] -> [0, 0, 1, 1, 0], in range of 5</p> <p>I'm trying to automate something like this:</p> <pre><code>&gt;&gt;&gt; index_array = np.arange(200,300) array([200, 201, ... , 299]) &gt;&gt;&gt; mask_array = ??? ...
<p>Here's one way:</p> <pre><code>In [1]: index_array = np.array([3, 4, 7, 9]) In [2]: n = 15 In [3]: mask_array = np.zeros(n, dtype=int) In [4]: mask_array[index_array] = 1 In [5]: mask_array Out[5]: array([0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0]) </code></pre> <p>If the mask is always a range, you can elim...
python|arrays|numpy|where|mask
42
365,981
25,506,281
What are some possible calculations with numpy or scipy that can return a NaN?
<p>What are the most common operations that would cause a <code>NaN</code>, in Python, which originate while working with NumPy or SciPy?</p> <p>For example:</p> <pre><code>1e500 - 1e500 &gt;&gt;&gt; nan </code></pre> <p>What is the reasoning for this behavior and why does it not return 0?</p>
<p>If you do any of the following without horsing around with the floating-point environment, you should get a NaN where you didn't have one before:</p> <ul> <li><code>0/0</code> (either sign on top and bottom)</li> <li><code>inf/inf</code> (either sign on top and bottom)</li> <li><code>inf - inf</code> or <code>(-inf...
python|numpy|floating-point|nan
72
365,982
26,427,666
use variables as key names when using numpy savez
<p>After loading an npz file, I like being able to access arrays with keys, e.g.:</p> <pre><code>KEY1 = "names" file = np.load(npzFilename) data = file[KEY1] </code></pre> <p>But you have to manually force this when you save, i.e.:</p> <pre><code>np.savez(npzFilename, names=names) </code></pre> <p>Is there anywa...
<p>Using a dictionary you could do:</p> <pre><code>vals_to_save = {KEY1:names} np.savez(npzFilename, **vals_to_save) </code></pre> <p>where you could set up the dict <code>vals_to_save</code> programatically as desired. </p>
python|numpy|save
5
365,983
26,153,541
New pandas dataframe column using values from python dictionary
<p>I have a pandas dataframe, for example:</p> <pre><code>colA colB code1 num code2 num code3 num code4 num code5 num </code></pre> <p>I also have a python dictionary, for example:</p> <pre><code>py_dict = {'code1': [val1, val2, val3, val4, val5], 'code2': [val1, val2, val3, val4, val5...
<p>First create a new dict containing only the value you want from each list:</p> <pre><code>new_dict = {k: v[2] for k, v in py_dict.iteritems()} </code></pre> <p>Then you can use <code>Series.map</code></p> <pre><code>df['new_col'] = df.colA.map(new_dict) </code></pre>
python|dictionary|pandas|indexing|dataframe
1
365,984
26,377,023
Send a multidimensional numpy array over a socket
<p>Good day,</p> <p>I've searched for this but haven't come up with any responses. I wish to send a multi dimensional numpy array over a socket. Hence, I decided to convert it to a string:</p> <p>However, it destroys the representation of the array:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x = np....
<p>Try this example:- </p> <pre><code>import socket import numpy as np from cStringIO import StringIO class numpysocket(): def __init__(self): pass @staticmethod def startServer(): port=7555 server_socket=socket.socket() server_socket.bind(('',port)) server_soc...
python|arrays|numpy|multidimensional-array
11
365,985
26,399,225
Pandas: Joining information from multiple data frames, array
<p>Suppose I have three data structures:</p> <ol> <li>A data frame <code>df1</code>, with columns <code>A, B, C</code> of length 10000</li> <li>A data frame <code>df2</code>, with columns <code>A, some extra misc. columns...</code> of length 8000</li> <li>A Python list <code>labels</code> of length 8000, where the ele...
<p>OK from what I understand the following should work:</p> <pre class="lang-python prettyprint-override"><code># create a new column for your labels, this will align to your index df2['labels'] = labels # now merge the rows from df1 on column 'A' df2 = df2.merge(df1, on='A', how='left') </code></pre> <p>Example:</p>...
pandas|dataframe
1
365,986
26,148,833
generate a random int from a range which is not currently shown in a row
<p>I'm doing sudoku in python, I want to randomly fill up a row which has blanks.</p> <p>so I have a function that detects the blank positions and also a function that generates ints to fill.</p> <p>Say, if a row is <code>[1 , 2 , ?, ?]</code> When the position function hit the first <code>'?'</code>, the random func...
<p>Its hard to say exactly what your question is with your description and incomplete code.</p> <p>Here's what I'm guessing you're asking:</p> <blockquote> <p>We're given a row <em>r</em> that has <em>n</em> elements in it.</p> <p>For each element in <em>r</em> equal to -1, fill it with a value <em>x</em>, tha...
python|numpy|random
1
365,987
26,285,661
Working with comparing dataframes and series and generating new dataframes on the fly in python pandas
<p>I am creating a function that compares a dataframe (DF) to a series (S) and eventually returns a new dataframe. The common column is 'name'. I want the function to return a dataframe with the same number of rows as the series (S) and the same number of columns as the df. The function will search name columns in th...
<p>Don, <br> So, let's go:</p> <pre><code># with this tables In [66]: S Out[66]: 0 aaa 1 bbb 2 ccc 3 ddd 4 eee Name: name, dtype: object In [84]: df Out[84]: a b c name 0 39 71 55 aaa 1 9 57 6 bbb 2 72 22 52 iii 3 68 97 81 jjj 4 30 64 78 kkk # transform the series to a d...
python|numpy|pandas
1
365,988
26,286,615
How can pandas.read_sql_query() query a TEMP table?
<p>I'm in the process of converting Python code over to the new SQLAlchemy-based Pandas 0.14.1.</p> <p>A common pattern we use is (generically):</p> <pre><code>connection = db.connect() # open connection/session sql = 'CREATE TEMP TABLE table1 AS SELECT ...' connection.execute(sql) ... other sql that creates TEMP ...
<p>You can now pass SQLAlchemy connectable to <code>pandas.read_sql</code>. From the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html" rel="noreferrer">docs</a>:</p> <blockquote> <p>pandas.read_sql(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=No...
sql|python-2.7|pandas|sqlalchemy|netezza
8
365,989
26,242,037
Algorithmic help in Python, find pair (x,y) where y/x > const
<p>I'm building a rather huge real-time odds system, and my bottleneck right now is the actual computation. I have a huge amount of sorted lists, and for each list, I need to find each pair (x,y) where (y/x) > const.</p> <p>This is what I'm currently doing;</p> <pre><code>for f in reversed(xrange(1, len(odds))): ...
<p>If the list is sorted, then for each x you can just search the list for the first occurrence of const*x, and all items after that match:</p> <pre><code>import numpy odds = numpy.arange(10.) const = 2.5 for x in odds: idx = numpy.searchsorted(odds, const*x, side='right') for y in odds[idx:]: print ...
python|algorithm|numpy
2
365,990
66,866,936
Comparing pandas dataframe columns using a function and returning a list
<p>I have a pandas dataframe which looks like this one:</p> <pre><code>Name A_x B_x C_x A_y B_y C_y ab xyz 2 abc123 xyz 2 abc123 cd yza 2 def456 zab 1 NaN ef zab 3 jkl012 abc 3 jkl012 </code></pre> <p>What I now want to do is to compare columns <code>A_x</code> with <code>A_y</code>, <code>B_x</code> with <code>B_y</co...
<p>Solution reshape DataFrame for 2 columns <code>x</code> and <code>y</code> by split columns names by <code>_</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a>, replace missing values and compare in <a...
python|pandas|function|dataframe
1
365,991
66,859,129
Calculate a running return in pandas df
<p>I have a df with daily return rates. I inserted a column to start with an initial investment of $100 for day 1. I'm trying to calculate the running return each day as below</p> <pre><code>import pandas as pd d = {'day': [1, 2, 3], 'return': [1.00, 1.04, 1.02], 'init_invest': [100, 0, 0]} df = pd.DataFrame(data=d) <...
<p>For your case, since you know all the returns, you can use that directly for calculation.</p> <pre><code>Day 1 value is given. Day 2 value = day 1 value * 1.04 = 104 Day 3 value = day 1 value * 1.04 * 1.02 = 106.08 </code></pre> <pre><code>df[&quot;init_invest&quot;] = df[&quot;return&quot;].cumprod() * df[&quot;in...
python|pandas|rolling-computation
1
365,992
67,078,073
Create Grand Mean Centered Variables by Group Means in Pandas
<p>I am trying to create grand mean centered variables by groups.</p> <p>The sample data is:</p> <pre><code>import pandas as pd import numpy as np dat = { 'group': ['1', '1', '1', '2', '2', '1', '2'], 'age': [40, 29, 34, 35, 37, 32, 36], 'weight': [150, 175, 135, 125, 189, 178, 137], 'score': [98.0, 77...
<p>If you are okay for another solution , what you do can also be done by <code>groupby.transform</code> directly.</p> <pre><code>out = ((df.groupby(&quot;group&quot;).transform(&quot;mean&quot;)-df.mean()) .fillna({&quot;group&quot;:df['group']}).reindex(columns=df.columns)) </code></pre> <hr /> <pre><code>prin...
python-3.x|pandas|dataframe|pandas-groupby|aggregate
2
365,993
67,075,889
How to fill NANs with values tending to zero until the next valid value?
<p>While resampling a dataframe (df) as:</p> <pre><code>df = pd.DataFrame.from_dict({'2021-03-02': 442, '2021-03-04': 520, '2021-03-09': 390, '2021-03-11': 442, '2021-03-16': 520, '2021-03-23': 520, '2021-03-25': 520, '2021-03-26': 442,}, orient='index',) df.index = pd.to_datetime(df.index) df = df.resample('30Min').a...
<p>There's no built-in function for this. You can create one quickly like this:</p> <pre><code># group of rows starting with non-nan groups = df[0].groupby(df[0].notnull().cumsum()) # output out = df[0].ffill().mul(1-groups.cumcount()/ groups.transform('size')) # plot out.plot() </code></pre> <p>And you get:</p> <p><...
python-3.x|pandas
2
365,994
67,007,760
Get the max value from each group with pandas.DataFrame.groupby
<p>I need to aggregate two columns of my dataframe, count the values of the second columns and then take only the row with the highest value in the &quot;count&quot; column, let me show:</p> <pre><code>df = col1|col2 --------- A | AX A | AX A | AY A | AY A | AY B | BX B | BX B | BX B | BY B | BY C...
<p>From your original DataFrame you can <code>.value_counts</code>, which returns a descending count within group, and then given this sorting <code>drop_duplicates</code> will keep the most frequent within group.</p> <pre><code>df1 = (df.groupby('col1')['col2'].value_counts() .rename('counts').reset_index() ...
python|pandas
4
365,995
66,765,622
Coreml: How to add two tensors on slices?
<p>I have two tensors: a.shape = [1, 3, 80, 80, 2] and b.shape = [1, 3, 80, 80, 19] and I only want to add b[..., 0:2] + a using the coreml model builder.</p> <p>Something like this</p> <pre><code>b[..., 0:2] = (b[..., 0:2] * 2. - 0.5 + a) </code></pre>
<p>Slice b into two parts, modify the 0:2 slice, then concatenate this back with the other slice of b into a (1, 3, 80, 80, 19) tensor.</p>
python|numpy|coreml|coremltools
0
365,996
67,174,175
Get an item value from a nested dictionary inside the rows of a pandas df and get rid off the rest
<p>I implemented <a href="https://demo.allennlp.org/open-information-extraction" rel="nofollow noreferrer">allennlp's OIE</a>, which extracts subject, predicate, object information (in the form of ARG0, V, ARG1 etc) embedded in nested strings. However, I need to make sure that each output is linked to the given <code>I...
<p>Your second idea should do the trick:</p> <pre class="lang-py prettyprint-override"><code>import ast df[&quot;OIE Triples&quot;] = df[&quot;OIE output&quot;].apply(ast.literal_eval) df[&quot;OIE Triples&quot;] = df[&quot;OIE Triples&quot;].apply(lambda val: [a_dict[&quot;description&quot;] ...
python|pandas|triples|allennlp
2
365,997
66,812,345
Getting an error in Activation function "TypeError: 'Tensor' object is not callable"
<p>I am trying to use the relu activation function in pytorch LSTM but getting the error on &quot; Tensor object is not callable. any guideline or help? Can i use the different activation function in forward propogation? but i am using the same activation function in hidden layers and forward propogation. your kind rev...
<pre><code>self.relu = nn.functional.relu(torch.FloatTensor(hidden_layer_size), torch.FloatTensor(output_size)) </code></pre> <p>This line doesn't really define a <code>ReLU</code> function for further use, but instead it <em>applies</em> the <code>ReLU</code> function to an arbitrary tensor (which is <code>torch....
python|pytorch|lstm
0
365,998
66,841,054
When using torch.backward() for a GANs generator, why doesn't discriminator losses change in Pytorch?
<p>My understanding of GANs is:</p> <ol> <li><p>When training your generator, you need to back-propagate through the discriminator first so you can follow the chain rule. As a result, we can't use a <code>.detach()</code> when working on our generators loss calculation.</p> </li> <li><p>When updating discriminator, si...
<p><code>backward</code> doesn't update the weights, it updates the gradients of the weights. Updating weights is the responsibility of the optimizer(s). There are different ways to implement GANs, but often you would have two optimizers, one that is responsible for updating the weights (and resetting the gradients) of...
python|pytorch|generative-adversarial-network
1
365,999
66,833,117
Is there a Pandas function that can group the hourly data of each day like 2021-01-01 01:00:00 to 2021-01-02 00:00:00 as one group and so on
<p>I've this dataset that contains data observed after each hour of the day. Since the observation is done after every hour, the data starts from 01:00:00 hour and ends at 00:00:00 of the next day.</p> <p>Is there a way to group these data into a single day starting from hour 01 and ends at hour 00 .</p> <blockquote> <...
<p>You could create a helper column, which is 'DateTime' minus one hour, and use that for grouping.</p> <p>EX:</p> <pre><code>import pandas as pd df = pd.DataFrame({'DateTime': [&quot;2020-01-01 01:00&quot;, &quot;2020-01-02 00:00&quot;, &quot;2020-01-02 01:00&quot;, &quot;2020-01-03 00...
python|pandas|datetime
1