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
374,700
31,359,980
Memory efficient sort of massive numpy array in Python
<p>I need to sort a VERY large genomic dataset using numpy. I have an array of 2.6 billion floats, dimensions = <code>(868940742, 3)</code> which takes up about 20GB of memory on my machine once loaded and just sitting there. I have an early 2015 13' MacBook Pro with 16GB of RAM, 500GB solid state HD and an 3.1 GHz int...
<p>At the moment each call to <code>np.argsort</code> is generating a <code>(868940742, 1)</code> array of int64 indices, which will take up ~7 GB just by itself. Additionally, when you use these indices to sort the columns of <code>full_arr</code> you are generating another <code>(868940742, 1)</code> array of floats,...
python|performance|sorting|numpy|memory
14
374,701
64,515,684
CSV Date Parsing in Pandas
<p>I am trying to parse dates together from the following sample set of data</p> <hr /> <pre><code>No,year,month,day,hour,pm2.5,DEWP,TEMP,PRES,cbwd,Iws,Is,Ir 1,2010,1,1,0,NA,-21,-11,1021,NW,1.79,0,0 2,2010,1,1,1,NA,-21,-12,1020,NW,4.92,0,0 3,2010,1,1,2,NA,-21,-11,1019,NW,6.71,0,0 4,2010,1,1,3,NA,-21,-14,1019,NW,9.84,0,...
<p>Try it passing as <code>dict</code> or list of list</p> <pre class="lang-py prettyprint-override"><code>dataset = pd.read_csv(&quot;raw.csv&quot;, parse_dates={'date':['year', 'month', 'day', 'hour']}, index_col = 1, date_parser=dateparser) </code></pre> <p>Or</p> <pre class="lang-py prettyprint-override"><code>data...
python|pandas|date|parsing
1
374,702
64,355,794
How to hold the output of a model at each training epoch in tensorflow 1.x?
<p>I am trying to implement a constraint on the output of a neural network using the output of the previous training epoch. I tried using tf.assign() to update the value of a variable that holds the output, but it turned out that it holds the initial value.</p>
<p>You must use callbacks. It's my example for maximum scorу:</p> <pre><code>checkpoint_precision = ModelCheckpoint(filepath='best-weights, precision_selu_pr.hdf5', monitor='val_precision', mode='max', verbose=1, save_best_only=True) checkpoint_auc = ModelCheckpoint(filepath='best-weights-auc_selu_pr.hdf5', monitor='v...
python|tensorflow|machine-learning
0
374,703
64,288,855
Element Click Selenium Not Finding Button to Click
<p>For the url below, I am trying to click the &quot;1-50&quot; button (which has its own xpath) and then the &quot;51-100,&quot; &quot;101-150,&quot; etc. buttons (which all share a 2nd xpath), but my code does not seem to be able to click on the button. Anybody able to figure this out? Cheers!</p> <pre><code>import p...
<p>Runs fine if you used the a tag.</p> <pre><code>driver.find_element_by_xpath('//table[2]/tbody/tr/td/a').click() time.sleep(2) for i in range(1,3): df = pd.read_html(driver.page_source)[0] df_appended.append(df) driver.find_element_by_xpath('//table[2]/tbody/tr/td/a[3]').click() time.sleep(1) </code...
python|pandas|selenium|selenium-webdriver|xpath
0
374,704
64,438,066
How can I fillna based on the columns from another dataframe?
<p>I'm trying to fill the null value in <code>job_industry_category</code> from a lookup dataframe. For example:</p> <pre><code>df = pd.DataFrame() df['job_title'] = ['Executive Secretary', 'Administrative Officer' , 'Recruiting Manager' , 'Senior Editor', 'Media Manager I'] df['job_industry_category'] = ['Health', 'Fi...
<pre><code>#Boolean select NaN m=df.job_industry_category.isna() #Mask the NaNs and map across values using a dict of lookup['job_title']:lookup['job_industry_category'] df.loc[m,'job_industry_category']=df.loc[m,'job_title'].map(dict(zip(lookup.job_title,lookup.job_industry_category))) job_title job_...
python|pandas|dataframe
0
374,705
64,190,008
Renaming values in a column based on predefined ranges
<p>I have a list of years in a column (pandas)</p> <pre><code>Year 2001 2002 2018 2002 2006 2010 2019 2010 </code></pre> <p>I would like to visualise in a bar chart how many years are by 2012 and how many years there are after 2012, i.e. I should have in my column something like this:</p> <pre><code>Year &lt;2012 &lt;2...
<p>This looks like a job for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html" rel="nofollow noreferrer"><code>pd.cut</code></a>:</p> <pre><code>pd.cut(df['Year'], bins=[-np.inf, 2012, np.inf], labels=['&lt;2012', '&gt;2012']) 0 &lt;2012 1 &lt;2012 2 &gt;2012 3 &lt;2012 4...
python|pandas
0
374,706
64,322,401
How to use groupby in python for multiple columns?
<p>have a df with values :</p> <pre><code>name numb exam marks tom 2546 math 25 tom 2546 science 25 tom 2546 env 25 mark 2547 math 15 mark 2547 env 10 sam 2548 env 18 </code></p...
<p>Consider <code>pivot_table</code> with some column name manipulation due to hierarchy and aggreate name:</p> <pre><code>pivot_df = df.pivot_table(index='name', columns='exam', values='marks', aggfunc=['count', 'sum'], margins=True, margins_name='total') pivot_df.columns = [i+'_'+j.replace...
python|pandas|group-by|pivot|aggregate
0
374,707
64,247,915
Modify column data before a specific character using Regex in pandas
<p>I'm trying to modify the Address column data by removing all the characters before the comma.</p> <p>Sample data:</p> <pre><code> **ADDRESS** 0 Ksfc Layout,Bangalore 1 Vishweshwara Nagar,Mysore 2 Jigani,Bangalore 3 Sector-1 ...
<p>Try this:</p> <pre><code>data.ADDRESS = data.ADDRESS.str.split(',').str[-1] </code></pre>
python|regex|pandas
0
374,708
64,280,524
How to multiply 2 different dataframe which have different shape but same header and row label in Python Pandas?
<p><strong>Dataframe - 1 (number of products by country)</strong></p> <p><strong>Note:</strong> Use below code to generate example dataframe</p> <pre><code>df1 = pd.DataFrame({'Devices':['Mobile','Mobile','Mobile','Mobile','Mobile','Laptop','Desktop'],'Sources':['India','India','India','India','UK','UK','US'],'Status':...
<p>Set <code>Devices</code> and <code>Sources</code> as the index and then multiply</p> <pre><code>df1.set_index(['Devices', 'Sources', 'Status'])[df1.columns[3:]].mul(df2.set_index(['Devices', 'Sources'])[df2.columns[3:]]).reset_index() Devices Sources Status 10/01/2020 10/02/2020 10/03/2020 10/04/2020 0 Desk...
python-3.x|pandas|dataframe
1
374,709
64,484,576
Why do I get an error trying to use keras package in R?
<p>I'm trying to run through an example for building a neural network in R. I tried following the instructions at <a href="https://opendatascience.com/using-keras-and-tensorflow-in-r/" rel="nofollow noreferrer">https://opendatascience.com/using-keras-and-tensorflow-in-r/</a>. I've installed the keras and tensorflow pac...
<p>In case anyone has a similar problem, I just uninstalled Rstudio and installed again through a new python environment in anaconda navigator and installed the modules I needed in that environment. That seemed to work.</p>
python|r|tensorflow|keras
0
374,710
64,329,250
How to mask paddings in LSTM model for speech emotion recognition
<p>Given a few directories of .wav audio files, I have extracted their features in terms of a 3D array (batch, step, features).</p> <p>For my case, the training dataset is (1883,100,136). Basically, each audio has been analyzed 100 times (imagine that as 1fps) and each time, 136 features have been extracted. However, t...
<p><code>Embedding</code> layer is not for your case. You can consider instead <code>Masking</code> <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Masking" rel="nofollow noreferrer">layer</a>. It is simply integrable in your model structure, as shown below.</p> <p>I also remember you that the input...
tensorflow|machine-learning|keras|deep-learning|lstm
1
374,711
64,362,016
Error pip installing wheel file from github repository (to download pycocotools)
<p>I am installing Tensorflow (1.15.0) in order to perform some deep learning object detection, but am having trouble pip installing pycocotools. I am following <a href="https://www.youtube.com/watch?v=usR2LQuxhL4&amp;t=134s" rel="nofollow noreferrer">this</a> tutorial, which is an updated tutorial originally from YouT...
<p>Try running it as follows:</p> <pre><code>pip install pycocotools-windows </code></pre> <p>as suggested <a href="https://github.com/cocodataset/cocoapi/issues/169" rel="nofollow noreferrer">here</a>.</p>
tensorflow|github|pip|pycocotools
1
374,712
64,311,465
Testing a Random Image against a Python Keras/Tensorflow CNN
<p>I've created and CNN and I am trying to figure out how to test a random image against it. I am utilizing Keras and Tensorflow. Lets assume I wanted to test the image found here: <a href="https://i.ytimg.com/vi/7I8OeQs7cQA/maxresdefault.jpg" rel="nofollow noreferrer">https://i.ytimg.com/vi/7I8OeQs7cQA/maxresdefault....
<p>Step 1: Save the model</p> <pre><code>model.save('model.h5') </code></pre> <p>Step 2: Load the model</p> <pre><code>loaded_model = tensorflow.keras.models.load_model('model.h5') </code></pre> <p>Step 3: Download the image via requests library(answer is taken from: <a href="https://stackoverflow.com/questions/3042757...
python|tensorflow|keras|conv-neural-network|image-classification
0
374,713
64,555,580
Change saved tensorflow model input shape at inference time
<p>I've searched everywhere but couldn't find anything. It looks so weird that nobody have already encountered the same problem as I... Let me explain:</p> <p>I've trained a <strong>Tensorflow 2</strong> custom model. During the training I have used <code>set_shape((None, 320, 320, 14))</code> so that Tensorflow knows ...
<p>I answer my own question. Unfortunately, my answer <strong>will not satisfy</strong> everybody. There are so many convoluted things happening in TF (Not to mention that when you search for help, most of it concern the 1st API... -_-&quot;).</p> <p>Anyway, here is the &quot;solution&quot;</p> <p>In my Neural Network,...
tensorflow|input|tensorflow2.0|shapes
0
374,714
64,398,484
How to manipulate client gradients in tensorflow federated sgd
<p>I'm following <a href="https://www.tensorflow.org/federated/tutorials/federated_learning_for_image_classification" rel="nofollow noreferrer">this tutorial</a> to get started with tensorflow federated. My aim is to run federated sgd (not federated avg) with some manipulations on client gradient values before they are...
<p><code>build_federated_sgd_process</code> is fully-canned; it is really designed to serve as a reference implementation, not as a point of extensibility.</p> <p>I believe what you are looking for is the function that <code>build_federated_sgd_process</code> calls under the hoos, <a href="https://www.tensorflow.org/fe...
python|tensorflow|tensorflow-federated|sgd
1
374,715
64,371,445
Read excel sheet in pandas with different sheet names in a pattern
<p>I am trying to read multiple excel files in a loop using read_excel :</p> <p>Different excel files contain sheet names which contain the word &quot;staff&quot; eg Staff_2013 , Staff_list etc</p> <p>Is there a way to read all these files dynamically using some wild card concept ?</p> <p>Something like the code below ...
<p>The <code>pandas.read_excel</code> can only read one sheet. The use you are suggesting would be problematic in case of multiple matches.</p> <p>So you have to list the sheets and select the ones you want to read one by one.</p> <p>For instance:</p> <pre><code>xls_file = pd.ExcelFile('my_excel_file.xls') staff_fnames...
python|pandas|dataframe
3
374,716
64,233,099
pyTorch gradient becomes none when dividing by scalar
<p>Consider the following code block:</p> <pre><code>import torch as torch n=10 x = torch.ones(n, requires_grad=True)/n y = torch.rand(n) z = torch.sum(x*y) z.backward() print(x.grad) # results in None print(y) </code></pre> <p>As written, <code>x.grad</code> is None. However, if I change the definition of <code>x</co...
<p>When you set <code>x</code> to a tensor divided by some scalar, <code>x</code> is no longer what is called a &quot;leaf&quot; <code>Tensor</code> in PyTorch. A leaf <code>Tensor</code> is a tensor at the beginning of the computation graph (which is a DAG graph with nodes representing objects such as tensors, and edg...
python|pytorch
1
374,717
64,601,301
Pytorch input tensor size with wrong dimension Conv1D
<pre><code> def train(epoch): model.train() train_loss = 0 for batch_idx, (data, _) in enumerate(train_loader): data = data[None, :, :] print(data.size()) # something seems to change between here data = data.to(device) optimizer.zero_grad() recon_batch, mu, logvar = model(data) # ...
<p>I just found my mistake when I call <code>forward()</code> I am doing <code>self.encode(x.view(-1,1998))</code> which is reshaping the tensor.</p>
python|pytorch|tensor
0
374,718
64,585,328
Why can R's read.csv() read a CSV from GitLab URL when pandas' read_csv() can't?
<p>I noticed that panda's <code>read_csv()</code> fails at reading a public CSV file hosted on GitLab:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.read_csv(&quot;https://gitlab.com/stragu/DSH/-/raw/master/Python/pandas/spi.csv&quot;) </code></pre> <p>The error I get (truncated):</p> ...
<p>If you're looking for a workaround, I recommend making the GET request via <a href="https://requests.readthedocs.io/en/master/" rel="nofollow noreferrer"><strong><code>requests</code></strong></a> library:</p> <pre><code>import requests from io import StringIO url = &quot;https://gitlab.com/stragu/DSH/-/raw/master/...
python|r|pandas|read.csv
4
374,719
64,300,420
How to reshape array which doesn't have column?
<p>I have one array which shape is (6000,) and now I want to convert it to (6000,1) to use it further. How can I do it?</p> <pre><code> print(&quot;TrainX&quot;, str(trainX.T.shape)) np.reshape(trainY, (1, trainY.shape[0])) print(&quot;TrainY&quot;, str(trainY.shape)) </code></pre> <p>Both giving same output (6...
<p>Something like this?</p> <pre><code>import numpy as np a = np.array((1,2,3)) b = np.array([a]).T print(np.shape(a)) print(np.shape(b)) </code></pre> <p>Output:</p> <pre><code>(3,) (3, 1) </code></pre>
python|arrays|numpy
0
374,720
64,453,512
Map dataframe values in some columns according to the values in other columns
<p>I have a dataframe which looks like this:</p> <pre><code> home_player_1 home_player_2 home_player_3 away_player_1 away_player_2 away_player_3 player_1 ~~~ player_2000 1 23 34 45 2 6 688 0 ~~~ 0 2 233 341 4 ...
<p>The following code should give you the desired DataFrame:</p> <pre class="lang-py prettyprint-override"><code>for index, row in df.iterrows(): values = row[:6] for value in values: df.at[index, 'player_{}'.format(value)] = 1 </code></pre> <h2><strong>Edit:</strong></h2> <p>In case you want to avoid i...
python|pandas|dataframe|logic
1
374,721
64,203,682
How do I filter the data when there are many conditions in pandas?
<p>I have a question about python pandas.</p> <p>For example, the dataset df has 100 rows and the column names are a1, a2, a3, ... , a20. If I want to find specific rows where a1=20, a2=1, a3=0, a4=1, a5=2,...., a20=1, how can I filter out the rows if such row exists?</p> <p>If I use pandas filter, how should I set th...
<p>Try this:</p> <pre><code>df = df[(df['a1'] == 20) &amp; (df['a2'] == 1) &amp; (df['a3'] == 0)] </code></pre>
python|pandas|dataframe
0
374,722
64,451,388
Summing up the output of multiple functions in python
<p>I currently have three sine functions (y1, y2, y3) and would like to sum the output of the functions in a new function (ytotal) but only where the output of the sine functions are greater than 0.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt #%% phi = np.linspace(-2*np.pi, 2*np.pi, 100) y1 = 0....
<p>Do you mean:</p> <pre><code>plt.plot(phi, y1.clip(0)+y2.clip(0)+y3.clip(0), label='Total') </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/uj1ec.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uj1ec.png" alt="enter image description here" /></a></p>
python|numpy|math|trigonometry
0
374,723
64,238,018
How to use standard scaler model on dataset having less features than original dataset in which it was initially trained
<p>I was using standard scalar model from sklearn.preprocessing. I fitted the standard scaler model on the dataset having 27 features in it. Is it possible to use same standard scalar model on a testing dataset having less than 27 features in it Code Snippet</p> <pre><code>from sklearn.preprocessing import StandardScal...
<p>If want select all features without first <code>3</code> features use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>DataFrame.iloc</code></a>:</p> <pre><code>from sklearn.preprocessing import StandardScaler sc = StandardScaler() x_trai...
python|pandas|machine-learning|scikit-learn
2
374,724
64,450,286
How to effeciently create conditional columns arrays using Numpy?
<p>The objective is to create an array but by fulfilling the condition of <code>(x=&gt;y) and (y=&gt;z)</code>.</p> <p>One naive way but does the job is by using a nested <code>for loop</code> as shown below</p> <pre><code>tot_length=200 steps=0.1 start_val=0.0 list_no =np.arange(start_val, tot_length, steps) a=np.ze...
<pre><code>tot_length = 200 steps = 0.1 list_no = np.arange(0.0, tot_length, steps) a = list() for x in list_no: for y in list_no: if y &gt; x: break for z in list_no: if z &gt; y: break a.append([x, y, z]) a = np.array(a) # if needed, a.transp...
python|pandas|numpy
2
374,725
64,531,446
sum rows in dataframe based on different columns
<p>How can I merge rows in the given dataframe as shown below? For each account and currency, I have to sum the values, so that there's no division by sector.</p> <p><a href="https://i.stack.imgur.com/e9ory.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e9ory.png" alt="enter image description here" ...
<p>Try</p> <pre><code>df.groupby(['acccount','currency'])['sum'].sum().reset_index() </code></pre>
python|pandas|dataframe|merge
4
374,726
64,445,546
Fill in timestamp gaps every 11th of a second
<p>I have a textfile 'example.txt' which contains data sampled at 11 Hz (so every 11th of a second).</p> <p>Here you can find my code to load the textfile and convert 'Date' and 'Time' into datetime format. In the end the dataframe has a size of (34,6):</p> <pre><code>import glob import os import datetime #Specify fil...
<p>If you have your timestamp as a timestamp, the missing time gap will be filled in by a line connecting the two data points on either side. We can call out the legit values by using a scatterplot over top of the line plot.</p> <pre><code>import seaborn as sns import matplotlib.pyplot as plt df['Time'] = pd.to_dateti...
python|pandas|dataframe|timestamp
0
374,727
64,430,001
Invalid pointer error whily running python in C++ using pybind11 and pytorch
<p>While running the following python code in C++ using pybind11, pytorch 1.6.0, I get &quot;Invalid Pointer&quot; error. In python, the code runs successfully without any error. Whats the reason? How can I solve this problem?</p> <pre><code>import torch import torch.nn.functional as F import numpy as np import cv2 imp...
<p>This line is causing the error because it assumes <code>__dict__</code> has a <code>backbone_name</code> element:</p> <pre><code>backbone = resnet.__dict__[backbone_name](pretrained=pretrained) </code></pre> <p>When that isn't the case, it basically tries to access invalid memory. Check <code>__dict__</code> first w...
python|c++|c++11|pytorch|pybind11
0
374,728
64,459,038
How to read all csv files in multiple zip files?
<p>I have a folder with many zip files and within those zip files are multiple csv files. Is there any way to get all of the .csv files in one dataframe in python? Or any way I can pass a list of zip files?</p> <p>The code I am currently trying is:</p> <pre><code>import glob import zipfile import pandas as pd for zip_...
<p>The following code should satisfy your requirements (just edit <code>dir_name</code> according to what you need):</p> <pre class="lang-py prettyprint-override"><code>import glob import zipfile import pandas as pd dfs = [] for filename in os.listdir(dir_name): if filename.endswith('.zip'): zip_file = os....
python|pandas|glob|zip
0
374,729
64,354,164
cuDNN Error Failed to get convolution algorithm. This is probably because cuDNN failed to initialize
<p>I have installed Anaconda with Python 3.8 and CUDA 10.1 with CUDNN 8.0.3 on my Window 10 with GPU GTX 1050. But Still I get the error <a href="https://i.stack.imgur.com/BARlk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BARlk.png" alt="Details of the Error" /></a></p>
<p>I've been having a similar issue with TF 2.3.1. However, right away I can tell you that your cudnn version is incompatible. Only cudnn 7.6 is supported with the latest TF which as of right now is 2.3.1. See compatibility link below.</p> <p><a href="https://www.tensorflow.org/install/gpu#hardware_requirements" rel="n...
python|tensorflow|tensorflow2.0
1
374,730
64,302,315
How to combine groupby, rolling and multiple columns' creation in Python
<p>I have an issue that is easily solved with dplyr in R, yet can't seem to find an easy way in Python. I have a df with id(=customerid), s(=store), m(=month) and ttl(=total purchase) as columns. I would like to calculate multiple new columns on id+s - for example last 3 months purchase and minimum purchase.</p> <p>Exa...
<p>With python syntax and pandas the logic is nearly identical</p> <pre><code>t = ''' id s m ttl 1 A 1/1/2020 7 1 A 2/1/2020 3 1 A 3/1/2020 7 1 A 4/1/2020 6 1 A 5/1/2020 7 1 A 6/1/2020 7 1 B 1/1/2020 6 1 B 2/1/2020 10 1 B 3/1/2020 8 1 ...
python|pandas|janitor
1
374,731
64,275,440
FIeld format conversion error in numpy array
<p>I am trying to create a numpy array consisting of an array of data, where each data point is another array of length 5. I am trying to do this by setting a first datum (i.e. array of five elements) and setting the name and formats of each data types using the following code:</p> <pre><code>DTYPE = [('t_start', 'S32'...
<p>I can't reproduce your exact error message, but it looks like there are two issues: your inner list should be a tuple, and you should use <code>U</code> (Unicode string) in place of <code>S</code> in the format specifier (<a href="https://numpy.org/doc/stable/reference/arrays.dtypes.html" rel="nofollow noreferrer">d...
python|python-3.x|numpy
0
374,732
64,396,124
Selecting sentences from a data frame text column if only the sentences contain any of the keywords from a search list
<p>I have a dataframe where in one column, I have a full text with multiple very long sentences. I used <code>NLTK</code> to tokenize the text but now I need to make sure I only extract the sentences that contain any of the words from a given long list of full words. I wrote the following code but the problem with it i...
<p>The regex you are using is <em>almost</em> good. What you would need is to search for individual words which you can achieve by using <code>\b</code> special regex character which matches word boundaries (in regex sense).</p> <p>Therefore, what would work is:</p> <pre><code>symptoms = [long list of words ~ about 100...
python|python-3.x|regex|pandas|nltk
0
374,733
64,362,318
pandas: replicating an excel formula in pandas
<p>What i have is a dataframe like:</p> <pre><code> total_sum pid 5 2 1 2 6 7 3 7 1 7 1 7 0 7 5 10 1 10 1 10 </code></pre> <p>What I want is another column <code>pos</code> like:</p> <pre><code> tot...
<p><strong>Explanation</strong>:</p> <p>Doing <code>groupby</code> on <code>pid</code> to group the same <code>pid</code> into separate groups. On each group, apply these following operations:</p> <p>_ Call <code>diff</code> on each group. <code>diff</code> returns integers or <code>NaN</code> indicate the differences ...
python|pandas|dataframe|sorting
3
374,734
64,177,093
Question Python Group by and Apply function
<p>I have a data set like below:</p> <pre><code>idx start_date end_date flag 1. 6-17-20. 6-24-20. 1 2. 6-17-20. 6-24-20. 0 3. 6-17-20. 6-24-20. 1 4. 6-17-20. 6-24-20. 0 1. 6-25-20. 7-03-20. 1 2. 6-25-20. 7-03-20. 1 3. 6-25-20. 7-03-20. 1 4. 6-25-20. 7-03-20. 1 </code></pre> <p>W...
<p>Your question could be clearer but I think I sort of understand what you are trying to achieve. Do comment if I am mistaken!</p> <p>I'm presuming that you want the start and end dates as row entries and the columns of <code>idx</code>s indicating which IDs have those start and end dates. With that assumption in mind...
python|pandas-groupby|apply
0
374,735
64,509,518
Pandas - convert float to int when there are NaN values in the column
<p>I'm trying to convert float numbers to int in my df column with this one liner:</p> <pre><code>df['id'] = df['id'].map(lambda x: int(x)) </code></pre> <p>But some values are NaN an will throw:</p> <pre><code>ValueError: cannot convert float NaN to integer </code></pre> <p>How do I fix this?</p>
<p><code>NaN</code> is itself float and can't be convert to usual <code>int</code>. You can use <code>pd.Int64Dtype()</code> for nullable integers:</p> <pre><code># sample data: df = pd.DataFrame({'id':[1, np.nan]}) df['id'] = df['id'].astype(pd.Int64Dtype()) </code></pre> <p>Output:</p> <pre><code> id 0 1 1 ...
pandas
7
374,736
64,372,558
Unable to convert full string from pandas series
<p>I have a pandas series where I save strings. But when I wish to convert this series to string, each cell is limited to a number of character. Does anyone know if I am doing something wrong or if theres a workaroud.</p> <pre><code>data = np.array(['good day good sir how are you doing today? I sure hope you are well',...
<p><strong>Series.to_string()</strong> returns a string representation of the Series, not a reduced value, if you want to combine all string in a single one, replace <code>ser.to_string()</code> for <code>&quot; &quot;.join(ser)</code> and it will concat all string with a space.</p>
python|pandas|string|series
0
374,737
64,589,892
Tensorflow 2.3.1 IndexError: list index out of range
<p><strong>I got an error ,IndexError: list index out of range.</strong></p> <p>it worked on a other machine but after i transferred it to a other machine it doesn't work anymore.</p> <p>Python: 3.8.5</p> <p>tensorflow: 2.3.1</p> <p>Traceback says:</p> <pre><code>tensorflow.python.autograph.impl.api.StagingError: in us...
<p>Define the detect_fn inside the get_model_detection_function function , something like this :</p> <pre><code>def get_model_detection_function(model): &quot;&quot;&quot;Get a tf.function for detection.&quot;&quot;&quot; @tf.function def detect_fn(image): &quot;&quot;&quot;Detect objects in image.&quo...
python|tensorflow|tensorflow2.0|index-error|tensorflow2.x
3
374,738
64,344,884
Pandas DataFrame : Create a column based on values from different rows
<p>I have a pandas dataframe which looks like this :</p> <pre><code> Ref Value 1 SKU1 A 2 SKU2 A 3 SKU3 B 4 SKU2 A 5 SKU1 B 6 SKU3 C </code></pre> <p>I would like to create a new column, conditioned on whether the values for a given Ref matc...
<p>Let's try <code>groupby().nunique()</code> to check the number of values within a ref:</p> <pre><code>df['NewCol'] = np.where(df.groupby('Ref')['Value'].transform('nunique')==1, 'good', 'bad') </code></pre> <p>Output:</p> <pre><code> Ref Value NewCol 1 SKU1 A bad 2 SKU2 A g...
python|pandas|dataframe
3
374,739
64,431,313
split multiple columns in pandas dataframe by delimiter
<p>I have survey data which annoying has returned multiple choice questions in the following way. It's in an excel sheet There is about 60 columns with responses from single to multiple that are split by /. This is what I have so far, is there any way to do this quicker without having to do this for each individual co...
<p>We can use list comprehension with <code>add_prefix</code>, then we use <code>pd.concat</code> to concatenate everything to your final df:</p> <pre><code>splits = [df[col].str.split(pat='/', expand=True).add_prefix(col) for col in df.columns] clean_df = pd.concat(splits, axis=1) </code></pre> <pre><code> q10 q2...
python|pandas|split
6
374,740
64,318,011
How can I find cosine similarity between input array and pandas dataframe and return the row in dataframe which is most similar?
<p>I have a data set as shown below and I want to find the cosine similarity between input array and reach row in dataframe in order to identify the row which is most similar or duplicate. The data shown below is a sample and has multiple features. I want to find the cosine similarity between input row and each row in ...
<p>There are <a href="https://stackoverflow.com/questions/18424228">various ways of computing cosine similarity</a>. Here I give a brief summary on how each of them applies to a dataframe.</p> <h2>Data</h2> <pre><code>import pandas as pd import numpy as np # Please don't make people do this. You should have enough rep...
python|pandas|scikit-learn|scipy|cosine-similarity
3
374,741
64,273,234
Python Issue - Correlated Random Samples and Cholesky Decomposition
<pre><code>import numpy as np from scipy.linalg import cholesky X1_temp = np.random.normal(0, 1, (40, 10)) # with mean 0 and std. dev. 1 C = cholesky(C0, lower = False) X1 = X1_temp @ np.transpose(C) </code></pre> <p>Thanks very much in advance. This is just a very simple task. I am given a desired covariance matrix C...
<p>Don't transpose <code>C</code> when you compute <code>X1</code>.</p> <pre><code>In [33]: C0 Out[33]: array([[0.00119545, 0.00055428, 0.00094478, 0.00057466, 0.00039038, 0.0004846 , 0.00047505, 0.00039403, 0.00041767, 0.00053985], [0.00055428, 0.00055869, 0.0005272 , 0.00046757, 0.0002733 , 0....
python|numpy|random|statistics|covariance
0
374,742
64,378,573
Compare sums of multiple pandas dataframes in an effective way
<p>I have multiple pandas dataframes (5) with some common names index. They have different size. I need sum at least 5 different common <code>colum names</code> (25 in total) from each dataframe and then compare the sums.</p> <pre><code>Data: df_files = [df1, df2, df3, df4, df5] df_files out: [ z n...
<p>If I understand your problem correctly, you need to bring the names of data frames and respective columns in one place to compare the sums. In that case I usually use a dictionary to keep the name of variable, something like this:</p> <pre><code>df_files = {'df1':df1, 'df2':df2, 'df3':df3, 'df4':df4, 'df5':df5} summ...
python|pandas|list|if-statement
1
374,743
64,609,003
Numpy vectorization instead of for loop
<p>I wrote a function which is too time consuming when used with for loops. It appends numpy vectors (10,0) as rows in each iteration. How can I use a vectorized numpy solution for the iterations to speed this up?</p> <p>Any hint why the vstack-array solution below is even slower than the append-list solution?</p> <p>T...
<p>In general you don't want to append to <code>numpy</code> arrays. Re-allocating space for them is too time consuming. If you know <code>n_iterations</code>, you can allocate up-front like this:</p> <pre><code>result_array = np.empty([n_iterations, n_cols]) for i in range(n_iterations): result_array[i] = samp...
python|numpy|vectorization
1
374,744
64,377,601
Counting from a column in a Pandas Dataframe
<p>I am attempting to count the number of instances of an element in a column of a Pandas Dataframe based on a set of criteria. I am running into difficulty in a few places.</p> <p>Here is what I have up to this point. It effectively reads the CSV, drops the duplicates, and sorts df2. I am performing all of these s...
<p>Try pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>value_counts</code></a> function</p>
python|python-3.x|pandas|dataframe
-1
374,745
64,176,002
fast fourier transform of csv data
<p>I have a csv file that contains time and torque data. <a href="https://pastebin.com/MAT2rG3U" rel="nofollow noreferrer">https://pastebin.com/MAT2rG3U</a> This data set is truncated because size limit.</p> <p>I am trying to find the FFT of the data to find the frequency of a vibration.</p> <p>Here is my code (here ...
<p>What you've posted works for me, but your data isn't valid for an FFT because the timesteps aren't consistent. That is, you don't have a well defined sample rate.</p> <pre><code>data = pd.read_csv('torque_data.txt',index_col=0) data = data['Torque'].astype(float).values print(data) N = data.shape[0] #number of ele...
python|pandas|numpy|matplotlib|fft
1
374,746
64,402,771
How to load numpy array with certain columns as specific type
<p>I tried following:</p> <pre><code>&gt;&gt;&gt; arr2 = [[0, 0, 0, -0.9, 0.3], [0, 0, 1, 0.9, 0.6], [0, 1, 0, -0.2, 0.6], [0, 1, 1, 0.8, 0.3], [1, 0, 1, 0.2, 1.0], [1, 1, 0, -0.8, 1.0]] &gt;&gt;&gt; narr2 = np.array(arr2) &gt;&gt;&gt; narr2 array([[ 0. , 0. , 0. , -0.9, 0.3], [ 0. , 0. , 1. , 0.9, 0.6], ...
<p>I propose that you convert lists to tuples, and then assign the data types. Here's my solution:</p> <pre><code>import numpy as np arr2 = [[0, 0, 0, -0.9, 0.3], [0, 0, 1, 0.9, 0.6], [0, 1, 0, -0.2, 0.6], [0, 1, 1, 0.8, 0.3], [1, 0, 1, 0.2, 1.0], [1, 1, 0, -0.8, 1.0]] tupp2 = [tuple(l) for l in arr2] datatype = [(...
python|arrays|numpy
0
374,747
64,255,616
How can I fill data frames with NAN with same values of previous data frames from the same list
<p>I have a list of data frames <code>A</code> most of them are NAN data frames some of them are not, I would like to fill all NAN data frames with same values of the previous data frames (that do not contain NAN) in the list. Here's a small example:</p> <pre><code>A=[] data = {'set_of_numbers': [1,2,3,4,4,5,9]} df1 =...
<p>If I understand correctly:</p> <pre><code>for i, df in enumerate(A): df[df.isnull()] = A[i-1] </code></pre> <p>or if you wish to change the dtype of previously non-nan df:</p> <pre><code>for i, df in enumerate(A): if df.isnull().all().all(): A[i] = A[i-1].copy() </code></pre> <p>per OP's <strong>EDIT</strong...
python|pandas|numpy|dataframe
1
374,748
47,703,374
2 groupby in the same dataframe, it is possible?
<p>I want to the following df, to make a <code>df = df.groupby(['id','quarter'])['jobs].mean()</code> but at the same time that dataframe must have the mean of jobs by id and year in another column. </p> <pre><code> id year quarter month jobs 1 2007 1 1 10 1 2007 1 ...
<p>Using <code>transform</code> then <code>drop_duplicates</code></p> <pre><code>df['jobs1']=df.groupby(['id','quarter'])['jobs'].transform('mean') df['jobs_year']=df.groupby(['id','year'])['jobs'].transform('mean') df=df.drop_duplicates(['id','year','quarter']) df Out[305]: id year quarter month jobs jo...
python|pandas|numpy
3
374,749
47,585,653
returning rows within range in pandas MultiIndex
<p>I have a dataframe that looks like:</p> <pre><code> count year person a.smith 1 2008 b.johns 2 c.gilles 3 a.smith 4 2009 b.johns 3 c.gilles 2 </code></pre> <p>in which both <code>year</code> and <code>person</code> are part of the index. I'd like to return all ...
<p>Using <code>pd.IndexSlice</code></p> <pre><code>idx = pd.IndexSlice df.loc[idx[:,'a.smith'],:] Out[200]: count year person 2008 a.smith 1 2009 a.smith 4 </code></pre> <p>Data Input </p> <pre><code>df Out[211]: count year person 2008 a.smith 1 b....
python|pandas
0
374,750
47,796,207
subsetting affects .view(np.float64) behaviour
<p>I'm trying to use some sklearn estimators for classifications on the coefficients of some fast fourier transform (technically Discrete Fourier Transform). I obtain a numpy array X_c as output of np.fft.fft(X) and I want to transform it into a real numpy array X_r, with each (complex) column of the original X_c trans...
<p>I get a warning:</p> <pre><code>In [5]: X_c2 = X_c[:,range(3)] In [6]: X_c2 Out[6]: array([[ 0.+0.j, 1.+0.j, 2.+0.j], [ 4.+0.j, 5.+0.j, 6.+0.j]]) In [7]: X_c2.view(np.float64) /usr/local/bin/ipython3:1: DeprecationWarning: Changing the shape of non-C contiguous array by descriptor assignment is deprecat...
python|arrays|numpy|casting|subset
0
374,751
47,600,891
Slice dataframe for each unique pair of columns
<p>I want to split a pandas dataframe according to unique pairs taken from two columns, then select the rows relative to that pair and project the remaining columns.</p> <pre><code>df: Col1 Col2 Col3 Col4 1 1 a 100 1 2 b 200 1 2 c 300 1 2 d 400 ...
<p>Using <code>groupby</code></p> <pre><code>for x,y in df.groupby(['Col1','Col2']): print(x) print(y) (1, 1) Col1 Col2 Col3 Col4 0 1 1 a 100 (1, 2) Col1 Col2 Col3 Col4 1 1 2 b 200 2 1 2 c 300 3 1 2 d 400 (3, 4) Col1 Col2 Col3 Col4 4 3 ...
python|pandas
1
374,752
47,883,487
pandas: applying function over each row of Dataframe
<p>I have a pandas DataFrame which contains 3 columns:</p> <pre><code>| val1 | val2 | val3 | |--------------------------| | Nike | NaN | NaN | | Men | Adidas | NaN | | Puma | Red | Women | </code></pre> <p>and 3 lists:</p> <pre><code>Brands = ['Adidas', 'Nike', 'Puma'] Gender = ['Men'...
<p>You can use:</p> <pre><code>df['brand'] = df[df.isin(Brands)].ffill(axis=1).iloc[:, -1] df['gender'] = df[df.isin(Gender)].ffill(axis=1).iloc[:, -1] df['color'] = df[df.isin(Color)].ffill(axis=1).iloc[:, -1] print (df) val1 val2 val3 brand gender color 0 Nike NaN NaN Nike NaN NaN 1 Men ...
python|python-2.7|pandas|dataframe|apply
0
374,753
47,784,388
How to prepare data.frame for keras using tensoflow CNN in r
<p>I have been trying to prepare a train data set for CNN in keras, but i can't find the way to properly set the data. </p> <p>In the keras <a href="https://keras.rstudio.com/articles/examples/mnist_cnn.html" rel="nofollow noreferrer">CNN example</a>, they use the MNIST data set, in which:</p> <pre><code>library(kera...
<p>This might help:</p> <pre><code># Create an empty array the size you want x_array &lt;- array(NA, dim = c(3, 3, length(x))) # Loop in each object of your list into the array for (i in length(x)) { x_array[,, i] &lt;- x[[i]] } </code></pre>
r|tensorflow|keras
0
374,754
47,972,667
Importing pandas.io.data
<p>I am following along with this tutorial: <a href="https://pythonprogramming.net/data-analysis-python-pandas-tutorial-introduction/" rel="nofollow noreferrer">https://pythonprogramming.net/data-analysis-python-pandas-tutorial-introduction/</a></p> <p>He suggests the following import:</p> <pre><code>import pandas.io...
<p><strong>Update:</strong> </p> <p>As mentioned by wilkas, now you might need to do </p> <pre><code>import pandas_datareader.data as web </code></pre> <hr> <p>I am assuming that you are using the latest version of the package. Check out the newest documentation at <a href="https://pandas-datareader.readthedocs.io/...
python|python-3.x|pandas
3
374,755
47,587,595
Google Cloud ML: Use Nightly TF Import Error No Module tensorflow
<p>I want to train the NMT model from Google on Google Cloud ML. <a href="https://github.com/tensorflow/nmt" rel="nofollow noreferrer">NMT Model</a></p> <p>Now I put all input data in a bucket and downloaded the git repository. The model needs the nightly version of tensorflow so I defined it in setup.py and when I use...
<p>The TensorFlow 1.5 might need newer version of CUDA (i.e., CUDA 9), and but the version CloudML Engine installed is CUDA 8. Can you please try to use TensorFlow 1.4 instead, which works on CUDA 8? Please tell us if 1.4 works for you here or send us an email via cloudml-feedback@google.com</p>
tensorflow|google-cloud-ml
0
374,756
47,802,612
weird behavior of numpy.histogram / random numbers in numpy?
<p>I stumbled upon some peculiar behavior of random numbers in Python , specifically I use the module numpy.random.</p> <p>Consider the following expression:</p> <pre><code>n = 50 N = 1000 np.histogram(np.sum(np.random.randint(0, 2, size=(n, N)), axis=0), bins=n+1)[0] </code></pre> <p>In the limit of large <code>N</...
<p>You're using <code>histogram</code> wrong. The bins aren't where you think they are. They don't go from 0 to 50; they go from the minimum input value to the maximum input value. The 0s represent bins that lie entirely between two integers.</p> <p>Try it with <code>numpy.bincount</code>:</p> <pre><code>In [31]: n =...
python|numpy|random|statistics
5
374,757
47,836,295
Tensorflow. ValueError: The two structures don't have the same number of elements
<p>My current code for implementing encoder lstm using <code>raw_rnn</code>. This question is also related to another question I asked before (<a href="https://stackoverflow.com/questions/47835350/tensorflow-raw-rnn-retrieve-tensor-of-shape-batch-x-dim-from-embedding-matrix">Tensorflow raw_rnn retrieve tensor of shape ...
<p>Resolved the problem by changing initial state and input:</p> <blockquote> <p>init_input = tf.zeros([batch_size, input_embedding_size], dtype=tf.float32)</p> <p>init_cell_state = cell.zero_state(batch_size, tf.float32)</p> </blockquote> <pre><code>def loop_fn_initial(): init_elements_finished = (0 &gt;=...
python|machine-learning|tensorflow|nlp|lstm
2
374,758
47,901,313
tensorflow.python.framework.errors_impl.NotFoundError: Op type not registered 'FertileStatsResourceHandleOp'
<p>I trying to run some example for tensorflow but it not works since such exception. I have no idea how to solve it?</p> <p>Probably I need install some packages or this example is not compatible with Tensorflow 1.4. I am using Windows 10, no cuda, Python 3.6.</p> <p>Is it require other version Tensorflow or it is n...
<p>I ran into the same issue today. I resolved it by updating my installed version of Tensorflow (or Tensorflow-GPU) In my case, I was on 1.8 and updating to 1.9 fixed it.</p> <p>All things aside, check your Tensorflow version and adjust as necessary Steve</p>
python|tensorflow
0
374,759
47,620,346
Python Pandas: How can I count the number of times a value appears in a column based upon another column?
<p><a href="https://i.stack.imgur.com/iB5HO.jpg" rel="nofollow noreferrer">This is my pandas dataframe I am referring to.</a></p> <p>Basically I would like to be able to display a count on <code>'crime type'</code> based on <code>'council'</code>. So for example, where <code>'council == Fermanagh and omagh'</code> cou...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>size</code></a...
python|pandas|dataframe|count
3
374,760
47,698,020
How to populate Pandas dataframe as function of index and columns
<p>I have a dataframe where the index and column are both numbers--i.e.</p> <pre><code>rng = np.arange(2,51) box = pd.DataFrame(index = rng, columns = rng) </code></pre> <p>I want the values of the dataframe to be a function of the index and column--so for instance box[2][2] should equal 4.</p> <p>Currently I have i...
<p>Here's what I think you should be doing with numpy broadcasting:</p> <pre><code>import numpy import pandas rng = numpy.arange(2, 51) box = pandas.DataFrame(index=rng, columns=rng, data=rng*rng[:, None]) </code></pre> <p>In the case that knowing all of the value ahead of time isn't feasible, you could assign them ...
python|pandas|dataframe
3
374,761
47,736,468
how to use custom calculation based on two dataframes in python
<p>I have 2 dataframes as below,</p> <p>df1</p> <pre><code>index X1 X2 X3 X4 0 6 10 6 7 1 8 9 11 13 2 12 13 15 11 3 8 11 7 6 4 11 7 6 6 5 13 14 11 10 </code></pre> <p>df2</p> <pre><code>index Y 0 20 1 14 2 17 3 14 4 15 5 20 </code></pre> <p>I want to get 3rd...
<p>You can use numpy for vectorized solution i.e </p> <pre><code>df[df.columns] = (df2.values - df2.values/df.values) X1 X2 X3 X4 index 0 16.666667 18.000000 16.666667 17.142857 1 12.250000 12.444444 12.727273 12.923077 2 ...
python|pandas|numpy|dataframe
1
374,762
47,612,822
How to create pandas dataframe from Twitter Search API?
<p>I am working with the Twitter Search API which returns a dictionary of dictionaries. My goal is to create a dataframe from a list of keys in the response dictionary.</p> <p>Example of API response here: <a href="https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html" rel="nofollow ...
<p>I will share a more generic solution that I came up with, as I was working with the Twitter API. Let's say you have the ID's of tweets that you want to fetch in a list called <code>my_ids</code> :</p> <pre><code># Fetch tweets from the twitter API using the following loop: list_of_tweets = [] # Tweets that can't be...
python|api|pandas|twitter
1
374,763
47,612,069
Tensorflow Serving: Large model, protobuf error
<p>I am trying to make serve a big (1.2 GB in size) model with Tensorflow Serving, but I am getting a:</p> <pre><code>2017-12-02 21:55:57.711317: I external/org_tensorflow/tensorflow/cc/saved_model/loader.cc:236] Loading SavedModel from: ... [libprotobuf ERROR external/protobuf_archive/src/google/protobuf/io/coded_str...
<p>Hope it helps someone, but I "found" a solution.</p> <p>The major problem was obvious; his is an NLP model, thus it has a big vocabulary that goes along with it. Leaving the vocabulary in the graph definition bloats the metagraphdef, and protobuf is giving an error when faced with such a big protocol. </p> <p>The ...
c++|machine-learning|tensorflow|deep-learning|tensorflow-serving
2
374,764
47,985,750
Extracting data/string from Pandas DF column
<p>Im trying to extract currency pairs from the poloniex API using Python pandas.</p> <p>I believe the data returned is all just a single column name:</p> <pre><code>Columns: [{"BTC_BCN":{"BTC":"479.74697466", "BCN":"1087153595.32266165"}, "BTC_BELA":{"BTC":"32.92293515", "BELA":"1807337.13247948"}, "BTC_BLK":{"BTC":...
<p>You don't need <code>BeautifulSoup</code> here at all. <em>The contents of the webpage is JSON</em> - parse it with <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html" rel="nofollow noreferrer"><code>.read_json()</code></a> directly:</p> <pre><code>df = pd.read_json('https://polon...
python|pandas|beautifulsoup
0
374,765
47,736,531
Vectorized matrix manhattan distance in numpy
<p>I'm trying to implement an efficient vectorized <code>numpy</code> to make a Manhattan distance matrix. I'm familiar with the construct used to create an efficient Euclidean distance matrix using dot products as follows:</p> <pre><code>A = [[1, 2] [2, 1]] B = [[1, 1], [2, 2], [1, 3], [1, 4]]...
<p>I don't think we can leverage BLAS based matrix-multiplication here, as there's no element-wise multiplication involved here. But, we have few alternatives.</p> <p><strong>Approach #1</strong></p> <p>We can use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="no...
python|numpy|vectorization
18
374,766
47,583,428
Pandas duplicates when grouped
<pre><code>x = df.groupby(["Customer ID", "Category"]).sum().sort_values(by="VALUE", ascending=False) </code></pre> <p>I want to group by Customer ID but when I use above code, it duplicates customers...</p> <p>Here is the result:</p> <p><a href="https://i.stack.imgur.com/y4UDn.png" rel="nofollow noreferrer"><img sr...
<p>I think you are looking for something like this:</p> <pre><code>df_out = df.groupby(['Customer ID','Category']).sum() df_out.reindex(df_out.sum(level=0).sort_values('Value', ascending=False).index,level=0) </code></pre> <p>Output:</p> <pre><code> Value Customer ID Category B ...
pandas|pandas-groupby
2
374,767
47,766,805
pandas only shows date and drops time when I select data from database
<p>how are you?</p> <p>I'm new to pandas and I have faced a problem where I'm using <code>read_sql</code>.</p> <pre><code>df = pd.read_sql("select TIME, col_1, col_2 from TABLE", connection) </code></pre> <p>A real database has TIME data which looks like below.</p> <pre><code> TIME 2017-12-08 00:00:00 2017-...
<p>Have you tried accessing the data manually to see if there is a seconds data? i.e.</p> <pre><code>print(df['TIME'][2].second) </code></pre> <p>If this data exists, then what you see is just the <code>__str__</code> representation of <code>M8[ns]</code> objects when your print your dataframe.</p>
python|pandas
0
374,768
47,965,026
Why is my date axis formatting broken when plotting with Pandas' built-in plot calls as opposed to via Matplotlib?
<p>I am plotting aggregated data in Python, using Pandas and Matlplotlib. My axis customization commands are failing as a function of which of two similar functions I'm calling to make bar plots. The working case is e.g.:</p> <pre><code>import datetime import pandas as pd import numpy as np import matplotlib.pyplot a...
<p>Bar plots in pandas are designed to compare categories rather than to display time-series or other types of continuous variables, as stated <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.bar.html" rel="nofollow noreferrer">in the docstring</a>:</p> <blockquote> <p>A bar plo...
python|pandas|matplotlib
1
374,769
47,721,663
How to use tf.nn.crelu in tensorflow?
<p>I am trying different activation functions in my simple neural network. </p> <p>It does not matter using <code>tf.nn.relu</code>, <code>tf.nn.sigmoid</code>,... the network does what it should do. </p> <p>But if I am using <code>tf.nn.crelu</code>, I have a dimension error.</p> <p>It returns something like <code>...
<p>You're right, if you're building the network manually, you need to adjust the dimensions of the following layer to match <code>tf.nn.crelu</code> output. In this sense, <code>tf.nn.crelu</code> is <em>not</em> interchangeable with <code>tf.nn.relu</code>, <code>tf.nn.elu</code>, etc.</p> <p>The situation is simpler...
machine-learning|tensorflow|computer-vision|activation-function
1
374,770
47,775,927
Pandas Transform Position/Rank in Group
<p>I have the following <code>DataFrame</code> with two groups of animals and how much food they eat each day,</p> <pre><code>df = pd.DataFrame({'animals': ['cat', 'cat', 'dog', 'dog', 'rat', 'cat', 'rat', 'rat', 'dog', 'cat'], 'food': [1, 2, 2, 5, 3, 1, 4, 0, 6, 5]},...
<p>Use double <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code></a>:</p> <pre><code>df['daily_meal'] = df.groupby(['animals', 'groups'])['food'].transform('mean') df['group_rank'] = df.groupby('groups')['daily_mea...
python|pandas|pandas-groupby
6
374,771
47,860,633
TensorFlow pip install not working on Windows 10
<p>I have spent a lot of time tying to install tensorflow for windows. I keep getting errors like "not supported."</p> <p>I have tried the commands:</p> <pre><code>pip install tensorflow </code></pre> <p>and</p> <pre><code>pip install --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-0.12.0...
<p>Note that TensorFlow needs x64 Windows and that Python 3.5 and higher go with <code>pip3</code> instead of <code>pip</code>. Still, there's a glitch with the installation script; I ran into the same problem and resolved it by using <a href="https://www.anaconda.com/distribution/#download-section" rel="nofollow noref...
python|tensorflow|pip
0
374,772
47,714,805
Predicting the future with pandas and statsmodels
<p>What i need to do is plot future temperature with these "requirments" : " assume that temperature is roughly a linear function of CO2 emission, estimating the coefficients of the linear function from recent data points (using the past 2 is fine, as is using the past 10 or so if you want to be more thorough). Furthe...
<p>The method <a href="http://www.statsmodels.org/dev/generated/statsmodels.regression.linear_model.OLS.predict.html#statsmodels.regression.linear_model.OLS.predict" rel="nofollow noreferrer"><code>OLS.predict</code></a> do not take <code>x</code> as arguments but the model parameters (and eventually exogenous data). B...
python|pandas|statsmodels
4
374,773
47,708,345
Pandas substring search for filter
<p>I have a use case where I need to validate each row in the df and mark if it is correct or not. Validation rules are in another df.</p> <pre><code>Main col1 col2 0 1 take me home 1 2 country roads 2 2 country roads take 3 4 me home Rules col3 col4 0 1 take 1 2 home 2 ...
<p>Merge and then apply the condtion using np.where i.e </p> <pre><code>temp = main.merge(rules,left_on='col1',right_on='col3') temp['results'] = temp.apply(lambda x : np.where(x['col4'] in x['col2'],'Pass','Fail'),1) no_dupe_df = temp.drop_duplicates('col2',keep='last').drop(['col3','col4'],1) col1 ...
python|pandas|dataframe
1
374,774
49,222,772
Pandas: frequencies per date grouped by column in a form of a list
<p>I would like to obtain frequencies of technologies per date from pandas data frame. A reproducible example:</p> <pre><code>data = pd.DataFrame( {'dates': ['2017-01-31', '2017-02-28', '2017-02-28'], 'tech': [['c++', 'python'], ['c++', 'c', 'java'], ['java']]} ) </code></pre> <p>The end resul...
<p>Seems like you need <code>get_dummies</code></p> <pre><code>pd.get_dummies(data.set_index('dates').tech.apply(pd.Series).stack()).sum(level=0) Out[193]: c c++ java python dates 2017-01-31 0 1 0 1 2017-02-28 1 1 2 0 </code></pre> <p>Or <code>skl...
python|string|list|pandas|pandas-groupby
2
374,775
49,214,286
Find common values between 3 DataFrames?
<p>I have 3 dataframes: df1, df2, and df3. </p> <pre><code>df1 = 'num' 'type' 23 a 34 b 89 a 90 c df2 = 'num' 'type' 23 a 34 b 56 a 90 c df3 = 'num' 'type' 56 a 34 s 71 a 90 ...
<p>et voila my friend</p> <pre><code>df_full = pd.concat([df1,df2,df3], axis = 0) df_agg = df_full.groupby('num').agg({'type': 'count'}) df_agg = df_agg.loc[df_agg['type'] &gt;= 2] </code></pre>
python|pandas|dataframe|counter
4
374,776
49,144,138
How to subtract numbers in 1 column of a pandas dataframe?
<p>Currently, I am using Pandas and created a dataframe that has two columns: </p> <pre><code>Price Current Value 1350.00 0 1.75 0 3.50 0 5.50 0 </code></pre> <p>How Do I subtract the first value, and then subtract the sum of the previous two values, continuously (Similar to...
<p>This will achieve what you need , <code>cumsum</code></p> <pre><code>1350*2-df.Price.cumsum() Out[304]: 0 1350.00 1 1348.25 2 1344.75 3 1339.25 Name: Price, dtype: float64 </code></pre> <p>After assign it back </p> <pre><code>df.Current=1350*2-df.Price.cumsum() df Out[308]: Price Current 0 13...
python|pandas|dataframe
2
374,777
48,924,041
Remove a row in 3d array
<p>given the index of a row, l would like to remove that row.</p> <p>l tried the following :</p> <pre><code>a.shape Out[128]: (60, 3) </code></pre> <p>when l try to remove the row number 14 from my 3D array <strong>a</strong> as follow :</p> <pre><code>np.delete(a,14,axis=0) a.shape Out[130]: (60, 3) </code></pre> ...
<p>Assignment will solve it as apparently <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html" rel="nofollow noreferrer">delete</a> returns an array instead of working inplace:</p> <pre><code>a = np.delete(a,14,axis=0) </code></pre>
python-3.x|numpy
1
374,778
49,316,668
Can we combine conditional statements using column indexes in Python?
<p><strong>For the following dataframe:</strong></p> <hr> <p><strong>Headers:</strong> Name P1 P2 P3</p> <hr> <p><strong>L1:</strong> A 1 0 2</p> <hr> <p><strong>L2:</strong> B 1 1 1</p> <hr> <p><strong>L3:</strong> C 0 5 6</p> <p>I want to get yes where all P1, P2 and P3 are greater than...
<p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.all.html" rel="nofollow noreferrer"><code>DataFrame.all</code></a> for check all <code>True</code>s per rows:</p> <pre><code>cols = ['P1','P2','P3'] df['Check']= np.where((df[cols] &gt; 0).all(axis=1),'Yes','No') print (df)...
python|pandas|numpy
0
374,779
48,919,302
Join in near index python
<p>Due to the lack of power at the station I use the meteorological data, I do not have the schedules and I need to create these schedules with <code>nan</code>. I can create the times normally (times where they are of frequency of <code>10 Hz</code>). But when the station comes back to work the rounding of the date th...
<p>Solved using </p> <pre><code>df.index = df.index.round('0.1S') </code></pre>
python|pandas
0
374,780
49,097,905
Referring to previous groups in Pandas SeriesGroupBy
<p>I'm writing a Python script which compares the maximum values of each group. I think there must be more beautiful ways using methods offered by <code>pandas</code> or not using global variables such as <code>previous_max</code> in the following code snippet. Please tell me how to do it.</p> <pre><code>import pandas...
<p>Use:</p> <ul> <li><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code></a> by <code>max</code>, get difference by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofoll...
python|pandas|pandas-groupby
0
374,781
49,200,989
calculate value based on value from previous value
<p>I have the following dataset given, describing transactions for purchasing items in a frame (frameNo). the frame encompasses events that happened in a single minute. therefore, the "currentGold" value only depicts the value of gold a player has had entering the frame. </p> <p>What I am trying to do, is to calculate...
<p>Is it possible that you have an error in your "desired" output in the following rows?</p> <pre><code>948881246 BR1 12.0 701438 1051 850 400 650 948881246 BR1 12.0 701796 1042 850 300 350 948881246 BR1 12.0 703291 2010 ...
python-3.x|pandas|pandas-groupby|cumulative-sum
1
374,782
49,273,684
output is in NAN Wrong distance not be calculated
<pre><code>Data input: cell_id Lat_Long Lat Long 15327 28.46852_76.99512 28.46852 76.99512 52695 28.46852_76.99512 28.46852 76.99512 52692 28.46852_76.99512 28.46852 76.99512 29907 28.46852_76.99512 28.46852 76.99512 29905 28.46852_76.99512 28.46852 76.99512 <...
<p><code>Geo.Inverse</code> returns a dictionary not a single value. Check the <a href="https://geographiclib.sourceforge.io/html/python/code.html" rel="nofollow noreferrer">documentation</a>.</p> <p>The distance is returned with the key <code>s12 – the distance from the first point to the second in meters</code></p> ...
python|pandas|geodesic-sphere
0
374,783
48,952,625
Split every row containing long text into multiple rows in pandas
<p>I have a DataFrame which has a string column such as below:</p> <pre><code>id text label 1 this is long string with many words 1 2 this is a middle string 0 3 short string 1 </code></pr...
<p>You could</p> <pre><code>In [1257]: n = 3 In [1279]: df.set_index(['label', 'id'])['text'].str.split().apply( lambda x: pd.Series([' '.join(x[i:i+n]) for i in range(0, len(x), n)]) ).stack().reset_index().drop('level_2', 1) Out[1279]: label id 0 0 1 1 this...
python|pandas
1
374,784
49,127,947
how to change a object-form array to a normal one
<p>Here is a <code>.txt</code> data file,where the first 2 lines are some headers: </p> <pre><code> REC OBS REPORT TIME STATION LATI- LONGI- ELEV STN PR STN DSLP ALTIM AIR.T DEWPT R.HUM WIND WIND HOR 3H PR 24H PR | ...
<p>Maybe you should call <code>delim_whitespace=True</code> and manually rewrite your <code>columns</code>.</p> <pre><code>obs = pd.read_table('sample.tex', header=1,delim_whitespace=True).drop('|',axis=1) obs.columns = ['REC_TYPE','OBS_TYPE','REPORT_TIME','STATION_BBSSS','LATITUDE','LONGITUDE','ELEV','STN_PR', ...
python|pandas|numpy
1
374,785
49,122,116
Error importing keras backend - cannot import name has_arg
<p>i attempt to import keras backend to get_session as follows, but i encounter an error: <a href="https://i.stack.imgur.com/CQHYI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CQHYI.png" alt="enter image description here"></a></p>
<p>There should be no need to import the tensorflow_backend explicitly.</p> <p>Look at the first lines of an example from the <a href="https://keras.io/backend/" rel="nofollow noreferrer">Keras documentation</a>:</p> <pre><code># TensorFlow example &gt;&gt;&gt; from keras import backend as K &gt;&gt;&gt; tf_session =...
tensorflow|keras
1
374,786
49,141,730
JSON Normalize On Extremely Nested JSON Data Structure
<p>I have the following JSON data structure. I am trying to get it into a Pandas DataFrame. </p> <p>The pandas.io.json json_normalize works OK, except for the 'tunnels-in' and 'tunnels-out' sections. These are lists with some nested dictionaries inside of them. I have tried almost every format of the json_normaliz...
<p>I'm struggling with this right now. I got around that selection by index <code>[0]</code> issue by pulling it out into another pandas.dataframe. As such:</p> <pre><code>df = json_normalize(pd.DataFrame(list(json_dict['data']['viptela-oper-vpn']['dpi']['flows']))['tunnels-in']) </code></pre>
python|json|pandas
0
374,787
48,920,430
Resampling hourly data to 6 hours
<pre><code> Timestamp Value 0 2017-11-22 09:00:00 12.356965 1 2017-11-22 10:00:00 26.698426 2 2017-11-22 11:00:00 13.153104 3 2017-11-22 12:00:00 15.425182 4 2017-11-22 13:00:00 15.161085 5 2017-11-...
<p>You can use <code>rolling.mean</code>:</p> <pre><code>df.set_index('Timestamp').rolling('6h').mean() Value Timestamp 2017-11-22 09:00:00 12.356965 2017-11-22 10:00:00 19.527696 2017-11-22 11:00:00 17.402832 2017-11-22 12:00:00 16.908419 2017-11-22 13:00:00 16.5589...
python|pandas
3
374,788
49,108,757
Error installing pandas and quandl via pip - windows
<p>Goodmorning, I'm trying installing pandas and quandl. I used <code>pip install quandl</code> and <code>pip install pandas</code> but the feedback is for both:</p> <pre><code>Command "C:\Python34\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\tomsa\\AppData\\Local\\Temp\\pip-build-m2kos9k2\\panda...
<p>Solved installing them manually from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pandas" rel="nofollow noreferrer">here</a> via </p> <pre><code>pip install pandas‑0.20.3‑cp34‑cp34m‑win_amd64.whl </code></pre> <p>in the directory (normally X:\Users\Download in windows if the wheel has not been moved somewhe...
python-3.x|pandas|pip|quandl
1
374,789
49,204,671
Pandas : Boolean indexing on multiple columns
<p>I have a data frame as below.</p> <pre><code>In [23]: data2 = [{'a': 'x', 'b': 'y','c':'q'}, {'a': 'x', 'b': 'p', 'c': 'q'}, {'a':'p', 'b':'q'},{'a':'q', 'b':'y','c':'q'}] In [26]: df = pd.DataFrame(data2) In [27]: df Out[27]: a b c 0 x y q 1 x p q 2 p q NaN 3 q y q </code></pre> <p>I wan...
<p>You can compare your df with 'x' and 'y' and then do a logical or to find rows with either 'x' or 'y'. Then use the boolean array as index to select those rows.</p> <pre><code>df.loc[(df.eq('x') | df.eq('y')).any(1)] Out[68]: a b c 0 x y q 1 x p q 3 q y q </code></pre>
python|pandas
2
374,790
49,165,672
Using pandas to find the max value for specific rows
<p>I've got a csv that looks like this (there are more years):</p> <pre><code>year,title_field,value 2009,Total Housing Units,39499 2009,Vacant Housing Units,3583 2009,Occupied Housing Units,35916 2008,Total Housing Units,41194 2008,Vacant Housing Units,4483 2008,Occupied Housing Units,36711 2009,Owner Occupied,18057 ...
<p>I think you need <code>idxmax</code></p> <pre><code>df.loc[[df.groupby(['title_field'])['value'].idxmax().loc['Vacant Housing Units']]] Out[92]: year title_field value 4 2008 Vacant Housing Units 4483 </code></pre>
python|pandas|csv
1
374,791
49,277,640
How to extract values from a Pandas DataFrame, rather than a Series (without referencing the index)?
<p>I am trying to return a specific item from a Pandas DataFrame via conditional selection (and do not want to have to reference the index to do so).</p> <p>Here is an example:</p> <p>I have the following dataframe:</p> <pre><code> Code Colour Fruit 0 1 red apple 1 2 orange orange 2 3 yellow ban...
<p>Let's try this:</p> <pre><code>df.loc[df['Fruit'] == 'blueberry','Code'].values[0] </code></pre> <p>Output:</p> <pre><code>5 </code></pre> <p>First, use <code>.loc</code> to access the values in your dataframe using the boolean indexing for row selection and index label for column selection. The convert that re...
python|pandas|dataframe
5
374,792
49,143,496
compare two pandas columns of mixed data datatypes
<p>i have a dataframe as follows, column A and Refer has values of types str,float and int. i have to compare and create a new column if both values same then pass or else fail. it is very simple if all values string datatype but before compare any numeric value in column A must be rounded of, if its a decimal and ends...
<p>IIUC, there are lot of build in function in pandas </p> <p>Update <code>to_numeric</code></p> <pre><code>df.apply(pd.to_numeric,errors='ignore',axis=1).nunique(1).eq(1).map({True:'Pass',False:'Fail'}) Out[272]: 0 Pass 1 Pass 2 Fail 3 Pass 4 Pass 5 Fail 6 Fail 7 Pass dtype: object </code></...
python|pandas
1
374,793
49,232,854
Feature Selection using MRMR
<p>I found two ways to implement MRMR for feature selection in python. The source of the paper that contains the method is: </p> <p><a href="https://www.dropbox.com/s/tr7wjpc2ik5xpxs/doc.pdf?dl=0" rel="noreferrer">https://www.dropbox.com/s/tr7wjpc2ik5xpxs/doc.pdf?dl=0</a></p> <p>This is my code for the dataset.</p> ...
<p>You'll probably need to contact either the authors of the original paper and/or the owner of the Github repo for a final answer, but most likely the differences here come from the fact that you are comparing 3 different algorithms (despite the name).</p> <p><a href="https://en.wikipedia.org/wiki/Minimum_redundancy_...
python|pandas|numpy
2
374,794
49,207,577
DataFrame to List format
<p>Im converting DataFrame into List using following code</p> <pre><code>resultDataFrame = [] resultDataFrame = pd.DataFrame(resultDataFrame, columns=('day', 'hour', 'minute')) </code></pre> <p>and appending values ...</p> <pre><code>resultDataFrame.to_dict('l') {'day': [6], 'hour': [12], 'minute': [54]} </code></pr...
<p>You can select first row for <code>Series</code> e.g. by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><c...
python|pandas
2
374,795
49,150,462
getting the top 2 values of a list
<p>In the below dataframe I have a list of values, how can we get the top 2 repeated from a list ?</p> <p>DataFrame:</p> <pre><code>user pro A [AA,AA,AA,BB,CC,AA,AA,CC,CC,BB] B [AA, BB, EE,BB,BB,EE,AA,CC,BB,EE] C [EE,EE,EE,CC,CC,CC,CC,DD,DD,AA] D [DD,AA,AA,AA,AA,AA,BB,BB,BB] </code></pre> <p>Expected outp...
<p>Use <a href="https://docs.python.org/3/library/collections.html#collections.Counter.most_common" rel="nofollow noreferrer"><code>collections.Counter.most_common</code></a>:</p> <pre><code>from collections import Counter df['new'] = df['pro'].apply(lambda x: [k for k, v in Counter(x).most_common(2)]) print (df) ...
python|pandas
4
374,796
49,038,659
How to substitute NaNs in a numpy array with elements in another list
<p>I'm facing an issue with a basic substitution. I have two arrays, one of them contains numbers and NaN, and the other one numbers that are supposed to replace the NaN, obviously ordered as I wish. As an example: <code>x1 = [NaN, 2, 3, 4, 5, NaN, 7, 8, NaN, 10]</code> and <code>fill = [1, 6, 9]</code> and I want to o...
<p>Does this work for you?</p> <pre><code>train = np.array([2, 4, 4, 8, 32, np.NaN, 12, np.NaN]) fill = [1,3] train[np.isnan(train)] = fill print(train) </code></pre> <p>Output:</p> <pre><code>[ 2. 4. 4. 8. 32. 1. 12. 3.] </code></pre>
python|python-3.x|numpy
4
374,797
49,158,505
Visualizing spherical harmonics in Python
<p>I am trying to draw a spherical harmonics for my college project. The following formula I want to depict,</p> <pre><code>Y = cos(theta) </code></pre> <p>for that, I wrote this code</p> <pre><code>import numpy as np from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt def sph2cart(r, phi, tta):...
<p>The picture in the Wikipedia article <a href="https://en.wikipedia.org/wiki/Spherical_harmonics" rel="nofollow noreferrer">Spherical harmonics</a> is obtained by using the <em>absolute value</em> of a spherical harmonic as the r coordinate, and then coloring the surface according to the sign of the harmonic. Here is...
python|python-3.x|numpy
4
374,798
49,082,287
Read text file data to pandas DataFrame
<p>I have specific file format from CNC (<em>work center</em>) data. saved like .txt . I want read this table to pandas dataframe but i never seen this format before.</p> <pre><code>_MASCHINENNUMMER : &gt;0-251-11-0950/51&lt; SACHBEARB.: &gt;BSTWIN32&lt; _PRODUKTSCHLUESSEL : &gt;BST 500&lt; DATUM ...
<p>Yes, it is possible, but really data dependent:</p> <ul> <li>first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> with omit first <code>3</code> rows and omit first whitespaces</li> <li>omit trailing whitespaces in columns by ...
python|pandas
6
374,799
48,923,565
math.fsum for arrays of multiple dimensions
<p>I have a numpy array of dimension <code>(i, j)</code> in which I would like to add up the first dimension to receive a array of shape <code>(j,)</code>. Normally, I'd use NumPy's own <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html" rel="nofollow noreferrer"><code>sum</code></a></p> <p...
<p>This one works fast enough for me.</p> <pre><code>import numpy import math a = numpy.random.rand(100, 77) a = numpy.swapaxes(a, 0, 1) a = numpy.array([math.fsum(row) for row in a]) </code></pre> <p>Hopefully it's the axis you are looking for (returns 77 sums).</p>
python|arrays|numpy
2