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
364,900
49,519,573
Using Restored Variables Across Sessions Gives "uninitialized value" Error
<p>I am restoring variables into a graph in one session, closing the session and then creating a new session where I attempt to evaluate the graph. When doing so I get the error <code>FailedPreconditionError: Attempting to use uninitialized value ...</code>. </p> <p>Attempting to evaluate the graph in the first sessio...
<p>According to <a href="https://www.tensorflow.org/programmers_guide/faq" rel="nofollow noreferrer">https://www.tensorflow.org/programmers_guide/faq</a>:</p> <blockquote> <p>What is the lifetime of a variable?</p> <p>A variable is created when you first run the tf.Variable.initializer operation for that variable in a ...
tensorflow
2
364,901
49,696,700
if string in pandas series contains a string from another pandas dataframe
<p>Struggling newbie. If I have two pandas dataframes something like :</p> <pre><code> import pandas as pd data = {'col1': ['black sphynx bob','brown labrador','grey labrador mervin', 'brown siamese cat','white siamese']} desc_df = pd.DataFrame(data=data) catg = {'dog': ['labrador','rottwe...
<p>You can using <code>str.contains</code> + <code>np.where</code></p> <pre><code>desc_df['col2']=np.where(desc_df.col1.str.contains(catg_df.cat.str.cat(sep='|')),'cat','dog') desc_df Out[1538]: col1 col2 0 black spyhnx bob dog 1 brown labrador dog 2 grey labrador mervin dog 3 b...
python|pandas
1
364,902
49,480,017
Pandas: adding a column to a dataframe from dictionary, when keys are the indices of the dataframe
<p>I know this question is similar to a lot of other questions, but I don't see an answer to this specific situation. Suppose I have a dataframe with unique index values, and I want to add a column with a dictionary where the keys are the index values. What is the easiest way to do this?</p> <p>The best way that I've ...
<p>Use a list comprehension;</p> <pre><code>df['nums'] = [dic.get(i) for i in df.index] df nums Aaron 25 Benjamin 40 Clinton 55 Daniel 1 </code></pre>
python|python-3.x|pandas
3
364,903
49,450,714
Resemplig and adding missing rows
<p>I have got a dataframe that represent 1 Sec of data that supposed to be sample at 100 Hz. </p> <p>I would like to 1) <code>resample</code> it which at the rate of 10 Millisecond with "avg" approach for each column and 2) add extra rows based on interpolation approach when missing, as in the following: </p> <p>D...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow noreferrer"><code>resample</code></a> by <code>10L</code> for <code>10ms</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.interpolate.html" rel="nofoll...
python|pandas|dataframe
2
364,904
49,637,647
how we can convert categorical data in a column into numbered data
<p>Lets take an example, suppose my table values are:</p> <p><strong>subjects</strong></p> <p>english </p> <p>mathematics </p> <p>science </p> <p>english </p> <p>science</p> <p>how can i convert these string data into numbered data as shown in table below.</p> <p><strong>subjects</strong></p> <p>1</p> <p>2</p...
<p>Assuming your original dataframe looks like this:</p> <pre><code>&gt;&gt;&gt; df subjects 0 english 1 mathematics 2 science 3 english 4 science </code></pre> <p>you could use <code>pd.factorize</code>:</p> <pre><code>df['factor'] = pd.factorize(df['subjects'])[0]+1 &gt;&gt;&gt; df ...
python|pandas|sklearn-pandas
0
364,905
49,345,786
How to install tensorflow GPU version on VirtualBox Ubuntu OS. And host OS is windows 10
<p>I want to setup environment for deep learning using Anaconda (python 3.6). I have system having nvidia get force 1060 with windows installed on it. Now I want to have Ubuntu OS in VB. Can I install Cuda and CuDNN libraries in VB based Ubuntu OS? Any one that can help me?</p>
<p>You <strong>can not</strong> use your GPU on <strong>virtual box</strong>. Because virtual box <a href="https://superuser.com/a/1020250">cannot</a> pass through the host GPU.</p> <p>However, you can use the windows version of python which can use the GPU on your windows machine. <a href="https://www.tensorflow.org/...
python|tensorflow|machine-learning|deep-learning|anaconda
7
364,906
49,356,541
TensorFlow Model takes exponential time on large dataSet
<p>I am using TensorFlow for Poets to detect features in clothing images. I have trained 4 different models(sleeve, shape, length &amp; hemline). Now i pass image urls to each of the model and store the result. Since i have huge data (100k images), so using spark to broadcast 4 models once and passing image RDD to det...
<p>Every call to <code>getLabelDresses</code> in your code adds operations to the graph.</p> <p>Split your code into setup (model loading) part, executed once and execution part that is executed for each image. The latter should only contain calls to <code>Session.run</code>.</p> <p>Another option is to clear graph b...
python|tensorflow|machine-learning|pyspark|deep-learning
1
364,907
49,650,036
TensorFlow | RNN not training (saving)
<p>I am currently working on a RNN which should generate text based on sample text with which it was trained. But for some reason no matter how long I train it it's always spilling out nonsense. You can find the GitHub repo <a href="https://github.com/MrGrimod/rnn_text_gen" rel="nofollow noreferrer">here</a>.</p> <p><...
<p>The problem was that when I restored the model, I used the last untrained layer of the network to predict the next character in <strong>net.run_step()</strong> function.</p>
python|tensorflow|neural-network|recurrent-neural-network
0
364,908
49,731,792
Get all 2D diagonals of a 3D tensor in numpy
<p>I have a 3D tensor <code>A x B x C</code>. For each matrix <code>B x C</code>, I want to extract the leading diagonal. </p> <p>Is there a vectorized way of doing this in numpy or pytorch instead of looping over <code>A</code>?</p>
<p>You can use <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.diagonal.html" rel="nofollow noreferrer">numpy.diagonal()</a></p> <pre><code>np.diagonal(a, axis1=1, axis2=2) </code></pre> <p>Example:</p> <pre><code>In [10]: a = np.arange(3*4*5).reshape(3,4,5) In [11]: a Out[11]: array([[[...
python|numpy|pytorch
3
364,909
49,467,251
Return top n rows based on threshold from pandas dataframe
<p>Here is my input dataframe:</p> <pre><code>df = pd.DataFrame({'Company':['A','B','C','D','E','F'],'Industry':['Metals','Metals','IT','IT','IT','banking'],'ROE':[10,9,5,14,1,9],'ROCE':[10,5,5,1,10,9],'Threshold':[1,1,2,2,2,1]});df </code></pre> <p>Need output as follows:</p> <pre><code>dfout = pd.DataFrame({'Compa...
<p>First, sort your data by ROE/ROCE:</p> <pre><code>df = df.iloc[(-np.maximum(df.ROCE, df.ROE)).argsort()] </code></pre> <p>Next, use <code>groupby</code> + <code>apply</code>:</p> <pre><code>df.groupby('Industry', group_keys=False, sort=False).apply( lambda x: x[:x['Threshold'].unique().item()] ).sort_index() ...
python|pandas|dataframe|pandas-groupby
1
364,910
49,492,171
Pandas interval data (valid from & valid to) to end of month resampling
<p>I have data extracted from a database where the income for a set of users are stored with valid_from &amp; valid_to dates (multiple income per user possible). I would like to make a row-by-row dataset. On each row I would like show the situation at the end of the month grouped per user.</p> <p>For the moment, I cre...
<p>IIUC:</p> <pre><code>interval_data.groupby(level=0,group_keys=False, as_index=False)\ .apply(lambda x: pd.DataFrame({'user':x.user.values,'income':x.income.values}, index=pd.date_range(x.valid_from.values[0], ...
python|pandas|numpy|datetime|intervals
1
364,911
49,535,003
How to use tf.train.Saver in SessionRunHook?
<p>I have trained many sub-models, each sub-models is a part of the last model. And then I want to use those pretrained sub models to initial the last model's parameters. I try to use SessionRunHook to load other ckpt file's model parameters to initial the last model's. I tried the follow code but failed. Hope some adv...
<p>SessionRunHook is not meant for this use case. As the error says, you cannot change the graph once <code>sess.run()</code> has been invoked.</p> <p>You can assign variables using <code>saver.restore()</code> in your "normal code". You don't have to be inside any hooks.</p> <p>Also, if you want to restore many vari...
tensorflow
1
364,912
49,361,124
Create dataframe columns from list with items with Python
<p>I have been searching google and have tried a couple of things but failed to do this. Basically I am pulling data from an api which loads into a json</p> <pre><code>session = requests.Session() s = session.get(url, headers = headers) r = s.json() df = pd.DataFrame(r) print(df) </code></pre> <p>The above code retu...
<p>This should help. Looks like you need to set the values using the details key <code>'details'</code></p> <p><strong>Ex:</strong></p> <pre><code>session = requests.Session() s = session.get(url, headers = headers) r = s.json() df = pd.DataFrame(r['details']) print(df) </code></pre>
python|pandas|dictionary
0
364,913
49,430,866
Get max and min value in a group of strings
<pre><code>values = [5, 6,7,8 , 9, 11,12, 13, 14, 17, 18,19, 20, 21,22, 23, 24, 25, 26, 27, 41, 42, 44, 45, 46, 47] s = pd.Series(values) s1 = s.groupby(s.diff().gt(1).cumsum()).apply(lambda x: ','.join(x.astype(str))) print (s1) </code></pre> <blockquote> <p>0: 5,6,7,8,9</p> ...
<p>I suggest create <code>list</code>s instead joined <code>string</code>s and then use <code>min</code> and <code>max</code>:</p> <pre><code>s1 = s.groupby(s.diff().gt(1).cumsum()).apply(list) print (s1) 0 [5, 6, 7, 8, 9] 1 [11, 12, 13, 14] 2 [17, 18, ...
python|pandas|numpy
0
364,914
49,774,836
Pandas pivot table using sum(min_count=1) in pandas 0.22
<p>I am migrating my code to Pandas 0.22 and running into a problem with a pivot table. In version 0.20 I have a line of code. This has the behaviour that when the cell in the pivot table is empty the sum aggregation returns NAN.</p> <pre><code>workload_pivot_df = pd.pivot_table(workload_df, index=["athlete_id", "dat...
<p>You can use <code>lambda</code> function and for same column name use <code>tuple</code> - first value is new column name and second aggregate function:</p> <pre><code>tup = ('sum', lambda x: x.sum(min_count=1)) workload_pivot_df = pd.pivot_table(workload_df, index=["athlete_id", "date"], ...
python|pandas|dataframe
0
364,915
49,658,030
to_csv is not writing the updated DataFrame
<p>I am importing a csv file as a pandas DataFrame. That DataFrame then gets updated and I am trying to write that information back to the original csv file by overwriting the file. After my code completes, I can see the file save time has updated, so it appears to have saved a new version. However, when I open the fil...
<p>So the problem was much deeper than I had thought and so the cause was not represented in the code I posted, but thankfully it was an easy fix. I have multiple classes in my program and two of them create the object </p> <pre><code>self.site_data=pandas.read_csv("site_data.csv",index_col=0, keep_default_na=False) <...
python|pandas|dataframe
0
364,916
49,405,664
filter rows based on specific conditions in pandas python
<p>I have a dataframe df1:</p> <pre><code>site cell T96976 V96976A T96976 V96976B T96976 V96976C T96976 V96976O T96980 D96980A T96980 D96980B T96980 U96980C T97750 D97750N T97750 D97750A T97750 D97750B T97750 V97750O T97760 V97760A T97760 V97760B T97777 L97777A T97777 U97777B T97777 V97777C T99989 ...
<p>I think need:</p> <pre><code>sites = df.loc[df['cell'].str.contains('[NOP]$'), 'site'] #alternative #sites = df.loc[df['cell'].str[-1].isin(['N','O','P']), 'site'] df = df[~df['site'].isin(sites)] print (df) site cell 4 T96980 D96980A 5 T96980 D96980B 6 T96980 U96980C 11 T97760 V97760A 12 T977...
python-3.x|pandas
0
364,917
49,455,185
Pandas Numpy add a column
<p>I have a numpy array with that shape (n, ) that is an array of tuples that have multiple elements. Is there a way for me to quickly add a column to one of the tuples &amp; it would still have the same shape (n,)?</p>
<p>Since there was no answer to this questions, I wrote a snippet which might be helpful. You can use <code>np.zeros</code> or <code>np.hstack</code> to add new column to the array.</p> <pre><code>import numpy as np def main(): my_tuples = np.array(((1,-2,3),(4,5,6))) element = (7,8) #suppose you want to add...
python|arrays|numpy
0
364,918
49,594,691
how to pad text sequences in R using keras and pad_sequences?
<p>I have a dataset with texts. </p> <pre><code>dat &lt;- data.frame(id=c("1","2","3","4","5"),text=as.character(c("hello","hello you","hello duck","Dogs and cats","hello cats, ducks and dogs")),stringsAsFactors = F) str(dat) </code></pre> <p>and I would like to prepare the text for text classification with keras. Th...
<p>There is nothing wrong in the output. We need to check the dimension</p> <pre><code>dim(data_idx) #[1] 5 10000 </code></pre> <p>It is just that the console is printing only the column header and based on the <code>max.print</code>it couldn't show the whole output</p> <pre><code>#[ reached getOption("max.pri...
r|tensorflow|keras
3
364,919
49,433,840
Tensorflow CUBLAS_STATUS_ALLOC_FAILED error
<pre><code>Tf version: 1.6.0 GPU Os: Windows 10 64bit CUDA: 9.0 CUDNN: 7.0.5 for CUDA 9.0 GPU: GeForce GTX 1070 GPU version: 385.54 RAM: 23.95GB CPU: Intel i7-3770k @3.50GHz Python version: 3.6.4 </code></pre> <p>The code I'm working on worked last week, but not anymore. No changes have been made on th...
<p>Lowering the per_process_gpu_memory_fraction setting seems to work!</p> <pre><code>tf_config = tf.ConfigProto() tf_config.gpu_options.per_process_gpu_memory_fraction = 0.99 with tf.Session(config=tf_config) as sess: </code></pre>
python|python-3.x|tensorflow|cublas|cudnn
0
364,920
49,515,123
Tensorflow: Troubles with .clone() in seq2seq model using Attention and BeamSearch
<p>I am trying to implement a seq2seq model, using bidirectional_dynamic_decode, Attention and the BeamSearchDecoder in Tensorflow (1.6.0). (I tried to copy only the relevant code, to keep it simple)</p> <pre><code># encoder def make_lstm(rnn_size, keep_prob): lstm = tf.nn.rnn_cell.LSTMCell(rnn_size, initializer ...
<p>You need to manually add(or concat) forward and backward state for each MultiRNNCell:</p> <pre><code>def add_stacked_cell_state(forward_state, backword_state, useGRUCell): temp_list = [] for state_fw, state_bw in zip(forward_state, backword_state): if useGRUCell: temp_list.append(tf.add(...
python-3.x|tensorflow|beam-search|seq2seq
0
364,921
49,419,477
tf.train.range_input_producer doesnot work
<p>there ,I am new to tensorflow,when I am trying tf.train.range_input_producer, it does not work from my code:</p> <pre><code>import tensorflow as tf if __name__ == '__main__': with tf.Graph().as_default(): with tf.Session() as sess: queue = tf.train.range_input_producer(tf.Variable(5, tf.int8...
<p>You need to initialize local and global variables before starting queue runners.</p> <pre class="lang-py prettyprint-override"><code>sess.run([tf.local_variables_initializer(), tf.global_variables_initializer()]) </code></pre>
tensorflow
0
364,922
49,483,938
Counting Pedestrians Using TensorFlow's Object Detection
<p>I am new to machine learning field and based on what I have seen on youtube and read on internet I conjectured that it might be possible to count pedestrians in a video using tensorflow's object detection API. </p> <p>Consequently, I did some research on tensorflow and read documentation about how to install tensor...
<p>You are using a pretrained model which is trained to identify people in general. I think you're saying that some people are pedestrians whereas some other people are not pedestrians, for example, someone standing waiting at the light is a pedestrian, but someone standing in their garden behind the street is not a pe...
tensorflow|object-detection-api
2
364,923
49,712,533
How do I merge two pandas dataframes by time series index?
<p>Currently I have two dataframes that look like this:</p> <pre><code>FSample </code></pre> <p><a href="https://i.stack.imgur.com/hhYkn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hhYkn.png" alt="enter image description here"></a></p> <pre><code>GMSample </code></pre> <p><a href="https://i.s...
<p>You get a key error, because the Date is an index, whereas the "on" keyword in merge takes a column. Alternatively, you could remove Symbol from the indexes and then join the dataframes by the Date indexes.</p> <pre><code>FSample.reset_index("Symbol").join(GMSample.reset_index("Symbol"), lsuffix="_x", rsuffix="_y")...
pandas
1
364,924
49,583,327
Can't install Go Tensorflow
<p>I'm trying to install Tensorflow Go on a Linux Ubuntu machine.</p> <p>I have done the first 3 steps in the <a href="https://www.tensorflow.org/versions/master/install/install_go" rel="nofollow noreferrer">Installation guide</a> and am currently at step 4. </p> <p>Everything above 4) works, but I couldn't run "go g...
<p>You need to install the <a href="https://www.tensorflow.org/install/lang_c" rel="nofollow noreferrer">C library</a> first ! </p> <p>Look at the doc :</p> <p><a href="https://i.stack.imgur.com/fMzE4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fMzE4.png" alt="enter image description here"></a>...
linux|ubuntu|go|tensorflow
0
364,925
49,521,882
Reducing redundant index in pandas dataframe
<p>I have a dataframe <code>q</code> that is indexed by drug and dosage form. I noticed that the dataframe shows the same index <code>plavix</code> in two different positions when the dataframe is not sorted. I was able to fix this issue by adding <code>.sort_index()</code> to the end of <code>q</code> (see Output 1)....
<p>For output 1, you'll need a simple <code>sort_index</code>.</p> <pre><code>q.sort_index(level=0, ascending=False) app_num warfarin inj 2 plavix tab 1 tab 4 cap 3 </code></pre> <p>For output 2, you'll need to append an extra level before sorting the ind...
python|pandas
2
364,926
49,478,545
Selecting rows with lowest values based on combination two columns from pandas
<p>I'm not even sure if the title makes sense.</p> <p>I have a pandas dataframe with 3 columns: x, y, time. There are a few thousand rows. Example below:</p> <pre><code> x y time 0 225 0 20.295270 1 225 1 21.134015 2 225 2 21.382298 3 225 3 20.704367 4 225 4 ...
<p>So need remove rows with <code>time</code> equal first by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> and then use your solution:</p> <pre><code>df = df[df['time'] != 0] df2 = df.loc[df.groupby("y")["time"].idxmin()...
python|pandas|min|pandas-groupby
2
364,927
49,510,143
TensorFlow is returning an error when used in Laravel project, why?
<p>I run this command from bash (in my case zsh)</p> <p><code>python images/classify_image.py --image_file images/new_name.jpg</code></p> <p>And I am getting the correct output which is:</p> <pre><code>power drill (score = 0.97464) hand blower, blow dryer, blow drier, hair dryer, hair drier (score = 0.00101) carpent...
<p>This is not an issue with Laravel. Can you run the command using exec()? Im guessing its a path issue. Process accepts a third parameter for env vars.</p> <p>See if this helps:</p> <pre><code>$command = 'python images/classify_image.py --image_file images/new_name.jpg'; $cwd = null; $envVars = [ 'HOME' =&gt; getEn...
php|python|laravel|shell|tensorflow
1
364,928
49,493,720
Merging/Combining Dataframes in Pandas
<p>I have a df1, example:</p> <pre><code> B A C B 1 A 1 C 2 </code></pre> <p>,and a df2, example:</p> <pre><code> C E D C 2 3 E 1 D 2 </code></pre> <p>The column and row 'C' is common in both dataframes. </p> <p>I would like to combine these datafr...
<p>There is problem <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow noreferrer"><code>combine_first</code></a> always sorted columns namd index, so need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="no...
python|pandas|dataframe|append|concatenation
2
364,929
49,534,421
set_model() missing 1 required positional argument: 'model'
<p>I'm have created a Keras Sequential Model and am using Adam optimizer. I wished to get the learning rate after every epoch. This <a href="https://stackoverflow.com/questions/47490834/how-can-i-print-the-learning-rate-at-each-epoch-with-adam-optimizer-in-keras">stackoverflow question</a> seem to answer my question. H...
<p>Actually, in the model.fit_generator method's callbacks parameter, you are passing the class instead of an object of that class. </p> <p>It should be</p> <pre><code>my_calback_object = MyCallback() # create an object of the MyCallback class model.fit_generator(datagen.flow(x_train, y_train, batch_size=75), ...
python|tensorflow|deep-learning|keras
44
364,930
49,475,217
Plot the two matrices as colormaps on the same graph
<p>I have two numpy multi dimmensional matrices that have five features each like this</p> <pre><code> array1 = array([ 1. , 0.97572023, 0.97671645, 0.99772446, 0.99326534, 0.94841498]....) array2 = array([ 0.97572023, 1. , 0.99343976, 0.9844228 , 0.9880037 , 0.96203135]....) </code></pre> <...
<p>Instructing matplotlib to use specific ticks for the <code>imshow</code> plot ensures that labels appear in the right places,</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from matplotlib import cm as cm # Generate some data for the sake of example array = np.random.uniform(0, 1, (5, 5)) ...
python|numpy|matplotlib
2
364,931
49,596,373
finding first instance of condition in all the groups using groupby in pandas
<p>I am trying to find the first instance of a condition getting satisfied in each group and then merge different groups together. Here in the below data, I want the first instance in a separate column as <code>True</code> when 'putbuy' column turns 1 from 0 for every month in the data, which is from 1994-2018.</p> <p...
<p>IIUC, you can use <code>idxmax</code> to find the index of first occurance of the maximum value of 'putbuy':</p> <pre><code>df.loc[df.groupby(['year_x','month_x'])['putbuy'].idxmax(),'DO'] = 1 df['DO'] = df.DO.fillna(0).astype(int) print(df) </code></pre> <p>Output:</p> <pre><code> month_x year_x day_x p...
python|pandas|loops|pandas-groupby
3
364,932
49,349,096
Python performance iterating through lists, numpy arrays
<p>I am working on a project where I have to loop through large arrays (lists), accessing each item by index. Usually this involves checking each element against a condition, and thereafter potentially updating its value. </p> <p>I've noticed that this is extremely slow compared to, for example, doing a similar thing ...
<p>If you are using <code>numpy</code> you should use the <code>numpy</code> array type and then take advantage of <code>numpy</code> functions and broadcasting:</p> <p>If your specific need is to assign <code>1.0</code> to all elements, there is a specific function for that in <code>numpy</code>:</p> <pre><code>impo...
python|numpy|anaconda
0
364,933
49,673,654
How to create matrix containing fraction numbers in numpy
<p>I would like to make matrix which contains fraction numbers, say 1/4, as elements.</p> <p>I made following matrix:</p> <pre><code>import numpy as np alpha = 10 B = np.array([ [0, -0.25, -1/20, alpha/40], [1/(alpha+3), 0, -1/(alpha+3), -(alpha-1)/(alpha+3) ], [ 1/(2*alpha+2), 1/(alpha+1), 0, 1/(10*alpha+10) ], [ -...
<p>Apparently some thing was done wrongly. However,</p> <pre><code>B = np.array([ [0, -1/4, -1/20, alpha/40], [1/(alpha+3), 0, -1/(alpha+3), -(alpha-1)/(alpha+3) ], [ 1/(2*alpha+2), 1/(alpha+1), 0, 1/(10*alpha+10) ], [ -1/2, -9/20, 0, 0 ] ]) print(B) </code></pre> <p>gives valid output now.</p>
python|numpy|matrix
0
364,934
49,608,953
Double requirement given when trying to use pip install pandas
<p>I want to build a Docker container using a Dockerfile containing <code>pip install -r requirements.txt</code>. pandas==0.22.0 is included in this requirements.txt file. Untill two days ago, the Docker container was perfectly build. Starting from yesterday, I receive an error:</p> <blockquote> <p>Double requiremen...
<p>I finally found the solution for this in case of python3 or pip3</p> <pre class="lang-sh prettyprint-override"><code>pip3 install pandas --no-build-isolation </code></pre>
python|pandas|docker|pip
8
364,935
49,729,340
Installing numpy, cython, cpython for Python 2.7.12
<p>I have been trying to install numpy for Python 2.7.12 on a ubuntu 16.04 machine, but am not sure I am doing the right thing.</p> <p>I issued the command </p> <p><code>python setup.py install</code></p> <p>and received the following error message:</p> <pre><code>ImportError: No module named Cython.Compiler.Main <...
<p>You can check if <code>pip</code> is install thanks to the command <code>which pip</code>, in my case : </p> <pre><code>$ which pip /home/usr1/anaconda3/bin/pip </code></pre> <p>If <code>pip</code> is not install install it : <a href="https://pip.pypa.io/en/stable/installing/" rel="nofollow noreferrer">instructio...
python|numpy|cython|cpython
2
364,936
49,442,670
My process being killed the moment it start training, tensorflow object detection
<p>I am trying to train image detector using my own dataset but it fails. I've made few changes in configuration file apart from number of classes and paths. Here are they</p> <pre><code>train_input_reader: { tf_record_input_reader { input_path: "data/data_train.record" } label_map_path: "data/rdata_train.pb...
<p>In my case, it was the CPU RAM that was out of memory. I train my network using GPU, but strangely, when I retrain it with load_weights, it killed.</p> <p>Increase CPU RAM fixed my problem.</p>
python-3.x|tensorflow|machine-learning|neural-network|object-detection
0
364,937
28,327,123
Installing Anaconda Python, pyhdf, and netcdf4 for windows 64 bit
<p>I am pretty new to python and programming , all self taught. I started a new position late last year requiring me to create and maintain large scientific data sets. A big hurdle was learning to install the pyhdf and netcdf4 modules for 64 bit python 2.7 on windows. Here is how to do that. </p>
<p><strong>NEW CONDENSED VERSION ----- JUNE 2016</strong></p> <p>I have learned more since I wrote this question. Anaconda makes everything except pyhdf (to my knowledge) easier.</p> <p><strong>1. Anaconda</strong></p> <p>Download Anaconda 2.7 windows 64 bit from <a href="http://continuum.io/downloads" rel="nofollo...
python|numpy|module|netcdf|pyhdf
5
364,938
28,177,114
Merge/Join 2 DataFrames by complex criteria
<p>I have 2 large datasets (large in terms of 70K to 110K each). I want to correlate/compare both and find which items from set2 can be found in set1 based on some conditions/criteria.</p> <p>My current strategy is to sort both lists by common fields and then run nested <code>for</code> loops, perform conditional <cod...
<p>pandas currently lacks direct support for "nearby" queries, though I have a <a href="https://github.com/pydata/pandas/pull/9258" rel="noreferrer">pull request</a> up to add some basic functionality (not enough for your use-case).</p> <p>Fortunately, the scientific Python ecosystem gives you the tools you need to do...
python|pandas|scipy|scikit-learn|dataframe
8
364,939
28,318,722
pandas read_sql drops dot in column names
<p>is that a bug or I'm doing specifically something wrong ? I create a df, put it in a sql table, df and table have a column with a dot in it. now when I read the df from the sql table, column names aren't the same. I wrote this little piece of code so that people can test it.</p> <pre><code>import sqlalchemy import ...
<p>Solution is to pass <code>sqlite_raw_colnames=True</code> to your engine</p> <pre><code>In [141]: engine = sqlalchemy.create_engine('sqlite:///', execution_options={'sqlite_raw_colnames':True}) In [142]: dfin.to_sql('testtable', engine, if_exists='fail') In [143]: pd.read_sql("SELECT * FROM testtable", engine).he...
python|pandas
4
364,940
28,150,707
Python find root for non-zero level
<p>Say I have the following code</p> <pre><code>def myfunc(x): return monsterMathExpressionOf(x) </code></pre> <p>and I would like to find numerically the solution of <code>myfunc(x) == y</code> for diverse values of <code>y</code>. If <code>y == 0</code> then there are a lot of root finding procedures available,...
<p>You don't have to redefine a function for every value of <code>y</code>: just define a single function of <code>y</code> that returns a function of <code>x</code>, and use that function inside your loop:</p> <pre><code>def wrapper(y): def myfunc(x): return monsterMathExpressionOf(x) - y return myfun...
python|numpy|scipy|solver
2
364,941
27,996,785
Python MatPlotlib barchart- Resize width
<p>I have written a code to plot a horizontal bar chart using python's matplotlib library.</p> <p>My goal is to resize the width of the bar chart, but the distance from origin must remain the same, which is 5.6. In short words, my intention is to trim the size in terms of width, keeping the length same. I could not fi...
<p>I have plotted 3 bar charts, and the issue is resolved. </p> <pre><code>import matplotlib.pyplot as plt;plt.rcdefaults() from numpy.random import rand from numpy import arange import numpy as np def libra_execution_time(): data = np.genfromtxt('C:\\programming\\Python27\\libra_graphs\\File\\histogram.csv',deli...
python|numpy|matplotlib
-1
364,942
28,081,247
Print real roots only in numpy
<p>I have something like this:</p> <pre><code>coefs = [28, -36, 50, -22] print(numpy.roots(coefs)) </code></pre> <p>Of course the result is:</p> <pre><code>[ 0.35770550+1.11792657j 0.35770550-1.11792657j 0.57030329+0.j ] </code></pre> <p>However, by using this method, how do I get it only to print the real roots ...
<p>Do NOT use <code>.iscomplex()</code> or <code>.isreal()</code>, because <code>roots()</code> is a numerical algorithm, and it returns the numerical approximation of the actual roots of the polynomial. This can lead to spurious imaginary parts, that are interpreted by the above methods as solutions.</p> <p>Example:<...
python|python-3.x|numpy
31
364,943
28,154,448
Efficiently grouping the rows of a Pandas DataFrame by the value of a column?
<p>I have a Pandas DataFrame <code>df</code>, with two columns <code>A</code> and <code>B</code>. <code>A</code> is also the index.</p> <p><code>B</code> has a very small range of permissible values (in my case, <code>B</code> is a boolean). How do I quickly answer the query: "all rows in <code>df</code> for which the...
<p>Here is an example using <a href="http://www.gregreda.com/2013/10/26/intro-to-pandas-data-structures/" rel="nofollow">http://www.gregreda.com/2013/10/26/intro-to-pandas-data-structures/</a> also I recommend you going over that tutorial along with the pandas documentation.</p> <pre><code>&gt;&gt;&gt; data = {'year':...
python|pandas
1
364,944
28,122,488
Fast way to compute if statements on arrays in python?
<p>Assume three numpy arrays x, y and z</p> <pre><code> z = (x**2)/ y for each x &gt; 2 y z = (x**2)/y**(3/2) for each x &gt; 3 y z = (1/x)*sin(x) for each x &gt; 4 y </code></pre> <p>The array x, y and z are of-course made up but they illustrate the point of operating multiple if stat...
<p>I'm not quite sure if you are looking to have your z array be the same size as x or y, but I will assume so.</p> <p>Numpy has a function that can find the indices of elements based on a condition. In the example below I am doing a calculation similar to what your first line does.</p> <pre><code>import numpy as np ...
python|arrays|numpy
2
364,945
28,305,678
Trouble with least squares in Python
<p>I am working on a project analyzing data and am trying to use a least squares method (built-in) to do so. I found a tutorial that provided code as an example and it works fine:</p> <pre><code>x = arange(0, 6e-2, 6e-2/30) A, k, theta = 10, 1.0/3e-2, pi/6 y_true = A*sin(2*pi*k*x+theta) y_meas = y_true+2*random.randn(...
<p>Three things are happening in the line you called <code>#Point of error</code>: You are multiplying values, adding values and applying the <code>sin()</code> function. "Unsupported operand type" means something is wrong in one of these operations. It means you need to verify the types of the operands, and also ma...
python|numpy|least-squares
2
364,946
73,401,471
Values changed after converting object type column to string column type Python
<p>I have two columns in my pandas dataframe</p> <pre><code>Current selling price New selling price 0.0374 0.03927 0.1154 0.12117 0.0424 0.04452 0.1154 0.12117 0.1062 0.11151 0.035 ...
<p>It is precision float problem, you can try round values:</p> <pre><code>df['New selling price'] = df['New selling price'].astype(float).round(5).astype('string') </code></pre>
python-3.x|pandas|dataframe|python-3.9
1
364,947
73,299,300
pd.scatter_matrix not working on pandas version 1.4.2
<p>Here is my code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split fruits = pd.read_table('readonly/fruit_data_with_colors.txt') from matplotlib import cm X = fruits[['height', 'width', 'mass', 'color_score']] y = fruits['fru...
<p>I guess it has now changed to <code>pandas.plotting.scatter_matrix</code></p> <p><br>Have a look at the document below. <br> <a href="https://pandas.pydata.org/docs/reference/api/pandas.plotting.scatter_matrix.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.plotting.scatter_matrix...
pandas|scatter-matrix
0
364,948
73,239,995
How do I make z score algorithms work? Where am I going wrong?
<p>I have been having some trouble with my code, about how to use the Kaggle database to find the popularity of data, and analyze it using Z-score algorithms. I have tried a lot, but can never seem to get my code to work. Here is the link to the data: <a href="https://docs.google.com/spreadsheets/d/1HIAzQta-dSfoovkdPeq...
<p>You have written:</p> <pre><code>crab = 0 # ... # ... crab = np.std(crab) # ... # ... k = (k - average) / crab # You are dividing by zero </code></pre> <p>Hence the infinty in the output</p>
python|pandas|numpy
0
364,949
73,278,431
Filtering values of an array using pixel positions from an image
<p>I have a image in greyscale. I have the value of each pixel saved to a text document that I pre-processed and loaded as an array, therefore my array has size 110529.</p> <p>An example of how my array looks like:</p> <pre><code>import numpy as np my_array = np.random.randint(low=18., high=36,size=(110592)) </code></p...
<p>what you wanted is not called &quot;filtering&quot; but a <a href="https://www.google.com/search?q=numpy+slice" rel="nofollow noreferrer">&quot;numpy slice&quot;</a>:</p> <pre><code>x, y, w, h = cv2.selectROI(my_frame) roi = my_frame[y:y+h, x:x+w] </code></pre>
python|numpy
1
364,950
73,315,409
Creating a DateTime column from seperate time and date columns
<p>So I have this :</p> <pre><code>df=pd.read_csv('file.csv') df time date 0 21:11:07 2022-08-04 1 21:11:12 2022-08-04 2 21:11:27 2022-08-04 </code></pre> <p>and I want to turn it into this:</p> <pre><code> datetime time date 0 2022-08-04 21:11:07 21:11:07 2...
<p>Remove <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pop.html" rel="nofollow noreferrer"><code>DataFrame.pop</code></a> which drop columns - new column is created like last column:</p> <pre><code>df['datetime'] = pd.to_datetime(df['date']) + pd.to_timedelta(df['time']) #df['date...
python|pandas|dataframe|datetime
1
364,951
73,385,095
Dataframes to Excel file (multiple sheets) per unique value
<p>I have three different dataframes which all contain a column with certain IDs.</p> <p>DF_1</p> <p><a href="https://i.stack.imgur.com/geHMn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/geHMn.png" alt="DF_1" /></a></p> <p>DF_2</p> <p><a href="https://i.stack.imgur.com/8aWQQ.png" rel="nofollow nor...
<p>Can you try the following:</p> <pre><code>unique_ids = df_1['ID'].unique() for name in unique_ids: writer = pd.ExcelWriter(f'{name}.xlsx') r1 = df_1[df_1['ID'].eq(name)] r1.to_excel(writer, sheet_name=f'{name}_df1') r2 = df_2[df_2['ID'].eq(name)] r2.to_excel(writer, sheet_name=f'{name}_df2') ...
python|excel|pandas
2
364,952
73,266,066
Merging a column from one dataframe to another in which only one index column has to be used in pandas
<p>I have two data frames that look like this, <code>data_df</code> is</p> <pre><code> Amplitude (V) Noise (V) Rise time (s) ... n_trigger signal_name ... 0 reference_trigger 0.123044 0.001194 3.394432e-10 ... DU...
<p>Try this:</p> <pre><code>data_df = data_df.assign(accepted=filter_df['accepted']) </code></pre>
python|pandas|indexing|multi-index
1
364,953
73,489,967
Converting the available pandas Dataframe presently across monthly into quarterly values
<p>This is my available df, it contains year from 2016 to 2020</p> <pre><code>Year Month Bill ----------------- 2016 1 2 2016 2 5 2016 3 10 2016 4 2 2016 5 4 2016 6 9 2016 7 7 2016 8 8 2016 9 9 2016 10 5 2016 11 1 2016 12 3 . . . 2020 12 10 </co...
<p>You can try:</p> <pre><code>df['levels'] = 'Q' + df['Month'].div(3).apply(math.ceil).astype(str) df['contribution'] = df.groupby(['Year', 'levels'])['Bill'].transform('mean') </code></pre>
python|pandas|dataframe|time-series
0
364,954
73,501,925
Python Pandas Flag for min max Values
<p>I have a dataframe which looks like this:</p> <pre><code>import pandas as pd d = {'Para1': ['Para1_1', 'Para1_1', 'Para1_2', 'Para1_2'], 'Para2': ['Para2_1', 'Para2_1', 'Para2_2', 'Para2_2'], 'ParaN': ['ParaN_1', 'ParaN_1', 'ParaN_2', 'ParaN_2'],'value':[0.5,0.3,0.01,0.5]} df=pd.DataFrame(data=d) print (df) ...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html" rel="noreferrer"><code>.replace</code></a>:</p> <pre class="lang-py prettyprint-override"><code>params = ['Para1', 'Para2', 'ParaN'] df['minmaxflag'] = df.groupby(params)['value'].transform(lambda s: s.replace({s.min():...
python|pandas
5
364,955
73,182,976
Get excel data in order using python
<p>I'm using python to get a list functions from the excel in order. <a href="https://i.stack.imgur.com/KdWo3.png" rel="nofollow noreferrer">Excel image</a></p> <p>I want to get result like that</p> <pre><code>Login Submit forgot password Delete (Submitted) Next&gt;confirm save cancel upload delete ... </code></pre> <p...
<p>IIUC, use <code>bfill</code> and <code>dropna</code>:</p> <pre><code>df = (pd.read_excel(fileNameMatrix,sheet_name='doTestCase', header=None) .bfill(axis=1)[0].dropna()) print(df) # Output 0 Login 1 Submit 2 forgot password 5 delete 6 (submitted) 8 ...
python|excel|pandas
1
364,956
73,240,994
how to sort the values in the dataframes
<p>My dataframe:</p> <p><a href="https://i.stack.imgur.com/SnCzS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SnCzS.png" alt="enter image description here" /></a></p> <p>How to sort the values like the final sorts? I don't know how to finish it by pandas.</p>
<p>What you are really looking to do is concatenate columns A and B to get your number. An easy way to do this is to convert it to a string, add them together, and then convert it back to an integer.</p> <pre><code>#creating dataframe data = dict( A=[1, 2, 3, 4, 5, 6], B=[6, 5, 4, 2, 1, 3], values=[&quot;a&quot;, &quot...
pandas
0
364,957
73,520,561
appending monthly data to dataframe between two dates (multiple entries)
<p>I have two dataframes: one containing replenishment orders for some products, and one containing sales data for the same products by month over multiple years. I have only included the entries for one specific product here. I have already used groupby to calculate the average sales per month per product from the sal...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code># if products[&quot;Date&quot;] isn't already converted, convert it: products[&quot;Date&quot;] = pd.to_datetime(products[&quot;Date&quot;]) min_date = products[&quot;Date&quot;].min() max_date = products[&quot;Date&quot;].max() tmp = pd.DataFrame({&quot;Dat...
python|pandas|loops|datetime|append
1
364,958
73,182,363
Split and store dataframe but name based on unique values in specific cols
<p>I have a dataframe like as below</p> <pre><code>data = pd.DataFrame({'email_id': ['abc@gmail.com;test1@gmail.com','abc@gmail.com;def@yahoo.com','abdc@gmail.com','ache@gmail.com','aqce@gmail.com','pqr@gmail.com','pqr@gmail.com'], 'Dept_id': [21,23,25,26,28,29,31], 'dept_name':['Science','Che...
<p>IIUC, you can use:</p> <pre><code>for k, v in data.groupby(['email_id']): dept_unique_ids = '_'.join(v['Dept_id'].astype(str).unique()) dept_unique_names = '_'.join(v['dept_name'].unique()) location_unique = '_'.join(v['location'].unique()) filename = '_'.join([dept_unique_ids, dept_unique_names, loc...
python|pandas|list|dataframe|group-by
1
364,959
73,363,045
TypeError: dtype datetime64[ns] cannot be converted to timedelta64[ns]
<p>I have a column of years from the <a href="https://datasets.datadrivendiscovery.org/d3m/datasets/-/tree/266c67f2b9e9f8494fc1e4d0e3c137626354b084/56_sunspots/56_sunspots_dataset/tables" rel="nofollow noreferrer">sunspots dataset</a>.</p> <p>I want to convert column 'year' in integer e.g. 1992 to datetime format then ...
<p><code>pandas.Timedelta</code> <a href="https://pandas.pydata.org/docs/reference/api/pandas.Timedelta.html" rel="nofollow noreferrer">&quot;[r]epresents a duration, the difference between two dates or times.&quot;</a> So you're trying to get Python to tell you the difference between a particular datetime and...nothin...
pandas|datetime|timedelta
0
364,960
73,296,508
Create new column with 7th business day of the month based on year and month columns
<p>I have a dataframe with two columns, the year and month of another variable which I left out for simplicity. It looks like this:</p> <pre class="lang-py prettyprint-override"><code> YearOfSRC MonthNumberOfSRC 0 2022 3 1 2022 4 2 2022 5 3 2022 6 4 ...
<p>If I understand correctly, you can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pandas.to_datetime</code></a> to convert to datetime, then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.tseries.offsets.BusinessDay.html"...
python|pandas|datetime|group-by|apply
2
364,961
73,315,889
while running this my code I encountered error: argument must be a string, a bytes-like object or a number, not 'tuple'
<pre><code>#print('[*] define model ... ') #nw, nh, nz = X_train.shape[1:] nw = X_train.shape[1:] print(nw) nh = X_train.shape[1:] print(nh) nz = X_train.shape[1:] print(nz) # define placeholders t_image_good = tf.placeholder('float32', [batch_size, nw, nh, nz], name='good_image') t_image_good_samples = tf.placeholde...
<p>I'm not sure what you're trying to do with those <code>nw</code>, <code>nh</code>, <code>nz</code>. Let's take one, for example:</p> <pre><code>nw = X_train.shape[1:] </code></pre> <p>It is giving you error because it expects a single number when you use them in the code below, for example here <code>[batch_size, nw...
python|tensorflow|deep-learning|google-colaboratory|training
0
364,962
73,439,319
Pandas conditional formatting based on comparison from different columns
<p>I have a large dataframe that comes from calculation with varying number of columns and rows:</p> <pre><code>+------+------+------+-----+-------+----+----+----+----+ | col1 | col2 | col3 | ... | col50 | A1 | B1 | C1 | D1 | +------+------+------+-----+-------+----+----+----+----+ | 2 | 1 | 7 | | 0 | ...
<p>You can use:</p> <pre><code># get last row and keep non NA s = df.iloc[-1].dropna() # get reference columns ref = df[s] # get sign of difference m = np.sign(df[s.index] .where(ref.notna().values) .astype(float) .sub(ref.values, axis=0) ) # define colors from sign of ...
python|pandas|numpy
2
364,963
73,224,550
How to Calculate Dropoff by Unique Field in Pandas DataFrame with Duplicates
<pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df = pd.DataFrame({ 'user' : ['A', 'A', 'B', 'B', 'B', 'C', 'C'], 'step_1' : [True, True, True, True, True, True, True], 'step_2' : [True, False, False, True, False, True, True], 'step_3' : [False, False, False, False, False,...
<p>In your case you can do</p> <pre><code>df.groupby('user').any().mean() Out[11]: step_1 1.000000 step_2 1.000000 step_3 0.333333 dtype: float64 </code></pre>
python|pandas|dataframe
1
364,964
73,210,923
Join columns with empty values in csv, Python
<p>I am joining 2 columns from a csv file and the columns look like this:</p> <p><a href="https://i.stack.imgur.com/LpKJ7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LpKJ7.png" alt="image" /></a></p> <p>I need to join them in a new column and make them look like this:</p> <p><a href="https://i.st...
<p>assuming the column1 has null values. below should move the values in the right columns to the left when value in left is null</p> <p>Can you also post the csv or dataframe, to help reproduce?</p> <pre><code>df.fillna(axis=1) </code></pre>
python|pandas|dataframe
0
364,965
73,481,896
pandas insert many new columns from existing columns raises "highly fragmented warning"
<p>My code is like this:</p> <pre class="lang-py prettyprint-override"><code>df.columns = ['cpu_0', 'cpu_1', 'cpu_2', 'cpu_3'..., 'cpu_47'] for i in range(48): df['new_cpu_{}'.format(i)] = df['cpu_{}'.format(i)] * 100 </code></pre> <p>There are about 180k rows in the dataframe, my code raised warning below:</p> <bl...
<p>You don't need a loop here.</p> <p>Use vectorial code:</p> <pre><code>df = pd.concat([df, df.mul(100).add_prefix('new_')], axis=1) </code></pre>
python|pandas
2
364,966
73,408,200
Replace duplicate value in dataframe row with NaN
<p>I have a dataframe which looks something like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>index</th> <th>c1</th> <th>c2</th> <th>c3</th> <th>m1</th> <th>m2</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>a</td> <td>b</td> <td>c</td> <td>a</td> <td>c</td> </tr> <tr> <td>2</td> <...
<p>You can use numpy to perform broadcasting comparison:</p> <pre><code># get &quot;c&quot; columns (you can use another method) # and convert to numpy array c = df.filter(regex='^c').to_numpy() # get &quot;m&quot; columns (you can use another method) m = df.filter(regex='^m') # mask values in &quot;m&quot; that are a...
python|pandas
2
364,967
73,461,720
How to remove rows from numpy array if certain number of an element is present
<p>I have a 2d numpy array that contains some numbers like:</p> <pre><code>data = [[1.1, 1.2, 1.3, 1.4], [2.1, 2.2, 2.3, -1.0], [-1.0, 3.2, 3.3, -1.0], [-1.0, -1.0. -1.0, -1.0]] </code></pre> <p>I want to remove every row that contains the value <code>-1.0</code> 2 or more times, so I'm left with</p> <pre><code>data =...
<p>You can easily do it with this piece of code:</p> <pre><code>new_data = data[(data == -1).sum(axis=1) &lt; 2] </code></pre> <p>Result:</p> <pre><code>&gt;&gt;&gt; new_data array([[ 1.1, 1.2, 1.3, 1.4], [ 2.1, 2.2, 2.3, -1. ]]) </code></pre>
python|arrays|numpy|numpy-ndarray
1
364,968
73,184,467
how to show the number of records from the first day to the last day in pandas
<p>I want to show the number of records from the first day to the last day in pandas.</p> <p>I have an dataframe like this:</p> <pre><code> day category value 0 2022-07-01 A 1 1 2022-07-01 B 2 2 2022-07-03 A 3 3 2022-07-05 A 4 4 2022-07-07 B 5 5...
<p>You can do <code>pd.crosstab</code> then <code>resample</code></p> <pre><code>#df.day = pd.to_datetime(df.day) out = pd.crosstab(df.day,df.category).resample('1D').first().fillna(0).reset_index() Out[607]: category day A B 0 2022-07-01 1.0 1.0 1 2022-07-02 0.0 0.0 2 2022-07-03...
python|pandas
1
364,969
73,192,501
Create new column based on values in each row in another column
<p>I was wondering if someone would be able to help me with the following. I have this dataframe:</p> <pre><code>df = {'Price': [60.50,5.20,7,20.16,73.50,12.55,8.70,6,54.10,89.40,12,55.50,6,120,13.20], 'Discount': [1,1,1,0.5,0.4,1,0.3,0.2,1,1,1,1,1,0.1,0.9]} df = pd.DataFrame(data=df) </code></pre> <p>What I am ...
<p>Your mistake is, that you are manipulationg the full dataframe when calling e.g.</p> <pre><code>df['Amount off'] = 0 </code></pre> <p>Thus after executing this line the total column is <code>0</code>. Dependent on the last row you will end up with either only <code>0</code> or <code>df['Price']*df['Discount']</code...
python|pandas
2
364,970
73,364,194
how to find amount of users when one user could had chosen many options?
<p><img src="https://i.stack.imgur.com/OB1nR.png" alt="Being given this table " /></p> <p>i have to answer two questions:</p> <ol> <li>How many is there users of SQL?</li> <li>How many of the users are using MySQL <strong>only</strong><br /> The hard part of this is that any respodent could had chosen many options, so ...
<p>How I would approach the problem (there might be betters ways)</p> <ol> <li>Since you want SQL users I assume it just means any user who has atleast chosen any one SQL variant. You can just use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.contains.html#pandas.Series.str.contains" rel="...
python|pandas|data-analysis|exploratory-data-analysis
0
364,971
73,299,197
Replicate a function from pandas into pyspark
<p>I am trying to execute the same function on a spark dataframe rather than pandas.</p> <pre><code>def check_value(df): lista=[] for index,value in enumerate(df.columns): lista.append('Column name: db_transactions/{} has {} % of white_space charachter and {} nullvalues'.format(df.columns[index],sum(lis...
<p>A direct translation would require you to do multiple <code>collect</code> for each column calculation. I suggest you do all calculations for columns in the dataframe as a single row and then collect that row. Here's an example.</p> <pre class="lang-py prettyprint-override"><code># input dataframe, say `data_sdf` # ...
python|pandas|apache-spark|pyspark
1
364,972
73,499,883
If a condition is met then add to the previous row elseif subtract from the previous row in python
<p>I'm working on a problem where if certain conditions are met then I need to add or subtract from the previous row. So I have the following df:</p> <pre class="lang-py prettyprint-override"><code>data = {'sample_val':[5.5, 6.2 , 4.0, 7.8, 3.6], 'sample_lab':['nor','high','nor','high','low']} df=pd.DataFrame(data) </c...
<p>If I understood correctly, you can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>np.select</code></a> to know which coefficients you must add or subtract, and then accumulate the result to the initial value of <code>10</code> using panda's <a href="h...
python|pandas|dataframe|numpy|if-statement
1
364,973
73,383,156
How to get the last/maximum date that is on/earlier than another baseline date by user?
<p>I have a df where I am trying to create the Last Login Date column, as shown in the image.</p> <p>I am not sure how to get the <strong>maximum login date that was on/prior the email notification date for that current row</strong>. I added explanations on how I expect the data to look. Any help is appreciated in eith...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>pandas.merge_asof</code></a>:</p> <pre><code>out pd.merge_asof(df.assign(date=pd.to_datetime(df['email_notification_date']).sort_values()), pd.to_datetime(df['login_date']).dropna().sort_va...
sql|pandas|amazon-redshift
0
364,974
73,430,859
How to agglomerate rows/lines in Python Pandas, based on one reference column?
<p>Let's say we have a DataFrame like this in Pandas:</p> <pre><code> 0 1 2 3 4 0 Date Description ABC DEF 1 LOREM ISPUM...
<p>For the date rows i.e. rows from 2 to end (<code>df.iloc[2:]</code>) do <code>ffill</code> on '0' column and <code>groupby</code> and <code>agg</code> using <code>' '.join</code>, but because some dates may repeat, use a <code>cumcount</code> of the groups to identify each group and use both columns '0' and 'column ...
python|pandas|row|cell
1
364,975
73,392,264
Add new column with last month sales avg groupby machine_id and item_id
<pre><code>data = {'machine_id': [1000,1000,3000,2000,3000,1000,1000,3000,2000,3000,1000,1000,3000,2000,3000,1000,2000], 'item_id': [100,100,100,200,300,100,100,100,200,300,100,100,100,200,300,100,200], 'Date': ['2022-03-01','2022-03-02','2022-03-03','2022-03-04','2022-03-05', '2022-04-01','2022-04-02','20...
<p>Between different month groups - the <strong>values of the same <em>day</em> will be aligned with each other</strong> - regardless of the differences in their number and order.</p> <p><strong>Requirement:</strong> days must be <strong>unique</strong> within each month.</p> <p>I am using my approach from this questio...
python|pandas|dataframe
2
364,976
73,422,651
Issue with returning sum of indexes of sliced list using Indexslice / .loc on a Dataframe
<p>Have been struggling with this for some time. I have the following multi-indexed by column Dataframe:</p> <pre><code>startd = pd.to_datetime('2022-06-01').date() endd = pd.to_datetime('2022-08-01').date() SW_NWE = ('NWE','MED') df_SW_NWE = df.loc[startd:endd, idx['Sweet',SW_NWE]].cumsum(axis=1).round() </code></p...
<p>You can try the <code>stack()</code> + (do something) + <code>unstack()</code> trick to sum the columns.</p> <p><code>stack()</code> lets you reshape the wide df into a long one so that you can <code>sum()</code> the data by week; this creates a Series. After it's done, convert it into a frame by calling <code>to_fr...
python|pandas|dataframe|slice|pandas-loc
1
364,977
73,352,892
Unable to find frames from the numpy array
<p>Currently working on the dataset which is in <code>.mat</code> file format. In order to get the frames, I have converted the video into numpy array using <code>loadmat</code> function. Not able to figure out how to find frames from the given numpy array?</p> <p>The output of the file after loadmat function is as fol...
<p>I appears as though the frames are part of the &quot;vid&quot; key in the dict which i labelled <code>x</code> in the example.</p> <p>I presume that array was a <code>numpy array</code>.</p> <p>So it looks like this:</p> <pre class="lang-py prettyprint-override"><code>from numpy import * x = {'siz': array([[60., 80...
python|numpy
1
364,978
73,250,537
Concat dataframes from dictionary
<p>I have a dictionary where each key contains a dataframe column with a daterange. How can I concat all of the dictionary keys together so that I can have one dataframe with all of the columns together?</p> <p>Example:</p> <pre><code>A: apples 2020-01-01 2 2020-01-02 3 2020-01-03 4 2...
<p>This would do the trick:</p> <pre><code>pd.concat(dict.values(), axis=1) </code></pre> <p>pd.concat is a fuction from pandas which adds dataframes together.</p> <p>Axis = 1 tells the function that you want to add the columns.</p>
python|pandas|dataframe
0
364,979
73,450,599
What is the equivalent of SPLIT-APPLY-COMBINE in PostgreSQL
<h1>TLDR;</h1> <p>What is the equivalent of the following Python code snippet in PostgreSQL?</p> <pre class="lang-py prettyprint-override"><code>df.groupby('column').apply(function) </code></pre> <p>Where <code>df</code> is a Pandas DataFrame instance.</p> <h1>Context</h1> <p>I am used to the <a href="https://pandas.py...
<p>Do not give up on SQL quite so quickly. <br/> If I understand correctly you want to to copy to another table then delete those rows which have the same measurement by place and time. So for Place A move then delete the rows with times <code>00:30:00 and 00:40:00</code>. This is because those are the same as time st...
pandas|postgresql
0
364,980
73,327,737
Why does numpy reshape mess up my data pattern?
<p>Let's say I have the following array A -</p> <pre><code>import numpy as np batch_size, seq_len = 3, 5 A = np.zeros((batch_size, seq_len)) A[0,0:] = 1 A[1,0:] = 2 A[2,0:] = 3 </code></pre> <p>A has the following value -</p> <pre><code>array([[1., 1., 1., 1., 1.], [2., 2., 2., 2., 2.], [3., 3., 3., 3., 3...
<p>From the <code>np.reshape</code> docs</p> <blockquote> <p>You can think of reshaping as first raveling the array (using the given index order), then inserting the elements from the raveled array into the new array using the same kind of index ordering as was used for the raveling.</p> </blockquote> <p><code>a4</code...
numpy
1
364,981
73,433,560
increment a value in rows with specific Column with python
<p><a href="https://i.stack.imgur.com/4oHVO.png" rel="nofollow noreferrer">enter image description here</a> what i need to to ist to increment the ID based on the Value in column Country i used this code:</p> <p><code> i=1 for row in new_cols5): new_cols5.loc[new_cols5.Country=='Germany','ID']='GR'+str(i) new_cols5.l...
<p>First you could use <code>print()</code> to see what you get with <code>new_cols5.loc[]</code>.</p> <p><code>new_cols5.loc[]</code> gives you all matching rows and you assign the same value to all rows at once.</p> <p>You would have to iterate these rows to assign different values.</p> <p>Or:</p> <p>You should get n...
python|pandas
0
364,982
73,490,489
How to keep the datetime format in xaxis intact while plotting pandas dataframe with matplotlib in Python?
<p>I have a pandas dataframe <code>df</code> which looks as follows:</p> <pre><code>Monthly Peak Demand 2019-07-31 1313.080833 2019-08-31 1407.938078 2019-09-30 1289.603335 2019-10-31 1266.722083 2019-11-30 1242.099010 2019-12-31 1374.902243 2020-01-31 1340.754667 2020-02-29 1256.317174 2020-03-31 1206.196696 ...
<p>Pandas plots bar charts as categoricals, so you need to use matplotlib directly. Pandas registers its own converter for period timeseries to get this nice formatting. Although it's easy to convert the index to a period index (<code>df.index.to_period(freq='M')</code>) I couldn't get this converter work with matplotl...
python|python-3.x|pandas|matplotlib|bar-chart
1
364,983
73,439,781
How to do argmax in group in pytorch?
<p>Is there any ways to implement maxpooling according to norm of sub vectors in a group in Pytorch? Specifically, this is what I want to implement:</p> <p><strong>Input</strong>:</p> <p><strong>x</strong>: a 2-D float tensor, shape <strong>#Nodes * dim</strong></p> <p><strong>cluster</strong>: a 1-D long tensor, shape...
<p>I don't think there's any built-in function to do what you want. Basically this would be some form of scatter_reduce on the norm of <code>x</code>, but instead of selecting the max norm you want to select the row corresponding to the max norm.</p> <p>A straightforward implementation may look something like this</p> ...
python|pytorch|scatter
0
364,984
73,505,323
Pandas get values in one column that are not in another column
<p>I am new to pandas and looking a way to find missing values in columns 'a' from column 'b'. How to get the following result?</p> <h1>MWE</h1> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df = pd.DataFrame({'a': [[1,2,3],[10,20,30]], 'b': [[1,2],[20]]}) ...
<p>You can use <code>np.setdiff1d</code>, just inside of <code>apply</code>:</p> <pre class="lang-py prettyprint-override"><code>df['c'] = df.apply(lambda row: np.setdiff1d(row['a'], row['b']), axis=1) df a b c 0 [1, 2, 3] [1, 2] [3] 1 [10, 20, 30] [20] [10, 30] </code></pre...
python|pandas
2
364,985
73,503,679
Panda variance row wise
<p>Hi everyone I am a beginner in python. I have a dataset that looks like the following</p> <pre><code>df = pd.DataFrame({&quot;a&quot; : [1,2,3], &quot;b&quot; : [[1,2],[2,3,4],[5]]}) a b 0 1 [1, 2] 1 2 [2, 3, 4] 2 3 [5] </code></pre> <p>and I wanted to calculate the variance of every row. ...
<p>IIUC you are looking for:</p> <pre><code>df['b'].apply(np.var) </code></pre> <p>output:</p> <pre><code>0 0.250000 1 0.666667 2 0.000000 </code></pre>
python|pandas|dataframe
0
364,986
73,249,933
Swap the column to one single row
<p>This is the df:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Animal</th> <th style="text-align: center;">Name</th> <th style="text-align: right;">foo</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">Tiger</td> <td style="text-align: center;">Two...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;&quot;] = &quot;foo&quot; + (df.groupby([&quot;Animal&quot;, &quot;Name&quot;]).cumcount() + 1).astype(str) print( df.pivot(index=[&quot;Animal&quot;, &quot;Name&quot;], columns=&quot;&quot;, values=&quot;foo&quot;).reset_index() ) </code></pre> <...
python|python-3.x|pandas|dataframe|pivot
3
364,987
73,297,053
Defining a function for a dataframe
<p>I'm trying to define a function that selects a part of a dataframe, groups it by a column in the dataframe and attach a suffix to the column names</p> <pre><code>def diagnosis(x): x = df.query('x == 1').groupby('gender').count() return x.rename(lambda y: y[:11] + '_' + x[0], axis='columns') </code></pre> <p>...
<p>I noticed two functions:</p> <pre><code>def diagnosis_v1(x): x = med_app_cleaned.query(x == 1).groupby('gender').count() return x.rename(lambda y: y[:11] + '_' + x[0], axis='columns') def diagnosis_v2(x): x = df.query('x == 1').groupby('gender').count() return x.rename(lambda y: y[:11] + '_' + x[0],...
python|pandas|function
0
364,988
73,266,806
Replicating MATLAB's `randperm` in NumPy
<p>I want to replicate MATLAB's <a href="https://www.mathworks.com/help/matlab/ref/randperm.html" rel="nofollow noreferrer"><code>randperm()</code></a> with NumPy.</p> <p>Currently, to get <code>randperm(n, k)</code> I use <code>np.random.permutation(n)[:k]</code>. The problem is it allocates an array of size <code>n</...
<p>I can recommend you <code>np.random.choice(n, k, replace = False)</code>. Yet, I am not sure about memory efficiency. Please refer to <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html" rel="nofollow noreferrer">docs</a></p>
python|numpy|performance|matlab|random
2
364,989
73,234,429
Create a dataframe from a deeply nested dictionary
<p>I currently using API to pull a some data example below</p> <pre><code>{'Data':[{'id':'123','subdata':[{'Addnl':'bar','details':[], 'country':'BRA'},{'Addnl':'foobar' ,'details':[{'resttype':'prod','restsubtype':'foobar'},{'resttype':'dev','restsubtype':'foobar'}], 'country':'USA'}]}]} </code></pre> <p>Expected dat...
<p>If <code>dct</code> is your dictionary from the question, then:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(dct[&quot;Data&quot;]).explode(&quot;subdata&quot;) df = pd.concat([df, df.pop(&quot;subdata&quot;).apply(pd.Series)], axis=1).explode( &quot;details&quot; ) df = pd.concat([df, d...
python|pandas|dictionary
2
364,990
73,441,152
Running Distinct Count in Pandas by a group
<p>I have a dataframe 'df', with the following structure:</p> <p><strong>Input:</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">ID</th> <th style="text-align: center;">Product</th> <th style="text-align: right;">Price</th> </tr> </thead> <tbody> <tr> <td s...
<p>You can try to compare the row and next row in <code>Price</code> column and calculate the <code>cumsum</code></p> <pre class="lang-py prettyprint-override"><code>df['Distinct_Running_Count'] = (df.groupby(['Product'])['Price'] .transform(lambda col: col.ne(col.shift().fillna(col)).cu...
python|pandas
0
364,991
73,447,588
What is the optimal Python data structure and how to export it to Excel
<p>I am trying to analyze mechanical computation results using Python and export them to Excel automatically. My raw data consists of various types of computation (each stored in a different text file). For each type, I have various load cases (loading conditions). For each load case, I output the results are various d...
<p>Finally, converting my list of dictionaries to <code>pandas.DataFrame</code> and using the appropriate arguments to <code>pandas.pivot_table</code> and exporting to Excel using <code>pandas.pivot_table.to_excel</code> did the trick.</p> <p>Full solution was those lines:</p> <pre><code>df = pandas.DataFrame.from_dict...
python|pandas|dataframe|dictionary|nested
1
364,992
73,211,571
Merging the datasets into one single column by using Pandas
<p>looks like I need your help, I am trying to merge the datasets into a single dataset. By using this codes</p> <pre><code>import pandas as pd import numpy as np Total_Transfer = pd.read_excel('total_transfer.xlsx') Total_Issued = pd.read_excel('total_issued.xlsx') Total_Retirement = pd.read_excel('retirement_finalist...
<p>I think this error appears because you are not using correctly pandas merge() function - you can merge only two DataFrames at a time.</p> <p>Maybe it helps:</p> <pre><code>Total_Issued.merge(Total_Retirement, on ='Vintage').merge(Total_Transfer, on='Vintage') </code></pre> <p>or</p> <pre><code>pd.merge(pd.merge(Tota...
python|pandas|numpy|merge
0
364,993
73,237,897
Python - imported a excel trying to call 2 columns of data where data is pulled from column 1 if matched in column 2
<p>I am new to python and scripting in general. so if this seems simple I am sorry. I have tried to google etc but not finding what I am after.</p> <ul> <li>Issue I have a excel sheet that I import</li> </ul> <pre><code>import pandas as pd path_input = r'C:\Users\XXXXX\PycharmProjects\List.xlsx </code></pre> <p>From th...
<p>What I understood you actually want to call cells in column owner that are equal to a certain name in column owner, not vice versa.</p> <p>You may not be able to directly call the data that satisfies the condition you want, but you can easily edit the dataframe after calling. So,</p> <pre><code>new_df = df[df.OWNER ...
python|excel|pandas
0
364,994
73,346,095
hugging face, Numpy is not available
<p>CODE I AM RUNNING:</p> <pre><code>from transformers import pipeline classifier = pipeline('sentiment-analysis') res = classifier(&quot;I Love Python.'&quot;) print(res) </code></pre> <p>ERROR I AM GETTING:</p> <pre><code>No model was supplied, defaulted to distilbert-base-uncased-finetuned-sst-2-english and revis...
<p>The immediate fix for you is probably</p> <pre><code>pip install --upgrade numpy </code></pre> <p>Which should get you <code>numpy==1.23.1</code> at the time of this answer.</p> <p>I didn't take too much of a look at the host of other requirements you have, but if you had other things that required older versions of...
python|numpy|nlp|huggingface-transformers
1
364,995
73,221,804
Specify grid color
<p>I am trying to create a grid with gray, white and black colors and specify these colors for each box in the grid. I could create a grid with 2 rows and three columns, but not sure to specify the colors in the grid (not randomly color the boxes in the grid)</p> <p>Code</p> <pre><code>import matplotlib.pyplot as plt ...
<p>Please find the below code to plot a grid, specify the colors for each box in the grid as well specify the row and column names</p> <pre><code>import matplotlib.pyplot as plt import numpy as np a = [[0,1,0.5],[1,0,0.5]] nrows, ncols = 2,3 image = np.zeros(nrows*ncols) image = image.reshape((nrows, ncols)) row_label...
python|numpy|matplotlib|grid
1
364,996
35,043,726
Function which changes strings of filenames based on a list
<p>I have multiple folders with csv files in them, and I am creating Cartesian lists and running some statistics on all file combinations.</p> <p>So far I am executing this like this:</p> <pre><code>import pandas as pd import os import scipy as sp from scipy import stats import glob import itertools # # path =r'F:\Sh...
<p>Create a function:</p> <pre><code>def get_df(path): allfiles = glob.glob(path + "/*.csv") result = list(itertools.product(allfiles,allfiles)) # dataframe=[] for files in result: x=(pd.read_csv(files[0], names = ['Percent', 'Value'])) z=x.Percent y=(pd.read_csv(files[1], n...
python|csv|pandas
1
364,997
34,916,412
Formatting csv to allow numpy to make a data frame
<p>I'm trying to read in this CSV file with numpy. I'm following <a href="http://wiki.quantsoftware.org/index.php?title=QSTK_Tutorial_2" rel="nofollow">this tutorial</a> but my data is formatted differently to their example</p> <p><a href="https://drive.google.com/open?id=0B29jmpbf6e_WZ2JYT3BxRFN1OGM" rel="nofollow">H...
<p>You can use parameter <code>sep</code> as arbitary whitespace: <code>\s+</code> in function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc....
python|csv|numpy|pandas
2
364,998
35,141,961
Pandas: produce a multiple bar plot based on conditional over column
<p>I've got a DataFrame </p> <pre><code>gender A B M a 1 M b 3 F a 0 F b 4 ... </code></pre> <p>I'd like to produce a multiple bar plot where of B on y axis and A on x axis where the bars are separate per gender, that is, bars for gender M are next to those for gender F.</p> <p>Any way ...
<pre><code>pd.pivot_table(df, index='A', columns='gender', values='B').plot(kind='bar') </code></pre> <p><a href="https://i.stack.imgur.com/U4VYt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U4VYt.png" alt="enter image description here"></a></p>
python|pandas|dataframe
3
364,999
35,170,791
sklearn.linear_model not found in TensorFlow Udacity course
<p>I'm following the instructions of the Deep Learning course by Google with TensorFlow. Unfortunately I'm stuck <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/1_notmnist.ipynb" rel="nofollow noreferrer" title="here">with this workbook</a> right now. I work in the docker vm wi...
<p>You can install and upgrade sklearn from the shell with pip. That may or may not be the problem - but at least you'll know its installed.</p> <pre><code>sudo pip install --upgrade scikit-learn </code></pre>
scikit-learn|tensorflow
7