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
5,800
72,234,859
Why won't PyTorch RNN accept unbatched input?
<p>I'm trying to train a PyTorch RNN to predict the next value in a 1D sequence. According to the PyTorch documentation page, I think I should be able to feed unbatched input to the RNN with shape [L,H_in] where L is the length of the sequence and H_in is the input length. That is, a 2D vector.</p> <p><a href="https://...
<p>I would recommend turning your input into a 3d array by adding a batch size of one with:</p> <pre><code>torch.unsqueeze(x1_input, dim=0). </code></pre>
pytorch|recurrent-neural-network
1
5,801
72,170,346
DATAFRAME TO BIGQUERY - Error: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmp1yeitxcu_job_4b7daa39.parquet'
<p>I am uploading a dataframe to a bigquery table.</p> <pre><code>df.to_gbq('Deduplic.DailyReport', project_id=BQ_PROJECT_ID, credentials=credentials, if_exists='append') </code></pre> <p>And I get the following error:</p> <pre><code>OSError Traceback (most recent call last) ~/.local/l...
<p>As Ricco D has mentioned, when writing the dataframe to the table, the BigQuery client creates temporary files on the host system, then removes it once the dataframe is written. The <a href="https://github.com/googleapis/python-bigquery/blob/main/google/cloud/bigquery/client.py#L2621-L2675" rel="nofollow noreferrer"...
pandas|dataframe|google-bigquery
1
5,802
72,203,472
How to return the loc/index (row and column) of a searched item in Pandas dataframe
<p>I am searching for a sub-string in a Pandas dateframe.</p> <pre><code>tmp = Metadata_sheet_0.apply(lambda row: row.astype(str).str.contains('sRNA spacer'), axis=1) </code></pre> <p>It returns a dataframe of the same size, with every element True or False. I would like the indexes of all Trues, not another dataframe ...
<p>Assuming such example:</p> <pre><code>df = pd.DataFrame([[1,2,3],[4,1,2],[1,5,1]], columns=list('ABC')) A B C 0 1 2 3 1 4 1 2 2 1 5 1 </code></pre> <p>you can use a boolean mask and <code>stack</code>:</p> <pre><code>df.where(df.eq(1)).stack() </code></pre> <p>output:</p> <pre><code>0 A 1.0 1 B ...
pandas|string|dataframe|search|indexing
1
5,803
72,315,271
How do you view the first non zero number in an NumPy array?
<p>I have a cube a = numpy.array(n,n,n). The size will vary.</p> <p>I want to look from the top, so down on the columns, which there are nxn of, and return an array (n,n) with the first non zero number you can 'see'.</p> <p>This is like looking down on the array imagining zeros are holes.</p> <p>I can use sum(a, axis=0...
<p>from what I understand you can use non zero function with slicing. refer to : <a href="https://numpy.org/doc/stable/reference/generated/numpy.nonzero.html" rel="nofollow noreferrer">https://numpy.org/doc/stable/reference/generated/numpy.nonzero.html</a></p>
python|numpy
0
5,804
72,211,665
I'm having problems with one-hot encoding
<p>I am using logistic regression for a football dataset, but it seems when i try to one-hot encode the home team names and away team names it gives the model a 100% accuracy, even when doing a train_test_split i still get 100. What am i doing wrong?</p> <pre><code>from sklearn.linear_model import LogisticRegression f...
<p>Overfitting would be a situation where your training accuracy is very high, and your test accuracy is very low. That means it's &quot;over fitting&quot; because it essentially just learns what the outcome will be on the training, but doesn't fit well on new, unseen data.</p> <p>The reason you are getting 100% accura...
numpy|scikit-learn
0
5,805
50,364,991
how to push live panda Dataframe and index it to fit it in my Tkinter table?
<p>I am trying to push my mqtt data to my tkinter table, which i have created using <a href="http://github.com/dmnfarrell/pandastable" rel="nofollow noreferrer">pandastable</a> module. I am getting data in form of a list. So i first created a csv file, and i labeled it manually. And then i pushed my list to that csv fi...
<p>Convert this to a dictionary instead of a Dataframe and I think it will work:</p> <pre><code>datalist=[date_today,time_today]+self.data datalist1=np.array(datalist) datalist2=pd.DataFrame(data=datalist1 ,columns=['Date','Time','power state','Motor state','Mode','Voltage','Current','Power Factor','KW','KWH','total R...
python-3.x|pandas|tkinter
0
5,806
62,834,697
copy of array gets overwritten in function
<p>I am trying to create an array <code>np.zeros((3, 3))</code> outside a function and use it inside a function over and over again. The reason for that is <code>numba's</code> <code>cuda</code> implementation, which does not support <code>array creation</code> inside functions that are to be run on a <code>gpu</code>....
<p>simple assignment will only assign pointer, so when you change <code>ar</code>, <code>ar_ref</code> changes too. try to use shallow copy for this issue</p> <pre><code>import numpy as np import copy def function(ar_ref=None): for n in range(3): print(n) ar = copy.copy(ar_ref) print(ar) ...
python|arrays|numpy
2
5,807
54,485,768
Data Manipulation using Pandas
<p>I want to copy a value in a dataframe uptil next NaN.</p> <p>Here is the dataframe I have:</p> <pre><code> Description 0 091SS16 GASOILA THREAD SEALANT 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN 7 3M07447...
<p>You need <code>fillna</code> with <code>ffill</code>:</p> <pre><code>df.fillna(ffill) </code></pre>
python|pandas
1
5,808
54,617,326
Cleaning of data in pandas
<p>I have a data frame in the following format:</p> <pre><code> Col Honda [edit] Accord (4 models)[1] Civic (4 models)[2] Pilot (3 models)[1] Toyota [edit] Prius (4 models)[1] Highlander (3 models)[4] Ford [edit] Explorer (2 models)[1] </code></pre> <p>I want data in the following forma...
<p>Create boolean mask for test string <code>[edit]</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>str.contains</code></a>, then split column by whitespace with first <code>(</code> or <code>[</code>, replace not matched values t...
python|pandas|dataframe
2
5,809
73,697,251
Skipping certain folders in Python
<p>Is there a way to skip certain folders? In the present code, I specify number of folders <code>N=20</code> i.e. the code analyzes all folders named <code>1,2,...,20</code>. However, in this range, I want to skip certain folders, say <code>10,15</code>. Is there a way to do so?</p> <pre><code>import pandas as pd impo...
<p>Just add a test to skip the unwanted numbers:</p> <pre><code> N = 20 # Number of folders skip = {10,15} # using a set for efficiency for i in range(1,N): if i in skip: continue # rest of code </code></pre> <p><em>NB. If you want to include 20, you should use <code>range(1, N+1)</code>.</em></p>
python|pandas|numpy|statistics
2
5,810
73,767,659
How to add rows according to other column
<p>now the result looks like this</p> <pre><code>file_name text 1 2a.txt 0 0.712518 0.61525 0.43918 0.2065 1 0.635078 0.81175 0.292786 0.0925 2b.txt 2 0.551273 0.5705 0.30198 0.0922 0 0.550212 0.31125 0.486563 0.2455 <...
<p>That should help:</p> <pre><code>df = pd.melt(df,id_vars='file_name' ,value_vars=['text','1']) df = df.drop('variable', axis=1) df = df.sort_values(by = 'file_name') </code></pre>
pandas|dataframe|duplicates
0
5,811
73,819,387
Can't read a .xlsx/.csv file while I have it open in my Excel
<p>I got that error everytime I try to read a .xlsx/.csv file in my Jupyter Notebook using Pandas and the file is currently open in my Excel:</p> <pre><code>import pandas as pd df = pd.read_excel('Filename.xlsx') PermissionError: [Errno 13] Permission denied: 'Filename.xlsx' </code></pre> <p>I have a friend that could...
<p>close all your open excel/csv files then try to read the file.</p> <p>For csv files:</p> <pre><code>import pandas as pd df = pd.read_csv('filename.csv') </code></pre> <p>For excel file:</p> <pre><code>pip install xlrd import pandas as pd df = pd.read_excel('filename.xlsx') </code></pre>
python|pandas|dataframe|jupyter-notebook|data-science
-1
5,812
71,303,701
How can I let my function return all values of a NumPY array columnwise?
<p>So I have this set of data:</p> <pre><code>[[ 99.14931546 104.03852715 107.43534677 97.85230675 98.74986914 98.80833412 96.81964892 98.56783189] [ 92.02628776 97.10439252 99.32066924 97.24584816 92.9267508 92.65657752 105.7197853 101.23162942] [ 95.66253664 95.17750125 90.93318132 110.18889465 9...
<p>Example for the first 2 samples (accordingly to @enke):</p> <pre><code>arr = np.array([[ 99.14931546, 104.03852715, 107.43534677, 97.85230675, 98.74986914, 98.80833412, 96.81964892, 98.56783189], [ 92.02628776, 97.10439252, 99.32066924, 97.24584816, 92.9267508, 92.65657752, 105.7197853, 101.23162942...
arrays|numpy|numpy-ndarray
0
5,813
71,180,682
Can't iterate through excel or .csv with pandas or openpyxl
<p>I'm trying to iterate through a column of a pandas dataframe from .csv with pandas, and I've tried .xlsx with openpyxl, and copy to a new dataframe if the string contains substring &quot;Leading Edge&quot;. I'm getting the error &quot;TypeError: argument of type 'float' is not iterable&quot; even though the columns ...
<p>You can't iterate an int, you can only iterate sequence types (such as <strong>list</strong>, <strong>str</strong>, and <strong>tuple</strong>) and some non-sequence types (like <strong>dict</strong>, <strong>file objects</strong>, and objects of any classes you define with an <strong>iter</strong>() method or with ...
python|pandas|openpyxl
0
5,814
71,239,632
Creating custom loss function, error with unstacking tensor in tensorflow, python
<p>Creating a weighted gaussian loss function for use in deep learning models and getting the following error message when running model.fit for training data</p> <blockquote> <p>ValueError: Dimension must be 2 but is 1 for '{{node gaussian_loss/unstack_1}} = UnpackT=DT_FLOAT, axis=-1, num=2' with input shapes: [?,1].<...
<p>Your loss function is expecting <code>y_true</code> (which is data coming from your <code>y_train</code> that you passed to <code>fit</code>) to have two elements in the last dimension for unstacking in <code>truevals</code> and <code>dummy</code>.</p> <p>One solution is making <code>truevals = y_true</code>, since ...
python|tensorflow|keras|deep-learning|loss-function
1
5,815
52,444,921
Save Numpy Array using Pickle
<p>I've got a Numpy array that I would like to save (130,000 x 3) that I would like to save using Pickle, with the following code. However, I keep getting the error "EOFError: Ran out of input" or "UnsupportedOperation: read" at the pkl.load line. This is my first time using Pickle, any ideas?</p> <p>Thanks,</p> <p>A...
<p>You should use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.save.html" rel="noreferrer">numpy.save</a> and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.load.html#numpy.load" rel="noreferrer">numpy.load</a>.</p>
python|numpy|pickle
52
5,816
52,439,468
Keras: How to take random samples for validation set?
<p>I'm currently training a Keras model whose corresponding fit call looks as follows:</p> <pre><code>model.fit(X,y_train,batch_size=myBatchSize,epochs=myAmountOfEpochs,validation_split=0.1,callbacks=myCallbackList) </code></pre> <p><a href="https://github.com/keras-team/keras/issues/597#issuecomment-394642797" rel="no...
<p>Keras doesn't provide any more advanced feature than just taking a fraction of your training data for validation. If you need something more advanced, like stratified sampling to make sure classes are well represented in the sample, then you need to do this manually outside of Keras (using say, scikit-learn or numpy...
python|tensorflow|keras
3
5,817
52,206,505
toPandas() error using pyspark: 'int' object is not iterable
<p>I have a pyspark dataframe and I am trying to convert it to pandas using toPandas(), however I am running into below mentioned error. <br></p> <p>I tried different options but got the same error:<br>1) limit the data to just few records <br>2) used collect() explicitly (which I believe toPandas() uses inherently) <...
<p>Our custom repository of libraries had a package for pyspark which was clashing with the pyspark that is provided by the spark cluster and somehow having both works on Spark shell but does not work on a notebook. <br>So, renaming the pyspark library in the custom repository resolved the issue!</p>
pandas|apache-spark|pyspark|apache-zeppelin
1
5,818
60,488,705
Why Numpy's int datatype is not of the same type as Numpy's int64 datatype?
<p>Why does this give me false?</p> <pre><code>isinstance(np.int32(3.0),np.int) </code></pre>
<p>Because <code>np.int</code> is the same as python <code>int</code> data type. </p> <p>Check <a href="https://stackoverflow.com/a/46416257/8353711">Difference between np.int, np.int_, int, and np.int_t in cython</a> for more info.</p> <pre><code>&gt;&gt;&gt; np.int &lt;class 'int'&gt; </code></pre> <p>To check wit...
python|python-3.x|numpy
1
5,819
60,417,369
dataframe.to_sql into Teradata (this user does not have permission to create on LABUSERS) Datalab Table name
<p>I have an issue with the <code>dataframe.to_sql</code> when trying to use this function</p> <p>The <code>dataframe.to_sql</code> does not recognize or separate the data lab name and the table name, instead it takes it all as a string to create a table. So it is trying to create it on the default root level and give...
<p><code>schema</code> (str, optional)</p> <p>Specify the schema (if database flavor supports this). If None, use default schema.</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html" rel="nofollow noreferrer">to_sql documentation</a></p>
python|pandas|sqlalchemy|teradata
1
5,820
60,636,991
Assigning value in a column based on values on many other columns in dataframe
<p>I have a dataframe like that contains of 5 columns , I want to update one column based on the other 4 columns, the dataframe looks like that</p> <pre><code>from via to x y 3 2 13 in out 3 2 15 in out 3 2 21 in o...
<p>I cannot find exactly the same result, but I have used the described algo:</p> <pre><code># identify the lines where a change will occur and store the index and the new value tmp = df.assign(origix=df.index).merge(df[~df['x'].isna() &amp; ~df['y'].isna()], left_on = ['from',...
python|pandas|dataframe|multiple-columns
0
5,821
72,681,091
Subtract df1 from df2, df2 from df3 and so on from all data from folder
<p>I have a few data frames as CSV files in the folder.</p> <p>example1_result.csv</p> <p>example2_result.csv</p> <p>example3_result.csv</p> <p>example4_result.csv</p> <p>example5_result.csv</p> <p>My each data frame looks like following</p> <pre><code> TestID Result1 Result2 Result3 0 0 5 ...
<pre><code>import pandas as pd df1 = pd.read_csv(&quot;file1.csv&quot;) df2 = pd.read_csv(&quot;file2.csv&quot;) dfresult = pd.DataFrame() dfresult[&quot;Result1&quot;] = df2[&quot;Result1&quot;] - df1[&quot;Result1&quot;] # do for all columns dfresult.to_csv(&quot;result.csv&quot;) </code></pre>
python|pandas|dataframe|subtraction
0
5,822
40,373,897
tensorflow map_fun indexing
<p>I am trying to use the tensorflow map function but I am stuck at an indexing problem. </p> <p>In simple python, I am trying to do the following operation:-</p> <pre><code>for i in range(1,25): u [i] = uold [i] - K * ( uold [i] - uold [i-1] ) </code></pre> <p>In tensorflow, I am encountering an indexing issu...
<p>You probably want to create a tensor that shifts to right by one dimension (using <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/array_ops.html#pad" rel="nofollow noreferrer">tf.pad()</a>) instead, and then calculate the difference. Ex.</p> <pre><code>temp = uold_shifted_to_right - K * (uold - ...
python|tensorflow
1
5,823
40,721,057
Multiply two matrix by columns with python
<p>I have two matrix:</p> <pre><code>A = [a11 a12 a21 a22] B = [b11 b12 b21 b22] </code></pre> <p>And I want to multiply all its columns (without loops) in order to obtain the matrix:</p> <pre><code>C =[a11*b11 a11*b12 a12*b11 a12*b12 a21*b21 a21*b22 a22*b21 a22*b22] </code></pre> <p>I...
<p>We could use <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>broadcasting</code></a> for a vectorized solution -</p> <pre><code>(A[...,None]*B[:,None]).reshape(A.shape[0],-1) </code></pre> <p><strong>Philosophy :</strong> In terms of vectorized/broadcasting ...
python|numpy|matrix|vectorization
8
5,824
40,577,096
why loss changes value after I add additional inference with reuse = True
<p>In tensorflow example cifar10, the loss value changes after I add one more inference with reuse = True to the graph. </p> <p>Originally:</p> <pre><code>2016-11-13 06:08:04.936044: step 0, loss = 4.68 (6.5 examples/sec; 19.787 sec/batch) </code></pre> <p>After my change: </p> <pre><code>2016-11-13 06:00:50.40091...
<p>parameter reuse is True means logits and logits2 use the same model to get their output, if reuse is False, logits and logits2 come from different model for more information to understand what I said, you can watch this: <a href="https://www.tensorflow.org/programmers_guide/variable_scope" rel="nofollow noreferrer">...
tensorflow
0
5,825
40,368,984
Solving a BVP on a fixed non-uniform grid in python without interpolating
<p>I am aware of <code>scipy.solve_bvp</code> but it requires that you interpolate your variables which I do not want to do. </p> <p>I have a boundary value problem of the following form:</p> <p><code>y1'(x) = -c1*f1(x)*f2(x)*y2(x) - f3(x)</code></p> <p><code>y2'(x) = f4(x)*y1 + f1(x)*y2(x)</code></p> <p><code>y1(x...
<p>This is a new function, and I don't have it on my <code>scipy</code> version (0.17), but I found the source in <code>scipy/scipy/integrate/_bvp.py</code> (github).</p> <p>The relevant pull request is <a href="https://github.com/scipy/scipy/pull/6025" rel="nofollow noreferrer">https://github.com/scipy/scipy/pull/602...
python|numpy|math|scipy|differential-equations
1
5,826
40,703,751
using Fourier transforms to do convolution?
<p>According to the <a href="https://en.wikipedia.org/wiki/Convolution_theorem#Convolution_theorem_for_inverse_Fourier_transform" rel="nofollow noreferrer">Convolution theorem</a>, we can convert the Fourier transform operator to convolution.</p> <p>Using Python and Scipy, my code is below but not correct. Can you help...
<p>The problem may be in the discrepancy between the discrete and continuous convolutions. The convolution kernel (i.e. y) will extend beyond the boundaries of x, and these regions need accounting for in the convolution.</p> <p>scipy.signal.convolve will by default pad the out of bounds regions with 0s, which will bia...
python|numpy|filter|fft|convolution
4
5,827
61,894,629
ValueError: Length of values does not match length of index in nested loop
<p>I'm trying to remove the stopwords in each row of my column. The columns contains rows and the rows since i already <code>word_tokenized</code> it with <code>nltk</code> then now it's a list which contains tuples. I'm trying to remove the stopwords with this nested list comprehension but it says <code>ValueError: Le...
<p>Read the error message carefully:</p> <blockquote> <p>ValueError: Length of values does not match length of index</p> </blockquote> <p>The "values" in this case is the stuff on the right of the <code>=</code>:</p> <pre class="lang-py prettyprint-override"><code>values = [word for new in data['new'] for word in ...
python|pandas|for-loop|nltk|list-comprehension
3
5,828
61,930,274
fastest way to get max value of each masked np.array for many masks?
<p>I have two numpy arrays of the same shape. One contains information that I am interested in, and the other contains a bunch of integers that can be used as mask values.</p> <p>In essence, I want to loop through each unique integer to get each mask for the array, then filtered the main array using this mask and find...
<h3>Generic bin-based reduction strategies</h3> <p>Listed below are few approaches to tackle such scenarios where we need to perform bin-based reduction operations. So, essentially we are given two arrays and we are required to use one as the bins and the other one for values and reduce the second one.</p> <p><strong>A...
python|numpy|mask
2
5,829
61,756,355
How to change a value in pandas df when itering rows
<pre><code> counter = 0 for _ in df.iterrows(): print(df.loc[df['descrizione'] == alimenti[counter][0]]) counter += 1 </code></pre> <p>I have a dataframe and I want to change a value of a different column ('quantita') in the same row of<br> (df.loc[df['descrizione'] == alimenti[counter][...
<p>you don't need manually iterating over rows.</p> <pre><code>df.loc[df['descrizione'] == alimenti[counter][0], 'descrizione'] = 'quantita'` # or df.loc[df['descrizione'] == alimenti[counter][0], 'quantita'] = 50` </code></pre>
python|pandas
1
5,830
58,151,779
Search column for specific phrases and count the amount of times they appear in the column and plot to bar graph
<p>Search column for each month of the year. Column is organized like this "01-Jan-2018". I want to find how many times "Jan-2018" appears in the column. Basically count it and plot it on a bar graph. I want it to show all the quantities for "Jan-2018" , "Feb-2018", etc. Should be 12 bars on the graph. Maybe using coun...
<p>IIUC, this is what you need.</p> <p>Let's work with the below dataframe as input dataframe.</p> <pre><code> date 0 1/31/2018 1 2/28/2018 2 2/28/2018 3 3/31/2018 4 4/30/2018 5 5/31/2018 6 6/30/2018 7 6/30/2018 8 7/31/2018 9 8/31/2018 10 9/30/2018 11 9/30/2018 12 9/30/2018 13 9/30/2018 14 ...
python|pandas|csv|matplotlib|seaborn
0
5,831
57,993,200
How to extract a geopandas plot as a numpy array that consists of numerical values of the pixels?
<p>I have a GeoDataFrame and I want to get a numpy array that corresponds to the GeoDataFrame.plot(). </p> <p>At the moment, my code looks like this:</p> <pre><code>import numpy as np import geopandas as gpd from shapely.geometry import Polygon import matplotlib.pyplot as plt from PIL import Image # Create GeoDataFr...
<p>I found a working solution for me. Instead of saving and opening every picture as .png, I use matplotlib "backend agg to acces the figure canvas as an RGB string and then convert it ot an array" (<a href="https://matplotlib.org/3.1.0/gallery/misc/agg_buffer.html" rel="nofollow noreferrer">https://matplotlib.org/3.1....
python|matplotlib|geopandas|shapely
1
5,832
34,057,165
Numpy: Clever way of accomplishing v[np.arange(v.shape[0]), col_indices] = 1?
<p>Suppose I have a matrix v:</p> <pre><code>0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 </code></pre> <p>I also have a vector col_indices = [0,0,1,2,2,1] that indicates which column I should put an 1 for each row of matrix v.</p> <p>The result of the task, in this case, should be:</p> <pre><code>1 0 0 1 0 0 0 1 0 0 0 1 0 ...
<p>That IS the cleaver way of doing the indexing.</p> <p>Look at these timings. Generating that array does not take long. Actually indexing those points takes much longer.</p> <pre><code>In [208]: x=np.zeros((10000,10000)) In [209]: timeit np.arange(x.shape[0]),np.arange(x.shape[1]) 10000 loops, best of 3: 23.5 us...
python|numpy
4
5,833
34,275,251
applying step function when reassigning pandas row
<p>I have two pandas tables, <code>d</code> and <code>num_original_introns</code>. They are both indexed with the same non-numeric index. I want to apply a step function to transform <code>d</code> based on values in <code>d</code> and <code>num_original_introns</code>, like so:</p> <pre><code>d["HasOriginalIntrons"] ...
<p>To have multiple logical conditions, each one needs to be enclosed in parentheses with an ampersand in-between. For example:</p> <pre><code>d["HasOriginalIntrons"] = (num_original_introns["NumberIntrons"] != 0) &amp; \ ( d["HasOriginalIntrons"] &gt;= ...
python|pandas
0
5,834
34,287,449
Python Numpy unsupported operand types 'list' - 'list'
<p>I have some problem. I want to substract one list from another. For that I use conversion from python array to numpy array. But it failed. For example, <code>wealthRS</code> is the list. I create a copy: <code>wealthRSCopy = wealthRS</code> Then I want to sustract, but it is error (<code>unsuppoerted operand types</...
<p><strong>Edit with answer:</strong></p> <p>You initial lists have lists as their elements. These lists are of different length, so casting to NumPy arrays makes arrays of dtype object, ie the elements of your arrays are <em>lists</em>. See here: <a href="https://stackoverflow.com/a/33987165/4244912">https://stackove...
python|arrays|list|numpy
1
5,835
36,759,987
How to normalize scipy's convolve2d when working with images?
<p>I'm using scipy's convolve2d:</p> <pre><code>for i in range(0, 12): R.append(scipy.signal.convolve2d(self.img, h[i], mode = 'same')) </code></pre> <p>After convolution all values are in magnitudes of 10000s, but considering I'm working with images, I need them to be in the range of 0-255. How do I nor...
<p>Assuming that you want to normalize within one single image, you can simply use <code>im_out = im_out / im_out.max() * 255</code> . </p> <p>You could also normalize kernel or original image.</p> <p>Example below.</p> <pre><code>import scipy.signal import numpy as np import matplotlib.pyplot as plt from skimage im...
python|opencv|numpy|scipy
2
5,836
54,843,448
How to "zip" Tensorflow Dataset and train in Keras correctly?
<p>I have a <code>train_x.csv</code> and a <code>train_y.csv</code>, and I'd like to train a model using Dataset API and Keras interface. This what I'm trying to do:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd import tensorflow as tf tf.enable_eager_execution() N_FEATUR...
<p>The problem is in the input shape of your dense layer. It should match shape of your input tensor, which is 1. <code>tf.keras.layers.Dense(N_OUTPUTS, input_shape=(features_shape,))</code></p> <p>Also you might encounter problems defining <code>model.fit()</code> <code>steps_per_epoch parameter</code>, it should be...
python|tensorflow|keras
2
5,837
54,891,381
Change day to specific entries in pandas dataframe
<p>I have a dataframe in pandas which has an error in the index: each entry between 23:00:00 and 23:59:59 has a wrong date. I would need to subtract one day (i.e. 24 hours) to each entry between those two times. </p> <p>I know that I can obtain the entries between those two times as <code>df[df.hour == 23]</code>, wh...
<p>I solved the issue myself by using <a href="https://stackoverflow.com/a/40428133/6014171">this answer</a>. This is my code:</p> <pre><code>as_list = df.index.tolist() new_index = [] for idx,entry in enumerate(as_list): if entry.hour == 23: if entry.day != 1: new_index.append(as_l...
python|pandas|datetime|dataframe
0
5,838
49,361,068
pandas: convert nested json to flattened table
<p>I have a JSON of the following structure:</p> <pre><code>{ "a": "a_1", "b": "b_1", "c": [{ "d": "d_1", "e": "e_1", "f": [], "g": "g_1", "h": "h_1" }, { "d": "d_2", "e": "e_2", "f": [], "g": "g_2", "h": "h_2" }, { ...
<hr> <p><strong>Before Reading</strong></p> <ul> <li>This do the Job as presented in the Question, if some additionnal specificities, please communicate it.</li> <li>This surely can be improved, take it as a possible solution to your problem</li> <li>Please note that the key to solve your problem leads in <a href="ht...
python|json|pandas|dataframe
0
5,839
27,963,577
Optimizing histogram distance metric for two matrices in Python
<p>I have two matrices <code>A</code> and <code>B</code>, each with a size of <code>NxM</code>, where <code>N</code> is the number of samples and <code>M</code> is the size of histogram bins. Thus, each row represents a histogram for that particular sample.</p> <p>What I would like to do is to compute the <code>chi-sq...
<p>Sure! I'm assuming you're using <a href="http://www.numpy.org/" rel="nofollow">numpy</a>?</p> <p>If you have the RAM available, you could use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">broadcast</a> the arrays and use numpy's efficient vectorization of the operations on t...
python|algorithm|optimization|numpy|matrix
1
5,840
28,253,779
Python Pandas Setting Dataframe index and Column names from an array
<p>Lets say I have data loaded from an spreadsheet:</p> <pre><code>df = pd.read_csv('KDRAT_2012.csv', index_col=0, encoding = "ISO-8859-1",) 0 1 2 3 4 5 6 7 8 9 0 -5.53 -6.69 -6.29 -5.76 -7.74 -7.66 -6.27 -4.13 -3.08 0.00 1 -5.52 -6.68 -6.28 -5.75 -7.73 -7.65 -6.26 -4.12 -3...
<p>How about <code>df.index = colnames['Names']</code> for example:</p> <pre><code>In [77]: df = pd.DataFrame(np.arange(18).reshape(6,3)) In [78]: colnames = pd.DataFrame({'Names': ['A', 'B', 'C', 'D', 'E', 'F'], 'foo': [0, 1, 0, 0, 0, 0]}) In [79]: df.index = colnames['Names'] In [80]: df Out[8...
python|pandas
2
5,841
28,054,501
Mask values that are not in sort order in numpy
<p>I have a complex calculation which I expect the result to be an array where values are in sorted order. However, because of numerical errors at some critical points, some resulting values are wrong. I'd like to mask those values. How should I do that?</p> <p>Here is an equivalent function, but that assume values ar...
<p>When <code>a</code> is supposed to be decreasing, you can use:</p> <pre><code>mask = a &gt; np.minimum.accumulate(a) </code></pre> <p>and when <code>a</code> is supposed to be increasing, you can use:</p> <pre><code>mask = a &lt; np.maximum.accumulate(a) </code></pre> <p>(<code>np</code> is <code>numpy</code>.)<...
python|numpy
5
5,842
73,268,015
Pandas - get columns where all values are unique (distinct)
<p>I have a dataframe with many column and I am trying to get the columns where all values are unique (distinct).</p> <p>I was able to to this for columns without missing values:</p> <pre><code>df.columns[df.nunique(dropna=False) == len(df)] </code></pre> <p>But I can't find a simple solution for columns with NaNs</p>
<p>This will print all columns that contains unique values excluding NaN</p> <pre><code>[col for col in df.columns if df[col].dropna().is_unique ] </code></pre> <p>Here is another one liner solution without using loop</p> <pre><code>df.columns[df.apply(lambda x : x.dropna().is_unique, axis=0)] </code></pre> <p>To get i...
python|python-3.x|pandas
2
5,843
73,222,812
Mergining excel sheet in pandas
<p>Having an two excel sheet as follows:</p> <p><a href="https://i.stack.imgur.com/5YJZ6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5YJZ6.jpg" alt="img1" /></a><a href="https://i.stack.imgur.com/g0yV3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g0yV3.jpg" alt="sheet2" /></...
<p>Let's assume you have df1 and df2 and you wanna merge the two dataframes together on the same start here is sample:</p> <pre><code>df = df1.merge(df2, how='outer', on='Start') </code></pre>
python|pandas|data-analysis|merging-data|exploratory-data-analysis
2
5,844
73,488,646
Get the mean value for range of dates from a time series and based on condition
<p>I have two dataframes <code>df1</code> and <code>df2</code>.</p> <p><code>df1</code> contains three columns: <code>Agent</code> and a datetime range (<code>start</code> and <code>end</code>).<br /> <code>df2</code> contains timeseries with three columns: <code>Agent</code>, <code>datetime</code> and <code>value</cod...
<p>Try this:</p> <pre><code>df1['start_date'] = pd.to_datetime(df1['start_date']) df1['end_date'] = pd.to_datetime(df1['end_date']) df2['datetime_log'] = pd.to_datetime(df2['datetime_log']) df = pd.merge(df2, df1, on = 'Agent', how = 'left') df['flag'] = np.where(((df['start_date'] &lt;= df['datetime_log']) &amp; (d...
python|pandas|dataframe|datetime
0
5,845
73,216,211
how to reshape a matrix to 3D but I found that matlab will do this according to column
<p>I was trying to transform a python program to matlab and I found that the transpose function cannot be realized in matlab. In python it goes as the first picture. But in Matlab, I found it read by column, which is so different from python. And I use cat and reshape function in Matlab, I cannot find one way to realiz...
<p>To have the same shape (in the sense that the same tuple of indices would access the same elements) you should use:</p> <pre class="lang-matlab prettyprint-override"><code>a = 0:1:99; % Note that your python code goes from 0 to 99, not from 1 to 100 b = reshape(a, 10, 10); b = b'; % This puts b in a similar order ...
python|numpy|matlab
0
5,846
73,340,033
How to combine multiple rows into a single row with many columns in pandas using an id (clustering multiple records with same id into one record)
<p><strong>Situation:</strong></p> <p><a href="https://i.stack.imgur.com/0EdjS.png" rel="nofollow noreferrer">1. all_task_usage_10_19</a></p> <p><em>all_task_usage_10_19</em> is the file which consists of <strong>29229472 rows × 20 columns</strong>. There are multiple rows with the same <em>ID</em> inside the column <s...
<p>The below code worked for me:</p> <pre><code>all_task_usage_10_19.groupby('machine_ID')[['start_time_of_the_measurement_period','end_time_of_the_measurement_period','job_ID', 'task_index','mean_CPU_usage_rate', 'canonical_memory_usage', 'assigned_memory_usage', 'unmapped_page_cache_memory_usage', 'tota...
python|pandas|dataframe
0
5,847
67,264,550
How to add new column by getting the data from each?
<p>I have Dataframe:</p> <pre><code>teamId pts xpts Liverpool 82 59 Man City 57 63 Leicester 53 47 Chelsea 48 55 </code></pre> <p>And I'm trying to add new columns that identify the team position by each column</p> <p>I wanna get this:</p> <pre><code>teamId pts xpts №pts №xpts Liverpool...
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.argsort.html" rel="nofollow noreferrer"><code>np.argsort</code></a>:</p> <pre><code>df[[&quot;no_pts&quot;, &quot;no_xpts&quot;]] = df.apply(lambda x: np.argsort(-x)) + 1 </code></pre> <p>We pass each column but negated so that it gives the ...
pandas
0
5,848
67,451,785
Loop for adding value to last n values in list
<p>I have a list where I would like to +1 to all the values after <em>n</em> in a loop, where <em>n</em> is a row index. I want to repeat this multiple times to achieve the following:</p> <pre><code>original_list = [1,2,3,4,5,6,7] multiples = [3,6] #i.e. index 2 &amp; 5 for i in multiples: Do Something to +1... f...
<pre><code>original_list = np.array([1,2,3,4,5,6,7]) multiples = np.array([3,6]) cs = np.zeros_like(original_list) multiples = np.array(multiples) - 1 # since you are not using 0-index cs[multiples] = 1 original_list + cs.cumsum() </code></pre> <p>Output:</p> <pre><code>array([1, 2, 4, 5, 6, 8, 9]) </code></pre>
python|numpy
2
5,849
67,555,510
Counting occurrences in time interval in a pandas data frame
<p>I have this simple data frame:</p> <pre><code> Date and time Event -------------------------- 2020-03-23 9:05:03 A 2020-03-23 14:06:02 B 2020-03-23 9:06:43C B 2020-03-23 12:11:50 D 2020-03-23 12:12:38 D 2020-03-23 12:13:17 B 2020-03-23 12:14:07 A 2020-03-23 12:14:54 A 2020-04-29 10...
<p>Here's an approach using pandas <code>.groupby()</code>, <code>.explode()</code>, and <code>'.pivot_table()</code></p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame([i.strip().split(' ') for i in ''' 2020-03-23 9:05:03 A ... 2020-03-23 14:06:02 B ... 2020-03-23 9:06:43 B ... ...
python|pandas|datetime|aggregate
0
5,850
60,263,100
Problem with neural network in TensorFlow 2.0
<pre><code>import tensorflow as tf import pandas as pd import numpy as np import matplotlib as plt from sklearn.model_selection import train_test_split from tensorflow import keras from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from sklearn.preprocessing import StandardScaler i...
<p>That's because <code>Endstage</code> is your label column and the framework does a favour to you by removing (popping) it out of your dataset. Otherwise your training data set would have also the target class, rendering it useless. </p> <p>Remove it from <code>NUMERIC_FEATURES</code> and any other place that makes ...
python|pandas|numpy|tensorflow|keras
2
5,851
60,001,958
Save a 3 dimensional array from R to a format to be read by Python numpy
<p>I have a 3-dimensional array in R (numerical), which I want to <em>transfer</em> to Python, i.e. to a 3-dimensional numpy array. How can I do this? I have tried several options, but all of them <em>destroy</em> the 3rd dimension.</p>
<p>Try reticulate to convert the array from R to python. Then save it using numpy (called from within R). </p> <pre><code>## inside R library(reticulate) x = array(runif(27),dim=c(3,3,3)) # import numpy np = import("numpy") np$save("test.npy",r_to_py(x)) </code></pre> <p>Now we load it with python:</p> <pre><code>i...
python|r|arrays|python-3.x|numpy
2
5,852
60,082,233
Error in plotting of frequency histogram from csv data
<p>I am working with a csv file with pandas module on python3. Csv file consists of 5 columns: job, company's name, description of the job, amount of reviews, location of the job; and i want to plot a frequency histogram , where i pick only the jobs containing the words "mechanical engineer" and find the frequencies of...
<p>Something along the following lines should help you with numerical data:</p> <pre><code>import numpy as np counts_, bins_ = np.histogram(englog.values) filtered = [(c,b) for (c,b) in zip(counts_,bins_) if counts_&gt;=5] counts, bins = list(zip(*filtered)) plt.hist(bins[:-1], bins, weights=counts) </code></pre> <p>...
python|python-3.x|pandas|csv|matplotlib
1
5,853
65,263,070
Get a specific string with Regex in Python
<p>I have strings that look alike as below:</p> <pre><code>ART-B-C-ART0015-D-E01 ADC-B-C-ADC00112-V-E01 AEE-B-C-AEE00011-D-E01 AQW-B-C-AQW0013-D-E01 AAZ-B-C-AAZ0014-D-E01 AQQ-B-C-AQQ0032-D-E01 ADD-B-C-D-ADD0001-D-E01 AAA-B-C-AAA0012-D-E01 </code></pre> <p>I want to have the below result: Expected Result:</p> <pre><code...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>Series.str.extract</code></a> by searching for 3 letters followed by <code>4-5</code> numbers:</p> <pre><code>In [477]: df['col'] = df['col'].str.extract(r'([a-zA-Z]{3}\d{4,5})') I...
python|python-3.x|regex|pandas|python-2.7
5
5,854
50,032,197
Tensorflow gradients are 0, weights are not updating
<p>I'm trying to learn TensorFlow after using Keras for a while, and I'm trying to build a ConvNet for CIFAR-10 classification. However, I think I misunderstand something in TensorFlow API, since the weights are not updating even in 1-layer net model.</p> <p>The code for the model is as follows:</p> <pre><code>num_ep...
<p>You are applying softmax two times to the output, once in <code>tf.nn.softmax</code> and again when you apply <code>softmax_cross_entropy</code>. This probably destroys any learning capability in the network.</p>
python|tensorflow|machine-learning|computer-vision|deep-learning
2
5,855
50,055,065
Subtracting values from a row based off other columns
<p>Sorry about the vague title it's hard to explain. It's easier to display. </p> <p>I'm trying subtract values in the same row but based off strings in other columns. Here is an input df:</p> <pre><code>import pandas as pd import numpy as np k = 5 N = 8 d = ({'Time' : np.random.randint(k, k + 100 , size=N), 'E...
<pre><code>import pandas as pd import numpy as np k = 5 N = 8 d = ({'Time' : np.random.randint(k, k + 100 , size=N), 'Events' : ['ABC','DEF','GHI','JKL','ABC','DEF','GHI','JKL'], 'Number1' : ['xx','xx',1,'xx','xx','xx',2,'xx'], 'Number2' : ['xx',1,'xx',1,'xx',2,'xx',2]}) df = pd.DataFrame(data=d) print(d...
python|pandas|loops|dataframe
2
5,856
63,764,945
Can't understand: ValueError: Graph disconnected: cannot obtain value for tensor Tensor
<p>I wrote a architecture similar to this code: <a href="https://keras.io/guides/functional_api/#manipulate-complex-graph-topologie" rel="nofollow noreferrer">https://keras.io/guides/functional_api/#manipulate-complex-graph-topologie</a>:</p> <pre><code> visual_features_input = keras.Input( shape=(1000,), name=&qu...
<p>pay attention to define the input layers correctly when you are building your model</p> <p>they are <code>inputs=[sentence_encoding_input, visual_features_input, et_features_input]</code> and not <code>inputs=[sentence_features, visual_features, et_features]</code></p> <p>here the full model</p> <pre><code>from tens...
python|tensorflow|keras|keras-layer|tf.keras
0
5,857
64,003,734
Cannot download tensorflow model of cahya/bert-base-indonesian-522M
<p>I was going to download <a href="https://huggingface.co/cahya/bert-base-indonesian-522M" rel="nofollow noreferrer">this</a> model, and then I was going to save it later to be used with bert-serving. Since bert-serving only supports tensorflow model, I need to download the tensorflow one and not the PyTorch. The PyTo...
<p>This seems to be purely an issue of your environment.</p> <p>Running the first code sample worked fine for me under Ubuntu 18.04 (I think using at least Ubuntu 16.04 should work as well, Windows 10 I cannot guarantee). I further use <code>transformers</code> 3.1.0, and <code>tensorflow</code> 2.3.0.</p> <p>The first...
bert-language-model|huggingface-transformers
0
5,858
63,872,108
One to many join in python with zero fill in repeated record created due to one to many join
<p>I have two pandas dataframe df1, &amp; df2.The relationship is one to many &amp; I need 0 instead of repeating same value of table with 1 relationship.Here is the sample of my two dataframes &amp; the datafrane after merging df1 looks like</p> <pre><code>Class Section ID Subject Score I A 12 Mat...
<p>A very late answer, but each group can be enumerated with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer">groupby cumcount</a> then the enumeration can be used for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/...
python|pandas
0
5,859
63,939,096
Non-deterministic behavior for training a neural network on GPU implemented in PyTorch and with a fixed random seed
<p>I observed a strange behavior of the final Accuracy when I run exactly the same experiment (the same code for training neural net for image classification) with the same random seed on different GPUs (machines). I use only one GPU. Precisely, When I run the experiment on one machine_1 the Accuracy is 86,37. When I r...
<p>This is what I use:</p> <pre class="lang-py prettyprint-override"><code>import torch import os import numpy as np import random def set_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False np.random....
pytorch|conv-neural-network|random-seed
1
5,860
63,881,970
How do I use SQL intersect operator in Pandas dataframe on databricks
<p>I'm using python 3.x on databricks. I have two dataframe,a &amp; b. a contains 2 rows &amp; b contains 5 rows. While I'm merging this two dataframe using below command</p> <pre><code>combine=pd.merge(a,b,on=[...],how=&quot;inner&quot;) </code></pre> <p>I'm getting 10 rows. But I need 5 rows or maximum number of rows...
<pre><code>result = pd.concat([a, b], axis=1, join='inner') </code></pre> <p>will give the following result:</p> <p><a href="https://i.stack.imgur.com/FKsds.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FKsds.png" alt="enter image description here" /></a></p> <p>I suggest you read this walkthrough ...
python|sql|pandas
0
5,861
63,806,772
Matplotlib interactive bar chart
<p>I am trying to explore interactive feature in matplotlib, basically user picks a y value by clicking on the graph, depending on the value the user picked, a horizontal line is drawn. And according to that line the color of barchart should change (how far is the value from the mean).</p> <p>My program draws the user ...
<p>I'm not sure I understood how you wanted to normalize your color coding, but I rewrote your code to make it work. Hopefully you'll be able to adapt the code to your needs:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.colors as mcolors import pandas as pd import numpy as np np.random.seed(12345) ...
python|pandas|numpy|matplotlib
2
5,862
46,701,216
Are all train samples used in fit_generator in Keras?
<p>I am using <code>model.fit_generator()</code> to train a neural network with <code>Keras</code>. During the fitting process I've set the <code>steps_per_epoch</code> to 16 (<code>len(training samples)/batch_size</code>). </p> <p>If the mini batch size is set to 12, and the total number of training samples is 195, d...
<p>No, because it is a generator the model does not know the total number of training samples. Therefore, it finishes an epoch when it reaches the final step defined with the <code>steps_per_epoch</code> argument. In your case it will indeed train 192 samples per epoch.</p> <p>If you want to use all samples in your mo...
python|tensorflow|machine-learning|keras|neural-network
2
5,863
46,967,538
Installing Tensorflow on Amazon EC2 Free Tier for testing
<p>I used <a href="https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/#0" rel="nofollow noreferrer">The Tensorflow for Poets</a> tutorial to train a model for classifying some images. Now I want to use that in a webpage on an EC2 instance on AWS Free Tier. As stated in the tutorial it is as simple as ...
<p>The free tier EC2 does not worry about what the instance is use for. </p> <p>Rather, how long it's instances are running for. </p> <p>A t2.micro you will get 750hours a month. </p> <p>All "free-tier eligible" products are labelled appropriately..</p> <p>If you need to use data storage and database they also have...
python|amazon-ec2|tensorflow
0
5,864
38,575,213
Join and sum on subset of rows in a dataframe
<p>I have a pandas dataframe which stores date ranges and some associated colums: </p> <pre><code> date_start date_end ... lots of other columns ... 1 2016-07-01 2016-07-02 2 2016-07-01 2016-07-03 3 2016-07-01 2016-07-04 4 2016-07-02 2016-07-07 5 2016-07-05 2016-07-06 </co...
<p>A sketch of a vectorized solution:</p> <p>Start with a <code>p</code> as in piRSquared's answer.</p> <p>Make sure <code>date_</code> cols have <code>datetime64</code> dtypes, i.e.:</p> <pre><code>df['date_start'] = pd.to_datetime(df.date_time) </code></pre> <p>Then calculate cumulative sums:</p> <pre><code>psum...
python|pandas|dataframe
3
5,865
38,558,735
Trying to convert CSV file contents to a desired format using python
<p>I am trying to convert CSV file contents from format A to Format B. I tried pandas, default dict, Dict writer, etc but I could not make it out.The problem is that it is printing horizontally but not vertically. Please find the example below.<a href="https://i.stack.imgur.com/9AoJa.png" rel="nofollow noreferrer"><img...
<p>I would like to thank @cyclops for the reply. Please find my code for the dynamic type .i.e. the user do not know number of columns in the input csv file.</p> <p>CODE:</p> <pre><code>import csv from collections import defaultdict column_header=[] columns = defaultdict(list) with open('C:\outfile4.csv') as f: ...
python-2.7|pandas
0
5,866
38,961,170
Pandas Add Values of Column to Different Dataframe
<p>So I have a DataFrame, df1, that has 3 columns, A, B, and C as such:</p> <pre><code> A B C Arizona 0 2.800000 5.600000 California 0 18.300000 36.600000 Colorado 0 2.666667 5.333333 Connecticut ...
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add.html" rel="nofollow">add()</a> method:</p> <pre><code>In [22]: df1.add(df2.D, axis='index') Out[22]: A B C Arizona 13.0 15.800000 18.600000 California 18.0 36.300000 54.600000...
python|pandas
3
5,867
38,731,480
How do I get this loop to work correctly when writing pandas df to xlsx?
<p>I have used <a href="https://stackoverflow.com/questions/20219254/how-to-write-to-an-existing-excel-file-without-overwriting-data">this code</a>, which is kind of working. Right now in the smaller 'rep_list' as it executes the first rep in the list which is CP is adds it, but then when it goes to AM it overwrites th...
<p>Try using the following:</p> <pre><code>import pandas as pd import datetime from openpyxl import load_workbook now = datetime.datetime.now() currentDate = now.strftime("%Y-%m-%d") call_report = pd.read_excel("Ending 2016-07-30.xlsx", "raw_data") #rep_list = ["CP", "AM", "JB", "TT", "KE"] rep_list = ["CP", "AM"] ...
python|pandas|openpyxl
1
5,868
38,927,886
Slow performance of timedelta methods
<p>Why does <code>.dt.days</code> take 100 times longer than <code>.dt.total_seconds()</code>?</p> <pre><code>df = pd.DataFrame({'a': pd.date_range('2011-01-01 00:00:00', periods=1000000, freq='1H')}) df.a = df.a - pd.to_datetime('2011-01-01 00:00:00') df.a.dt.days # 12 sec df.a.dt.total_seconds() # 0.14 sec </code></...
<p><code>.dt.total_seconds</code> is basically just a multiplication, and can be performed at numpythonic speed:</p> <pre><code>def total_seconds(self): """ Total duration of each element expressed in seconds. .. versionadded:: 0.17.0 """ return self._maybe_mask_results(1e-9 * self.asi8) </code></...
python-3.x|pandas
3
5,869
63,059,308
Json file not formatted correctly when writing json differences with pandas and numpy
<p>I am trying to compare two json and then write another json with columns names and with differences as yes or no. I am using pandas and numpy</p> <p>The below is sample files i am including actually, these json are dynamic, that mean we dont know how many key will be there upfront</p> <p><strong>Input files:</strong...
<p>Honestly pandas is overkill for this... however</p> <ol> <li>load dataframes as you did</li> <li>concat them as columns. rename columns</li> <li>do calcs and map boolean to desired Yes/No</li> <li><code>to_json()</code> returns a string so <code>json.loads()</code> to get it back into a list/dict. Filter columns to...
python|json|pandas
1
5,870
62,950,611
null value after binning
<p>while transforming continuous variable to categorical variable using <strong>pd.cut()</strong> null value appears in 'age' column which is transformed form 'age_in_years' that doesn't have any null value. what is the solution here?</p> <pre><code>df['age_in_years']=df['age_in_days']/365 df.drop('age_in_days',inplace...
<p>You can try:</p> <pre><code>bins=[-np.inf,0,35,60,100,np.inf] df['age']=pd.cut(df['age_in_years'],bins,labels=group,right=True).astype('object') </code></pre> <p>This will diagnose the problem and also include values below 0 <code>(-inf, 0.0]</code> and above 100 <code>[100.0, inf)</code></p>
python|pandas|dataframe|data-science
0
5,871
63,012,552
Change DataTypes of Pandas Columns by selecting columns by regex
<p>I have a Pandas dataframe with a lot of columns looking like p_d_d_c0, p_d_d_c1, ... p_d_d_g1, p_d_d_g2, ....</p> <pre><code> df = a b c p_d_d_c0 p_d_d_c1 p_d_d_c2 ... p_d_d_g0 p_d_d_g1 ... </code></pre> <p>All these columns, which confirm to the regex need to be selected and their dat...
<p>From the same link, and with some <code>astype</code> magic.</p> <pre class="lang-py prettyprint-override"><code>column_vals = df.columns.map(lambda x: x.startswith(&quot;p_d_d_&quot;)) train_temp = df.loc(axis=1)[column_vals] train_temp = train_temp.astype(float) </code></pre> <hr /> <p>EDIT:</p> <p>To modify the o...
python|python-3.x|regex|pandas|pandas-1.0
3
5,872
67,619,245
How can I split pandas dataframe into column of tuple, quickly?
<p>I have a pd.Series element of strings, separated by <code>'_'</code>, with only two elements in it.</p> <p>for instance,</p> <pre><code>s = pd.Series([a_1, a_2, a_3, b_1]) </code></pre> <p>the command <code>s.str.split(&quot;_&quot;)</code> will return a series of lists</p> <pre><code>0 ['a', '1'] 1 ['a', '2'] 2...
<p>One idea is use list comprehension:</p> <pre><code>s = pd.Series('a_1, a_2, a_3, b_1'.split(', ')) #4k rows s = pd.concat([s] * 1000, ignore_index=True) In [195]: %timeit s.str.split(&quot;_&quot;).apply(tuple) 2.49 ms ± 41.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [196]: %timeit [tuple(x.split...
python|pandas
2
5,873
31,766,547
Pandas Filtering
<p>I have a data frame that I am getting some counts on, like so:</p> <pre><code>t = df['NAME'].value_counts()[:10] </code></pre> <p>I would then like to reduce the original data set (df) to only include items that match t. Something like:</p> <pre><code>temp = df[t] </code></pre> <p>or</p> <pre><code>temp = df[df...
<p>try this:</p> <pre><code>df[df.name.isin(t.index)] </code></pre>
python|pandas
1
5,874
31,806,512
Export Pandas dataframe to custom CSV format with JSON rows
<p>In my pandas program I am reading a csv and converting some columns as json</p> <p>For ex: my csv is like this:</p> <pre><code>id_4 col1 col2 .....................................col100 1 43 56 .....................................67 2 46 67 ....................................78 </code></pre> <...
<p>Pandas dataframe can be directly serializable in JSON with <code>to_json</code> method.</p> <p>Your output format is not very clear but have a look at this:</p> <pre><code># Generate dataframe df = pd.DataFrame(np.random.randn(5, 100), columns=['col' + str(n) for n in xrange(1, 101)]) # Create id_4 column df.index...
python|json|csv|pandas
2
5,875
41,624,310
Pandas datetime day frequency to week frequency
<p>Q1: I have the following pandas dataframe:</p> <p><a href="https://i.stack.imgur.com/aZ7jq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aZ7jq.png" alt="enter image description here"></a></p> <p>with a huge number of rows with a daily frequency (the <em>Data</em> column). I would like to conve...
<p>first make sure your "Date" column is of type datetime.<br> Consider this example: </p> <pre><code>tidx = pd.date_range('2012-01-01', periods=1000) df = pd.DataFrame(dict( Money=np.random.rand(len(tidx)) * 1000, Workers=np.random.randint(1, 11, len(tidx)), Date=tidx )) </code></pre> <h...
python|pandas|date|data-conversion
4
5,876
27,575,823
Breaking down large dataset into organized index
<p>I'm trying to create an indexed dictionary of <code>shape_id</code>'s from a dataset that I have (see below). I realize I could use loops (and tried to do so), but I have an intuition that there's a bulk way to do this in pandas that isn't as computationally expensive.</p> <p>Possible solutions: <a href="http://pan...
<p>Assuming that your REAL task is not validating the data file, reading the file and filling an appropriate data structure with a loop isn't bulky, not at all...</p> <pre><code>f = open('shapes.csv') f.next() # skip headers lines = [line.strip().split(',') for line in f] # f is closed automatically data = {} ; item =...
python|csv|dictionary|pandas
0
5,877
61,217,866
How to get a list of event that occurred simultaneous
<p>Im trying to get the number of simulteneaous telephone call. I have this dataframe and I want to get for each user how many simulteanous call they had. my desired output is [{'A': 4}, {'E': 3}]</p> <pre><code>user = ['A', 'A', 'A', 'E', 'F', 'E', 'E', 'A', 'G', 'A'] started_time =...
<p>I assume any overlapping call of the same user to be "simultaneous". Explanation in code:</p> <pre><code>def count_simul(group): n = 0 g = [] ranges = {} # For each user, start the loop with a time range covering the distant # past to distant future started_time = pd.Timestamp('1900-01-01')...
python-3.x|pandas
1
5,878
61,373,070
Maplotlib calendar subplot need to avoid
<p><a href="https://i.stack.imgur.com/K3jPS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K3jPS.png" alt="enter image description here"></a></p> <p>I tried to plot a calendar graphic with this code, I plot a graphic, but I do nοt know how to avoid the subplot, I adapted from other code. </p> <p>C...
<p>You call <code>fig, ax = plt.subplots(2, 1, ....)</code>. This means 2 rows, 1 column. If you only want one subplot, use <code>fig, ax = plt.subplots(1, 1, ...)</code>. Thereafter, you should directly use <code>ax</code> instead of <code>ax[i]</code>.</p>
python|pandas|matplotlib
1
5,879
68,454,383
Can u check why is an error coming after concatenating numpy arrays
<p>I tried Concatenating 2 numpy arrays but I got an error. The error is:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\hp\Desktop\Python\Numpy\OperationsOnArrays1.py&quot;, line 28, in &lt;module&gt; array3 = np.concatenate((array,array2)) File &quot;&lt;__array_function__ internals&gt...
<p><code>print(array.shape, array2.shape)</code> will print <code>(2, 3) (4, 2)</code>.</p> <p>For concatenate to work, the first dimension has to be the same in all arrays.</p>
python|arrays|python-3.x|numpy
2
5,880
68,792,486
How to select a value in a dataframe with MultiIndex?
<p>I use the Panda library to analyze the data coming from an excel file. I used pivot_table to get a pivot table with the information I'm interested in. I end up with a multi index array. For &quot;OPE-2016-0001&quot;, I would like to obtain the figures for 2017 for example. I've tried lots of things and nothing works...
<p>You can use <code>.loc</code> to select rows by a DataFrame's Index's labels. If the Index is a MultiIndex, it will index into the first level of the MultiIndex (<code>Numéro Opéracion</code> in your case). Though you can pass a tuple to index into both levels (e.g. if you specifically wanted <code>(&quot;OPE-2016-0...
pandas|dataframe|multi-index
1
5,881
68,533,960
Multiple modes for multiple accounts in Python
<p>I have a dataframe of several accounts that display different modes of animal categories. How can I identify the accounts that have more than 1 mode?</p> <p>For example, note that account 3 only has one mode (i.e. &quot;dog&quot;), but accounts 1, 2 and 4 have multiple modes (i.e more than one mode).</p> <pre><code>...
<p>You can use numpy.random.choice for that</p> <pre><code>test.groupby('account')['category'].agg( lambda x: np.random.choice(x.mode(dropna=False))) </code></pre>
python|pandas|mode
1
5,882
36,442,094
Using Pandas filtering non-numeric data from two columns of a Dataframe
<p>I'm loading a Pandas dataframe which has many data types (loaded from Excel). Two particular columns should be floats, but occasionally a researcher entered in a random comment like "not measured." I need to drop any rows where any values in one of two columns is not a number and preserve non-numeric data in other...
<p>You can first create subset with columns <code>B</code>,<code>C</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow"><code>to_n...
excel|numpy|pandas
1
5,883
36,292,441
How long are Pandas groupby objects remembered?
<p>I have the following example Python 3.4 script. It does the following:</p> <ol> <li>creates a dataframe,</li> <li>converts the date variable to datetime64 format,</li> <li>creates a groupby object based on two categorical variables,</li> <li>produces a dataframe that contains a count of the number items in each gro...
<p>Not the same, the index has changed. For example:</p> <pre><code>tempDF.loc[1].id # before 10 tempDF.loc[1].id # after 2 </code></pre> <p>So if you compute <code>tempGroupby</code> with the old <code>tempDF</code> and then change the indexes in <code>tempDF</code> when you do this:</p> <pre><code>tempDF['dif...
python|python-3.x|pandas|dataframe
2
5,884
65,904,279
Scatter Pie Plot Python Pandas
<p>&quot;Scatter Pie Plot&quot; ( a scatter plot using pie charts instead of dots). I require this as I have to represent 3 dimensions of data. 1: x axis (0-6) 2: y axis (0-6) 3: Category lets say (A,B,C - H)</p> <p>If two x and y values are the same I want a pie chart to be in that position representing that Category....
<p>I'm not sure how to get 6 pie charts. If we group on <code>XVAL</code> and <code>YVAL</code>, there are 7 unique pairs. You can do something down this line:</p> <pre><code>fig, ax = plt.subplots(figsize=(40,40)) for (x,y), d in df.groupby(['XVAL','YVAL']): dist = d['GROUP'].value_counts() draw_pie(dist, x, y...
python|pandas|matplotlib|scatterpie
1
5,885
65,792,565
Preserving training/validation split after restarting training from a checkpoint with TensorFlow
<p>I have written a TensorFlow training loop which does validation at the end of each epoch. At the start of the training I split my dataset into training and validation subsets (about 85%-15% split). My dataset actually consists of audio samples stored in small chunks on disk, and I randomly shuffle the entire dataset...
<p>If you set the seed of the shuffling, the order will be consistant:</p> <pre><code>import tensorflow as tf for _ in range(5): ds = tf.data.Dataset.range(1, 10).shuffle(4, seed=42).batch(3) for i in ds: print(i) print() </code></pre> <pre><code>tf.Tensor([4 1 2], shape=(3,), dtype=int64) tf.Tenso...
python|tensorflow|machine-learning
2
5,886
65,719,217
Panda dataframe take column and append as new rows efficiently
<p>If I have a df:</p> <pre><code>df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c']) </code></pre> <p>and wish to take the second column &quot;b&quot; and append to the end of a &quot;new&quot; df with the columns &quot;a&quot; and &quot;b&quot; and a name column containing the name...
<p>IIUC, you can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.melt.html?highlight=dataframe%20melt#pandas-dataframe-melt" rel="nofollow noreferrer"><code>pd.DataFrame.melt</code></a> with parameter <code>id_vars</code> equal to 'a',</p> <pre><code>df.melt('a') </code></pre> <p>Output:</p> ...
python|pandas
2
5,887
63,606,492
How do I concatenate multiple pandas dataframe columns(Address details) into a single column, space delimited, and ignoring empty strings?
<p>So I've got a pandas dataframe that contains a ton of address info. Aka</p> <pre><code>AddressNumber StreetNamePrefix StreetName StreetNameSuffix StreetNamePreDirectional StreetNamePostDirectional OccupancySuite </code></pre> <p>I'd like to combine everything except for OccupancySuite into Address1</p> <p>I can get ...
<p>I Hope this helps you:</p> <p>I added the column &quot;Address1&quot; to the data frame.</p> <p>Then, you can perform a for cycle over the len of the data frame (in order to work with the rows) and over the elements in the columns of the data frame.</p> <p>With an if statement you can ignore the two last columns &qu...
python|pandas|dataframe
0
5,888
63,578,833
tf.keras.backend.function for transforming embeddings inside tf.data.dataset
<p>I am trying to use the output of a neural network to transform data inside tf.data.dataset. Specifically, I am using a <a href="https://arxiv.org/pdf/1806.04734.pdf" rel="nofollow noreferrer">Delta-Encoder</a> to manipulate embeddings inside the tf.data pipeline. In so doing, however, I get the following error:</p...
<p>At the risk of outing myself as a n00b, the answer is to switch the order of the map and batch functions. I am trying to apply a neural network to make some changes on data. tf.keras models take <strong>batches</strong> as input, not <strong>individual samples</strong>. By batching the data first, I can run <stro...
tensorflow|tensorflow2.0|tf.keras|autoencoder|tf.data.dataset
0
5,889
21,902,211
How do I import a plotly graph within a python script?
<p>Is there any API call to import a plotly graph as a .png file within an existing python script? If so, what is it?</p> <p>For example, having just created a graph using the plotly module for python...</p> <pre><code>py.plot([data0, data1], layout = layout, filename='foo', fileopt='overwrite') </code></pre> <p>......
<p>Another solution: add <code>.png</code> to any public plotly graph, e.g. </p> <pre><code>import requests r = requests.get('https://plot.ly/~chris/1638.png') </code></pre> <p>This works for any public plotly graph. <code>.png</code>, <code>.svg</code>, <code>.pdf</code> are supported. </p> <p><code>.py</code>, <co...
python|numpy|png|plotly
3
5,890
21,484,930
Numpy: boolean comparison on two vectors
<p>I have two vectors (or two one dimensional numpy arrays with the same number of elements) <em>a</em> and <em>b</em> where I want to find the number of cases I have that:</p> <p><strong>a &lt; 0 and b >0</strong></p> <p>But when I type the above (or something similar) into IPython I get:</p> <p>ValueError: The tru...
<p>I'm not certain that I understand what you're trying to do, but you might want <code>((a &lt; 0) &amp; (b &gt; 0)).sum()</code></p> <pre><code>&gt;&gt;&gt; a array([-1, 0, 2, 0]) &gt;&gt;&gt; b array([4, 0, 5, 3]) &gt;&gt;&gt; a &lt; 0 array([ True, False, False, False], dtype=bool) &gt;&gt;&gt; b &gt; 0 array([...
numpy
2
5,891
24,755,632
matplotlib can not import pylab
<p>I have installed <code>matplotlib</code> and of course its requirements <code>Numpy</code> and <code>scipy</code> on my pc but I get this error message when I import <code>pylab</code>:</p> <pre><code> &gt;&gt;&gt; from matplotlib import pylab Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ...
<p>It may be that you are missing:</p> <pre><code>import matplotlib as mpl </code></pre> <p>However, if that does not work. Reinstall the Anacoda distribution, then make sure you have numpy and scipy installed. </p> <p>The top of your program is then:</p> <pre><code>import numpy as np import scipy import matplotlib...
python|numpy|matplotlib|scipy
-1
5,892
29,848,757
Multiplication of two arrays in numpy
<p>I have two numpy arrays:</p> <pre><code>x = numpy.array([1, 2]) y = numpy.array([3, 4]) </code></pre> <p>And I would like to create a matrix of elements products:</p> <pre><code>[[3, 6], [4, 8]] </code></pre> <p>What is the easiest way to do this?</p>
<p>One way is to use the <code>outer</code> function of <code>np.multiply</code> (and transpose if you want the same order as in your question):</p> <pre><code>&gt;&gt;&gt; np.multiply.outer(x, y).T array([[3, 6], [4, 8]]) </code></pre> <p>Most ufuncs in NumPy have this useful <code>outer</code> feature (<code...
python|arrays|python-2.7|numpy|multiplication
7
5,893
29,872,350
Fastest way of comparing two numpy arrays
<p>I have two arrays:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a=np.array([2, 1, 3, 3, 3]) &gt;&gt;&gt; b=np.array([1, 2, 3, 3, 3]) </code></pre> <p>What is the fastest way of comparing these two arrays for equality of elements, regardless of the order?</p> <p><strong>EDIT</strong> I measured for ...
<p>Numpy as a collection of set operations.</p> <pre><code>import numpy as np import numpy.lib.arraysetops as aso a=np.array([2, 1, 3, 3, 3]) b=np.array([1, 2, 3, 3, 3]) print aso.setdiff1d(a, b) </code></pre>
python|arrays|performance|python-2.7|numpy
4
5,894
53,617,786
How to remove rows in a dataframe with more than x number of Null values?
<p>I am trying to remove the rows in the data frame with more than 7 null values. Please suggest something that is efficient to achieve this.</p>
<p>If I understand correctly, you need to remove rows only if total nan's in a row is more than <code>7</code>:</p> <pre><code>df = df[df.isnull().sum(axis=1) &lt; 7] </code></pre> <p>This will keep only rows which have <code>nan</code>'s less than 7 in the dataframe, and will remove all having nan's > 7.</p>
python-3.x|pandas|dataframe|data-science
21
5,895
53,567,301
Numpy append and normal append
<pre><code>x = [[1,2],[2,3],[10,1],[10,10]] def duplicatingRows(x, l): severity = x[l][1] if severity == 1 or severity == 2: for k in range(1,6): x.append(x[l]) for l in range(len(x)): duplicatingRows(x,l) print(x) x = np.array([[1,2],[2,3],[10,1],[10,10]]) def duplicati...
<p>You have some bugs in your code. Here's a little bit improved, correct, and (partially) vectorized implementation of your code which prints your desired output.</p> <p>Here we leverage <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html" rel="nofollow noreferrer"><code>numpy.tile</code></a...
python|list|numpy|append|atom-editor
1
5,896
53,446,129
Matplotlib Hour Minute Based Histogram
<pre><code>jupyter notebook 5.2.2 Python 3.6.4 pandas 0.22.0 matplotlib 2.2.2 </code></pre> <p>Hi I'm trying to present and format a histogram in a jupyter notebook based on hour and minute log data retrieved from a hadoop store using Hive SQL. </p> <p>I'm having problems with the presentation. I'd like to be able t...
<p>Thanks to <a href="https://stackoverflow.com/users/4124317/importanceofbeingernest">https://stackoverflow.com/users/4124317/importanceofbeingernest</a> who gave me enough clues to find the answer.</p> <pre><code>%%local import pandas as pd import matplotlib import matplotlib.pyplot as plt import datetime as dt impo...
python|pandas|matplotlib|hive|jupyter-notebook
0
5,897
17,159,207
Change timezone of date-time column in pandas and add as hierarchical index
<p>I have data with a time-stamp in UTC. I'd like to convert the timezone of this timestamp to 'US/Pacific' and add it as a hierarchical index to a pandas DataFrame. I've been able to convert the timestamp as an Index, but it loses the timezone formatting when I try to add it back into the DataFrame, either as a column...
<p>If you set it as the index, it's automatically converted to an Index:</p> <pre><code>In [11]: dat.index = pd.to_datetime(dat.pop('datetime'), utc=True) In [12]: dat Out[12]: label value datetime 2011-07-19 07:00:00 a 0 2011-07-19 08:00:00 a 1 2011-07-19 09:00:00 a 2 ...
python|timezone|dataframe|pandas|multi-index
31
5,898
12,534,029
Radial sampling with SciPy
<p>I'm doing image processing with <code>scipy.ndimage</code>. Given a ring-shaped object, I'd like to generate a "profile" around its circumference. The profile could be something like thickness measurements at various point around the ring, or the mean signal along the ring's "thickness."</p> <p>It seems to me that ...
<p>A standard probability distribution on a circle (or sphere) is the Von-Mises Fisher distribution.</p> <p>Scipy supports this distribution: <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.vonmises.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.vonmises.h...
python|image-processing|numpy|scipy
1
5,899
21,981,820
creating multiple excel worksheets using data in a pandas dataframe
<p>Just started using pandas and python.</p> <p>I have a worksheet which I have read into a dataframe and the applied forward fill (ffill) method to. </p> <p>I would then like to create a single excel document with two worksheets in it. </p> <p>One worksheet would have the data in the dataframe before the ffill meth...
<pre><code>import pandas as pd df1 = pd.DataFrame({'Data': ['a', 'b', 'c', 'd']}) df2 = pd.DataFrame({'Data': [1, 2, 3, 4]}) df3 = pd.DataFrame({'Data': [1.1, 1.2, 1.3, 1.4]}) writer = pd.ExcelWriter('multiple.xlsx', engine='xlsxwriter') df1.to_excel(writer, sheet_name='Sheeta') df2.to_excel(writer, sheet_name='S...
python|pandas
65