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
12,600
67,444,790
Not why input variable won't switch from NoneType to string
<pre><code>cryptoinput = print(input(&quot;Choose cryptocurrency ticker to analyze: &quot;)) finalinput = str(cryptoinput) print(str(finalinput)) #User Input start = datetime.date(2021, 4, 23) end = datetime.date(2021, 5, 7) inputc = pdr.get_data_yahoo(cryptoinput, start, end) </code></pre> <p>Keeps returning tha...
<p>Remove the print when you assign to <code>cryptoinput</code>. Also, no need to cast to string, as <code>input()</code> returns a string already.</p> <pre><code>cryptoinput = (input(&quot;Choose cryptocurrency ticker to analyze: &quot;)) finalinput = cryptoinput print(finalinput) </code></pre>
python|pandas
2
12,601
67,427,952
Trying to use a pd.df column value to replace a string value in the same row, seperate column
<p>I have tried to use .iat but that is a static value. I have about 75 rows with two columns, I'm looking to replace a hyperlink in column &quot;B&quot; with the domain from column &quot;A&quot;. I think .iat would be the best way but I can't figure out the dynamic value for (current row, 1).</p> <p>Let me explain a...
<p>If you just want to replace just one specific column B value, then try use <code>np.where</code>:</p> <pre><code>import numpy as np value_to_replace = &quot;whatever&quot; # This is saying if B == value_to_replace, set column B to A, else just leave as B # result = np.where((conditional), ...
python|pandas|dataframe|for-loop
1
12,602
67,408,038
Pandas: group columns into a time series
<p>Consider this set of data:</p> <pre><code>data = [{'Year':'1959:01','0':138.89,'1':139.39,'2':139.74,'3':139.69,'4':140.68,'5':141.17}, {'Year':'1959:07','0':141.70,'1':141.90,'2':141.01,'3':140.47,'4':140.38,'5':139.95}, {'Year':'1960:01','0':139.98,'1':139.87,'2':139.75,'3':139.56,'4':139.61,'5':13...
<p>here is one way</p> <pre><code>s = pd.DataFrame(data).set_index(&quot;Year&quot;).stack() s.index = pd.Index([pd.to_datetime(start, format=&quot;%Y:%m&quot;) + pd.DateOffset(months=int(off)) for start, off in s.index], name=&quot;Year&quot;) df = s.to_frame(&quot;Value&quot;) </code></pre> <p>Fir...
python|pandas|time-series
1
12,603
59,966,845
Error using ImageDataGenerator with Keras Tuner search
<p>I am using <code>from tensorflow.keras.preprocessing.image import ImageDataGenerator</code> Here is the code :</p> <pre><code>(x_train, y_train), (x_test, y_test) = cifar10.load_data() x_train, x_test = x_train.astype('float32') / 255, x_test.astype('float32') / 255 y_train, y_test = to_categorical(y_train), to_cat...
<p>Looks like <code>Sparse_categorical_crossentropy</code> wasn't the best choice for the generator and that was the whole problem.</p> <p>Reference: <a href="https://github.com/keras-team/keras-tuner/issues/223" rel="nofollow noreferrer">https://github.com/keras-team/keras-tuner/issues/223</a></p>
keras|tensorflow2.0|tf.keras|tuner
0
12,604
60,232,710
Pandas: How to combine column int values if different given column is duplicated?
<p>There are similar questions on Stack Overflow, but none of them have worked for my situation. I've tried working with a combination of <code>add(...)</code>, <code>merge(...)</code>, <code>concat(...)</code>, <code>drop_duplicates(...)</code> and more, and I just can't seem to figure it out.</p> <p>I'm handling dat...
<p>You can try <code>agg</code> with a dictionary:</p> <pre><code>agg_dict = {col: 'first' if col in ['FavoriteFood','Index'] else 'sum' for col in df.columns if col!='ID'} df.groupby('ID', as_index=False, sort=False).agg(agg_dict) </code></pre> <p>Output:</p> <pre><code> ID Index FavoriteFood A1 ...
python|pandas
1
12,605
59,908,507
Taking the last two rows' minimum value
<p>I have this data frame:</p> <pre><code>ID Date X 123_Var 456_Var 789_Var A 16-07-19 3 777 250 810 A 17-07-19 9 637 121 529 A 18-07-19 7 878 786 406 A 19-07-19 4 656 140 204 A 20-07-19 2 295 272 490 A 21-07-19 3 ...
<p><strong>IIUC</strong>, We use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.shift.html" rel="nofollow noreferrer"><code>groupby.shift</code></a> to select the previous var for each <strong>ID</strong>, then we can use <a href="https://pandas.pydata.org/panda...
pandas
3
12,606
49,949,463
Does tf.transpose also change the memory (like np.ascontiguousarray)?
<p>If I use <code>tf.transpose</code> does it also change the memory layout? </p> <p>In numpy it is used the function <code>np.ascontiguousarray</code>. </p> <p>I mean this would be important if I use cuda. Because it makes a difference if the memory layout is [N C H W] or [N H W C]. (N ... Nr of samples, H ... array...
<p>If you read carefully <a href="https://www.tensorflow.org/api_docs/python/tf/transpose" rel="nofollow noreferrer">the documentation</a> you can find the answer:</p> <blockquote> <p>Numpy Compatibility</p> <p>In numpy transposes are memory-efficient constant time operations as they simply return a new view of...
python-2.7|numpy|tensorflow
3
12,607
49,924,873
Keras video frame prediction with lower output dimension then input dimension
<p>I want to train a Keras DNN for video frame prediction: </p> <ul> <li><strong>Input</strong>: 4 consecutive Frames of a Video </li> <li><strong>Output</strong>: Next frame, predicted from the network</li> </ul> <p>So, basically, the dimensions are: input: (number_samples, 4, 60, 60), output: (number_samples, 1...
<p>This loop in the code example (for which you gave the URL) can be tailored to do what you desire.</p> <pre><code>for j in range(16): new_pos = seq.predict(track[np.newaxis, ::, ::, ::, ::]) new = new_pos[::, -1, ::, ::, ::] track = np.concatenate((track, new), axis=0) </code></pre>
tensorflow|machine-learning|neural-network|deep-learning|keras
1
12,608
64,158,995
Pandas Lambda OR / AND Statements Across Columns
<p>I am trying to create a new column [Check] that looks at my [Color] column and my [Size] column to say if the color is blue and size is greater than 50, then the column should be the Owner, else leave it blank.</p> <p>IF Color = Blue &amp; Size &gt; 50, THEN [Owner] ELSE null</p> <p>I have the following:</p> <pre><c...
<p>You can use <code>apply</code> on a column, but you can also use it on a dataframe itself. You'll need to provide an axis (row or columns) if you are using the dataframe.</p> <p><code>f = lambda row: row['Owner'] if (row['Color'] == 'Blue') &amp; (row['Size'] &gt; 50) else null</code></p> <p><code>df['Check'] = df.a...
python|pandas
1
12,609
46,845,388
Conv3D not working
<p>I built a tensorflow model using <code>conv3d</code>, froze it and optimized for inference. When I call the inference in Android (<code>TensorflowInferenceInterface.run</code>), I get the following error:</p> <pre><code>java.lang.IllegalArgumentException: No OpKernel was registered to support Op 'Conv3D' with these...
<p>Looks like creating <code>ops_to_register.h</code> is not enough. I had to modify the <code>tensorflow/core/kernels/BUILD</code> file, such that files in <code>tensorflow/core/kernels/</code> containing are listed in the <code>android_extended_ops_group1</code> or <code>android_extended_ops_group2</code> section (an...
android|tensorflow
0
12,610
63,242,071
How do I save pandasProfile report using Tkinter asktosavefile module?
<p>When I run the code and enter a file name and click on save the application generates HTML then it says rendering HTML and after that is done it closes. when I look at the file generated it appears to be empty.</p> <p><em>Here is my code:</em></p> <pre class="lang-py prettyprint-override"><code>def SaveReport(): ...
<p>You are complicating matters. Just <code>write</code> to the <code>file</code> directly:</p> <pre><code>def SaveReport(): html = df.to_html() files = [('HTML Files', '*.html')] file = filedialog.asksaveasfile(mode=&quot;w&quot;, title=&quot;Save File&quot;, filetypes=f...
python|pandas|tkinter
2
12,611
62,962,383
Changing code to allow more than 3 stacked bars
<p>So I found this code online which plots a stacked bar chart with three bars (each having three bars stacked on top of one another):</p> <pre><code>%matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') data = [[2000, 2000, 2000, ...
<p>Seems like a complicated way to do:</p> <pre><code>rows = zip(*data) headers = ['Year', 'Month', 'Value'] colors = [&quot;#006D2C&quot;, &quot;#31A354&quot;,&quot;#74C476&quot;] df = pd.DataFrame(rows, columns=headers) (df .pivot(index='Year', columns='Month', values='Value') .reindex(columns=df.Month.unique()) ....
python|pandas|matplotlib|indexing|indexoutofboundsexception
2
12,612
67,873,735
Create a new column with unique identifier for each group
<p>I need to create a new &quot;identifier column&quot; with unique values for each combination of values of two columns. For example, the same &quot;identifier&quot; should be used when <strong>ID</strong> and <strong>phase</strong> are the same (e.g. r1 and ph1 [but a new, unique value should be added to the column w...
<p>Try with <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.ngroup.html#pandas-core-groupby-groupby-ngroup" rel="nofollow noreferrer"><code>groupby ngroup</code></a> + 1, use <code>sort=False</code> to ensure groups are enumerated in the order they appear in the DataFrame:</p> <pre><co...
python|pandas|dataframe
4
12,613
61,536,693
How to set elemnts of numpy array based on elements of another numpy array
<p>I'm trying to set elemnts of array1 to nan based on elements of array2 which are nan.</p> <p>The following is my code (which isn't working)</p> <p>I would greatly appreciate assistance :) </p> <pre><code>array1 = np.array([1.,1.,1.,1.,1.,1.,1.,1.,1.,1.]) array2 = np.array([2.,2.,2.,2.,np.nan,np.nan,np.nan,2.,2.,2...
<p>Use np.isnan.</p> <pre><code>import numpy as np array1 = np.array([1.,1.,1.,1.,1.,1.,1.,1.,1.,1.]) array2 = np.array([2.,2.,2.,2.,np.nan,np.nan,np.nan,2.,2.,2.]) array1[np.isnan(array2)] = np.nan print(array1) </code></pre> <p>Output is as desired:</p> <pre><code>[ 1. 1. 1. 1. nan nan nan 1. 1. 1.] </code><...
python|numpy
4
12,614
61,422,670
Applying a custom groupby aggregate function to find average of Numpy Array
<p>I am having a pandas DataFrame where B contains NumPy list of fixed size.</p> <pre><code>|------|---------------|-------| | A | B | C | |------|---------------|-------| | 0 | [2,3,5,6] | X | |------|---------------|-------| | 1 | [1,2,3,4] | X | |------|---------------|----...
<p>What you need is possible with convert values to 2d array and then using <code>np.mean</code>:</p> <pre><code>f = lambda x: np.mean(np.array(x.tolist()), axis=0) df2 = df.groupby('C')['B'].apply(f).reset_index() print (df2) C B 0 X [1.5, 2.5, 4.0, 5.0] 1 Y [2.0, 3.0, 4.0, 4.0] 2 Z [2.0,...
python|pandas|numpy|pandas-groupby
3
12,615
61,510,122
{ "error": "Malformed request: POST /v1/models/text_model" } Tensorflow Serving
<p>I am Using Colab for text Classification, it is Multilabel text classification model</p> <pre><code> import json # inputFeature1 inputFeature1="¿Tiene el arte que gustar a todos? Pues no" #inputFeature2 inputFeature2="Una imagen del último día de la exposición ded" #inputFeature3 inputFeature3="marabilias"...
<p>Without knowing the model signature, I believe the issue is with your <code>instances=</code> statement. Change it to: <code>instances=[{"inputFeature1":inputFeature1,"inputFeature2=":inputFeature2,"inputFeature3":inputFeature3}] </code></p> <p>You were passing the feature value as a list [] rather than just the va...
python|tensorflow|tensorflow-serving
0
12,616
68,644,181
Remove dictionary key if any item of the tuple that composes it is not in a dataframe
<p>I have a dict and a df that as the following below:</p> <pre><code>import networkx as nx import pandas as pd import scipy.spatial.distance as ssd import numpy as np dict_edge = {(1,2): {'Duration': 1.17, 'Numcalls':4}, (3,2): {'Duration': 1.27, 'Numcalls':3}, (3,4): {'Duration': 1.3, 'Numc...
<p>You can check whether all the keys are in the index:</p> <pre><code>for key, value in zip(dict_edge.keys(), dict_edge.values()): if pd.Series(key).isin(df.index).all(): x = df.loc[key[0]].values y = df.loc[key[1]].values cosine = 1 - ssd.cosine(x,y) value['Cosine_Similarity'] = co...
python|pandas
1
12,617
68,704,968
Student's t-test for the excel sheet using python
<p>I have an excel sheet with data for 60 years for 50 Regions like follows:</p> <p><strong>Year R1 R2 R3 .. .. .. .. .. .. .. .. R50</strong></p> <p>1951 66 45 22 .. .. .. .. .. .. .. .. 20</p> <p>1952 54 .. .. .. .. .. .. .. .. .. .. .. .. 15</p> <p>..</p> <p>..</p> <p>2010 51 33 .. .. .. .. .. .. .. .. .. 45</p> <p>...
<pre><code>from scipy.stats import ttest_ind import pandas as pd df=pd.read_excel(&quot;t-test_Data.xlsx&quot;) l=list() for i in df.columns[1:]: l.append(pd.DataFrame({i:ttest_ind(df[df.Year &lt; 1981][i],df[df.Year &gt;= 1981][i])})) d=pd.concat(l,axis=1) d.index=[&quot;statistic&quot;,&quot;p_value&quot;] d.to_...
python|pandas|numpy|scipy|statistics
-1
12,618
68,670,375
Getting KeyError when saving style multiindex pandas to excel
<p>When saving a <code>df</code> that has been style into excel, compiler return</p> <blockquote> <p>KeyError: &quot;['A'] not in index&quot;</p> </blockquote> <pre><code>import pandas as pd import numpy as np def color_negative_red(value): if value &lt; 0: color = 'red' elif value &gt; 0: color = 'green'...
<p>This is nothing to do with <code>Styler.to_excel</code>. It is to do with the fact you are using a MultiIndex columns and not supplying a <code>subset</code> in a valid format.</p> <p>As advised in the docs you must supply a valid <code>.loc</code> indexer.</p> <p>The solution is to use:</p> <pre class="lang-py pret...
python|pandas|styles
1
12,619
53,285,989
Pasting from external program into Excel file
<p>Apologies if this has been answered - I just spent the last hour or so looking for a specific method and was unable to find it.</p> <p>I am getting data from a reporting program via keyboard emulation with pynput - the program has specific menus for copying data and selecting what is actually copied.</p> <p>I have...
<p>Having the data already copied to the clipboard, you can use python pandas DataFrames to process it. Below is the method which accepts data copied from the clipboard and convert it into DataFrame.</p> <pre><code>pandas.read_clipboard(sep='\\s+', **kwargs) </code></pre> <p>Now you can select whichever column you wa...
python|excel|pandas|copy|paste
0
12,620
65,637,222
RuntimeError: Subtraction, the `-` operator, with a bool tensor is not supported
<p>I am using this github repo: <a href="https://github.com/vchoutas/smplify-x" rel="nofollow noreferrer">https://github.com/vchoutas/smplify-x</a> and I am running a script. I get the following error. How can I fix it? I understand I might have to convert <code>-</code> to <code>~</code> however not sure where it exac...
<pre><code>$ vi /home/mona/venv/smplifyx/lib/python3.6/site-packages/torchgeometry/core/conversions.py </code></pre> <p>and comment and add lines similarly for mask conversion compatibility in PyTorch 1.7.1</p> <pre><code>mask_c0 = mask_d2 * mask_d0_d1 #mask_c1 = mask_d2 * (1 - mask_d0_d1) mask_c1 = mask_d2 * ~(mask_d0...
python|deep-learning|computer-vision|pytorch|torch
2
12,621
65,554,032
Understanding convolutional layers shapes
<p>I've been reading about convolutional nets and I've programmed a few models myself. When I see visual diagrams of other models it shows each layer being smaller and deeper than the last ones. Layers have three dimensions like <code>256x256x32</code>. What is this third number? I assume the first two numbers are the ...
<h4>TLDR; <code>256x256x32</code> refers to the layer's output shape rather than the layer itself.</h4> <hr /> <p>There are many articles and posts out there explaining how convolution layers work. I'll try to answer your question without going into too many details, just focusing on <em>shapes</em>.</p> <p>Assuming yo...
machine-learning|deep-learning|pytorch|conv-neural-network
7
12,622
65,871,169
Pandas adding additional values between two row-values in a dataframe with number constraint
<p>I have data frame. Under the same index, I have &quot;early_date&quot; &amp; &quot;latest_date&quot;, which are in &quot;int&quot; dtype. I want to create additional values in between the &quot;early_date&quot; &amp; &quot;latest_date&quot; row-values. Incidentally, I want to stack the generated values into new rows...
<p>IIUC, you can add a condition in your for loop:</p> <pre><code>df_p['new'] = [list(range(x,y+1)) if str(x)[-2:]!='52' else [x,y] for x, y in zip(df_p.pop('early_date'), df_p.pop('late_date'))] </code></pre> <hr /> <pre><code>print(df_p) index new 0 ...
python|pandas|dataframe
1
12,623
63,663,816
pandas new data frame from list elements
<p>I have a data frame</p> <pre><code>col1 col2 col 3 …col n </code></pre> <p>I have to do all possible combination between all columns and do the chisquare test of independence.</p> <pre><code> import researchpy for i in range (0, len(corr_data.columns)): for j in range(0, len(corr_data.columns))...
<p>try this code</p> <pre><code>import pandas as pd import researchpy as rp import numpy as np import itertools # set seed for reproducibility np.random.seed(922020) df = pd.DataFrame(np.random.randint(3, size= (101, 4)), columns= ['disease', 'severity', 'alive', 'status']) def it_chi(data): ...
pandas|list
0
12,624
63,687,794
Q: ValueError Keras expected conv2d_14_input to have shape (3, 12, 1) but got array with shape (3, 12, 6500)?
<p>I am building a CNN for <strong>non image data</strong> in <strong>Keras 2.1.0</strong> on Window 10.</p> <p>My input feature is a 3x12 matrix of non negative number and my output is a binary multi-label vector with length 6x1</p> <p>And I was running into this error <strong>expected conv2d_14_input to have shape (3...
<p>you need to pass data_format=&quot;channels_last&quot; argument, bcoz your channels are at last</p> <p>you try this:</p> <pre><code>x_train=x_train.reshape((6500,3,12,1)) x_test=x_test.reshape((-1,3,12,1)) and in each of conv2d layer conv2D(&lt;other args&gt;, data_format=&quot;channels_last&quot;) </code></pre>
keras|multidimensional-array|numpy-ndarray|conv-neural-network|numpy-slicing
1
12,625
63,522,423
Pandas: replace a NaN with another DataFrame
<p>I'm trying to figure this out so please help me, I have this dataset :</p> <pre><code>df1= pd.DataFrame(data={'col1': ['a','b','c','d'], 'col2': [1,2,np.nan,4]}) df2=pd.DataFrame(data={'col1': ['a','b','b','a','f','c','e','d','e','a'], 'col2':[1,3,2,3,6,4,1,2,5,2]...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> for match values by <code>col1</code> with <code>Series</code> with unique column <code>col1</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/ap...
python|pandas
2
12,626
63,493,281
convert pandas dataframe to json with specific format
<p>I am trying to convert the dataframe mentioned below to desired json</p> <p><a href="https://i.stack.imgur.com/LYoEp.png" rel="nofollow noreferrer">enter image description here</a></p> <pre><code>column_id,column_name,mandatory,column_data_type,column_data_length,_id,data_format,file_type,active_ind 1,PAT_ID,FALSE,V...
<p>here is what I would do:</p> <pre class="lang-py prettyprint-override"><code># Load data df = pd.read_csv('data.csv') # Create list of dict for columns column col_set = ['column_id', 'column_name', 'mandatory', 'column_data_type', 'column_data_length'] df['columns'] =...
json|python-3.x|pandas
0
12,627
71,836,800
Is there a way to iteratively add plots to Animation.FuncAnimation()?
<p>I'm working on my master thesis right now and need to animate a high number of points moving. Those points will be representing predators and prey. The number of predators and preys should be changeable and probably around 500 each. For now i hard coded the animation function with 3 predators and 1 prey. is there a ...
<p>One way to achieve it is by knowing that your first add all the predators, then all the preys. So, <code>ax.patches</code> contains an ordered list of patches, and you can loop over them to update their positions:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib import random import numpy as np...
python|numpy|matplotlib|animation
0
12,628
71,882,887
how to convert tuples in a column rows of a pandas dataframe into repeating rows and columns?
<p>I have a dataframe which contains the following data (only 3 samples are provided here):</p> <pre><code>data = {'Department' : ['D1', 'D2', 'D3'], 'TopWords' : [[('cat', 6), ('project', 6), ('dog', 6), ('develop', 4), ('smooth', 4), ('efficient', 4), ('administrative', 4), ('procedure', 4), ('establishment', 3), ('m...
<p>I'd suggest you do the wrangling before loading into a dataframe, with the <code>data</code> dictionary:</p> <pre class="lang-py prettyprint-override"><code>length = [len(entry) for entry in data['TopWords']] department = {'Department' : np.repeat(data['Department'], length)} (pd .DataFrame([ent for entry in data['...
python-3.x|pandas|tuples
3
12,629
55,155,245
Group a column of a data frame based on another dataframe
<p>Based on this dataframe</p> <pre><code> df1 Name Age Johny 15 Diana 35 Doris 97 Peter 25 Antony 55 </code></pre> <p>I have this dataframe with the number of ranges that I want to use, for example</p> <pre><code> df2 Header Init1 Final1 Init2 Final...
<p>Using <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.cut.html" rel="nofollow noreferrer"><code>pd.cut</code></a>:</p> <pre><code>l = df2.iloc[1,1:].tolist() labels = [str(t[0])+'-'+str(t[1]) for t in zip(l[::1],l[1::1])] df['Age'] = pd.cut(df['Age'], bins=l, labels=labels) print(df...
python|pandas|dataframe|grouping
2
12,630
55,484,834
tensorflow, tf.while_loop: The two structures don't have the same nested structure
<p>I tried to build a nested loop which is used to create a 2-dim zero-matrix to solve LCS problem (dynamic programming). This is later used in computing the Rouge-L score (the input is tensor, not string), but it always goes wrong raising <code>ValueError: The two structures don't have the same nested structure.</code...
<p>Hi Basically what the error message is saying is that your return value is a list while it was expecting it to be a number, this makes sense as you have defined your shape_invariants to be <code>[0, len(lengths)]</code> which both are integers thus the second structure defined as <code>[.,.]</code> however the first...
python|tensorflow|deep-learning
0
12,631
66,809,441
Option c and option s in pandas dataframe plot
<p>I saw the following snippet of code from a book I am studying from</p> <pre><code>housing.plot(kind=&quot;scatter&quot;, x=&quot;longitude&quot;, y=&quot;latitude&quot;, alpha=0.4, s=housing[&quot;population&quot;]/100, label=&quot;population&quot;, figsize=(10,7), c=&quot;median_house_value&quot;, cmap=plt.get_cm...
<p>I believe you should look at matplotlib documentation site, mentioned <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.scatter.html" rel="nofollow noreferrer">here</a> . Since the default <code>plotting.backend</code> is set to matplotlib in pandas, so these things are mentioned there. Here is wh...
pandas|dataframe
1
12,632
47,213,925
select different column python pandas
<p>I have a question how to select different column(create new series) based on another column value. raw data as following:</p> <pre><code> DEST_ZIP5 EXP_EDD_FRC_DAY GND_EDD_FRC_DAY \ 0 00501 5 6 1 00544 5 ...
<p>IIUC:</p> <pre><code>c = df['EXP_EDD_FRC_DAY'].astype(str).radd('GND_DAY_') new_series = pd.Series(df.lookup(df.index, c), df.index) </code></pre>
python|python-2.7|pandas|dataframe
1
12,633
47,477,314
Tensorflow Java API set Placeholder for categorical columns
<p>I want to predict on my trained Model from Python Tensorflow API with the Java API, but have problems to feed in the features to predict in Java.</p> <p>My Python Code is like this:</p> <pre><code>from __future__ import absolute_import from __future__ import division from __future__ import print_function import o...
<p>Since you're using <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/export/build_parsing_serving_input_receiver_fn" rel="nofollow noreferrer"><code>tf.estimator.export.build_parsing_serving_input_receiver_fn</code></a>, the exported saved model you've created expects a serialized <a href="https://git...
java|python|tensorflow|tensorflow-serving
2
12,634
47,248,727
Parsing CSV file with Pandas in Python 3
<p>I am trying to parse a movie database with Python 3. How can I parse genres of a movie with different variables? For example:</p> <pre><code>1,Toy Story (1995),Adventure|Animation|Children|Comedy|Fantasy 2,Jumanji (1995),Adventure|Children|Fantasy </code></pre> <p>First value is movie_id, second is movie_name, and...
<p>You can use separator <code>,|</code> but is necessary first row have to contains all possible genres:</p> <pre><code>df = pd.read_csv("movielens/movies.csv", sep="[,|]", header=None, engine='python') print (df) 0 1 2 3 4 5 6 0 1 Toy Story (1995) Adventur...
python|csv|numpy
2
12,635
68,227,837
Pandas Datareader not responding, HTTP status 404
<p>I am trying to get the historical price data of a company (APPLE in this case) using pandas datareader in python using data_source as Yahoo.</p> <p>This worked perfectly until just a few days ago (July 2021). I am not sure if Yahoo has discontinued their API again or is it just me.</p> <pre><code>import pandas_datar...
<p>I had the same error.</p> <p>I upgraded pandas-datareader from 0.9.0 to 0.10.0. I also upgraded pandas from 1.1.1 to 1.3.0.</p> <p>The error then disappeared. I do not know which one really solved the issue.</p> <p>One possible way to upgrade is typing: <code>pip install --upgrade pandas-datareader</code>.</p>
python|pandas|dataframe|stock|pandas-datareader
5
12,636
68,363,198
speed up unparallelizable for loop in pytorch code
<p>I built a network in pytorch, and upon profiling, saw that ~90% of the work is done in a for loop in one of my blocks. The problem is that this loop is not parallelizable, due to dependency on the previous values that were masked by mask1 (see MWE bellow).</p> <p>I tried compiling it using torch.jit.script and the s...
<p>One idea is to move this operation off-process. For instance, if this was a preprocessing step before training, you could have a pool of workers pre-processing multiple batches ahead of time and queuing them such that the wait time to dequeue the first ready batch was negligible or much smaller.</p> <p>Another thoug...
pytorch
0
12,637
68,205,917
How to use mulpile conditioning in pandas series, select few and take moving average
<p>With reference to the previous post: <a href="https://stackoverflow.com/questions/68192773/averaging-and-plotting-a-non-systematic-arranged-data-using-python-pandas">Averaging and plotting a non-systematic/arranged data using Python/Pandas</a></p> <p>I found a very crude and native way to do this:</p> <ol> <li>Post ...
<p>For this purpose you should use <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer">boolean indexing</a> instead of an <code>if</code> statement:</p> <pre class="lang-py prettyprint-override"><code># remove the if-statement conditions = (x1 &gt; ...
python|pandas|matplotlib
1
12,638
56,931,557
Do TensorFlow optimizers learn gradients in a graph with assignments?
<p>I am reproducing the original paper of Elman networks (Elman, 1990) – together with Jordan networks, known as Simple Recurrent Networks (SRN). As far as I can understand, my code correctly implements the forward propagation, while the learning phase is incomplete. I am implementing the network using the low-level AP...
<p>No, assign operations do not backpropagate a gradient. That is on purpose, as assigning a value to a variable is not a differentiable operation. However, you probably do not want the gradient of the assignment, but the gradient of the new value of the variable. You can use that gradient, just do not use it as the ou...
python|tensorflow|neural-network|deep-learning|recurrent-neural-network
1
12,639
56,946,983
CudNN Invalid input shape
<p>I am inputing a 1 dimension numpy array into a CuDNNLSTM layer that is 19 integers long. So i set the input shape to input_shape=(19,) however when trying to train the model it is giving me the following error. I can see it is expecting a numpy array with a 3rd dimenstion but not sure why</p> <pre><code>ValueError:...
<p>If you have a sequence with 19 integers, then the timesteps dimension should be 19, and the features dimension should be 1, meaning the input shape to your network should be <code>(19, 1)</code>.</p> <p>You should also reshape your data to match the new input shape.</p>
python|numpy|keras|cudnn
0
12,640
45,846,676
How to replace strings with a specific value to another string in a column in pandas dataframe
<p>I have a dataframe</p> <pre><code>AID Name Country 1 XX-USA FL, USA 2 YY USA-USA 3 YY-USA UK </code></pre> <p>I want to replace instances in <code>Country</code> only that include the string 'USA' for instance into 'USA' alone.</p> <p>So the result would be</p> <pre><code>AID Na...
<p><strong>UPDATE:</strong> I don't know what am i doing "wrong", but it works just fine for me:</p> <pre><code>In [83]: fn = r'D:\download\countries.csv' In [84]: Alldf = pd.read_csv(fn, sep=',') In [85]: pd.options.display.max_rows = 10 In [86]: Alldf Out[86]: aid name country 0 795...
python-2.7|pandas
2
12,641
45,901,523
tensorflow Optimizer.minimize function
<p>I am confused about minimize function. Eg. a distance variable X with shape [mini_batch_size, 1],</p> <pre><code>loss_1 = tf.reduce_mean(X), loss_2 = X </code></pre> <p>then minimize(loss_1) is mini-batch gradient descent, but how about minimize(loss_2)? element-wise updating? If so, is it exactly the same as sto...
<p>Actually this is a very technical thing in TF. loss_2 is.... equivalent to loss_1 up to the multiplication by the constant. It is not "SGD" as other answers suggest - this is not how TF works; it is also a mini batch update, and the only difference from loss_1 is that it is multiplied by batch_size, that's it. </p> ...
tensorflow|minimize
3
12,642
46,110,102
how to merge mulitple dataframes to one multiindex dataframe where each of merged dataframes becomes 2nd level column
<p>What I'd like to achieve (without too much shuffling around) is to merge 3 different dataframes, each with same columns and indexes, but each representing different category.</p> <p>df1</p> <pre><code> Children Movie enthusiast household 06f32e6e45da385834dac983256d59f3...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with parameter <code>keys</code>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.swaplevel.html" rel="nofollow noreferrer"><code>...
python|pandas|dataframe|merge|multi-index
0
12,643
46,120,041
Searching through data base for partial and full match integers
<p>I'm trying to search through a dataframe with a column that can have one or more integer values, to match one or more given integers. The integers in the database has a '-' in between For example</p> <pre><code>-------------------------------------------------- | Customer 1 |1124 | --------------...
<p><strong>Use <code>set</code></strong> </p> <ul> <li>define <code>x</code> as the test <code>set</code></li> <li>make <code>s</code> a series of <code>set</code>s</li> <li><code>s - x</code> creates a series of differences</li> <li><code>(s - x).str.len()</code> are the sizes of the differences</li> <li><code>s &am...
python|database|pandas|parsing|search
3
12,644
45,985,289
Test set accuracy of simple Tensorflow CNN segmentation is low
<p>I modified the <a href="https://www.tensorflow.org/get_started/mnist/pros/" rel="nofollow noreferrer">https://www.tensorflow.org/get_started/mnist/pros/</a> to pose it as an image segmentation, rather than a classification problem. The inputs are 60x60 downsampled MRI images (reshaped to [1,3600]) and the outputs ar...
<p>Overfitting indeed: if you'd like to compare number of training examples and number of parameters, number of parameters is far more than number of examples. However, even overfitting, I don't think dice 0.8 is low.</p> <p>Suggestions: you may want to know Fully Convolutional Networks (<a href="http://www.cv-foundat...
tensorflow|neural-network|conv-neural-network|image-segmentation
0
12,645
45,738,773
How to specify x and y axis for plotting dataframe in Python
<p>I would like to spcify x and y axis to draw data in dataframe in Python.</p> <p>For example, I have four columns in dataframe. And here's my code.</p> <pre><code>df.plot(x=df['a'], y=df['b'], label=df['c']) </code></pre> <hr> <p>It throws an error saying: These values come from 'b' column. </p> <blockquote> ...
<p><strong>df.plot</strong> takes the column labels as x and y, not the data itself</p> <p><code>df.plot(x='a', y='b')</code> might work</p> <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas...
python|pandas|plot
23
12,646
46,027,914
how to create tfrecord for custom labels in Tensorflow object detection?
<p>I am trying to use tensorflow object detection API for custom image classification. After collecting images and creating csv from labelimg I tried generating the TfRecord. But everytime I run the program it returns error </p> <pre><code> C:\&gt;python generate_tfrecord.py --csv_input=data/train _labels.csv --ou...
<blockquote> <p>C:\image.jpg : The system cannot find the file specified.</p> </blockquote> <p>The path in the file has to be a full path.</p>
python|machine-learning|tensorflow|object-detection
0
12,647
45,961,476
gcc: error: unrecognized command line option '-mfpu=neon-vfpv4'
<p>gcc: error: unrecognized command line option '-mfpu=neon-vfpv4' while building tensorflow from source. I have used bazel build -c opt --copt="-mfpu=neon-vfpv4" --copt="-funsafe-math-optimizations" --copt="-ftree-vectorize" --copt="-fomit-frame-pointer" --local_resources 1024,1.0,1.0 --verbose_failures tensorflow/too...
<p>Don't add <code>--copt="-mfpu=neon-vfpv4"</code> to your command line as this is not a flag gcc supports.</p>
tensorflow
0
12,648
50,972,169
Tensorflow object detection API: Custom VGG 16 model
<p>I am in the process of creating a Custom VGG model as a feature extractor of Faster RCNN model in Tensorflow object detection API. As mentioned on in the document <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/defining_your_own_model.md" rel="nofollow noreferrer">https://gi...
<p>I've changed vgg slim code to get the right tensor.</p> <pre><code>def vgg_16(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='vgg_16', fc_conv_padding='VALID', global_pool=False): """Oxford Net VGG 16-Layers version D E...
python|tensorflow|tensorflow-slim|vgg-net
3
12,649
66,677,752
How to extract some keys and values from dictionary and put into table using Pandas
<p>Below is the sample dictionary</p> <pre><code>sample = {'took': 728, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 111, 'relation': 'eq'}, 'max_score': 1.0, 'hits': [{'_index': 'movie_data_01_03', '_type': '_doc', '_id': '0', '_score': 1.0, '_sou...
<p>You can try <code>json_normalize</code> then extract the columns of interest:</p> <pre><code>pd.json_normalize(sample, record_path=['hits','hits'] )[['_id','_score','_source.Title']] </code></pre> <p>Output:</p> <pre><code> _id _score _source.Title 0 0 1.0 The Land Girls 1 1 ...
python|pandas
2
12,650
70,674,744
How to insert a column with the order in which the purchases were made using Pandas?
<p>I have the following Data-frame with purchases:</p> <pre><code>[in]: data = [[1, '01/01/2020', 'product_A'], [1, '01/02/2020', 'product_B'], [1, '01/01/2020', 'product_C'], [2, '01/01/2020', 'product_A'], [2, '01/09/2020', 'product_B'], [3, '01/01/2020', 'product_C'], [4, '01/01/2020', 'product_A'], [...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rank.html" rel="nofollow noreferrer">rank</a>, with <code>method='dense'</code>:</p> <pre class="lang-py prettyprint-override"><code>temp = df.sort_values(['client_id', 'purchase_date']) (temp.assign(purchase_order_index = temp.groupby('clien...
python|pandas|pandas-groupby
2
12,651
51,262,355
Identify unique combinations of values in columns, sum another column, and count number of appearances in pandas
<p>I have a DataFrame like so:</p> <pre><code>import pandas as pd d = {'param_1': [1.0, 2.0, 1.0, 1.0, 3.0, 3.0, 1.0, 2.0, 2.0,], 'param_2': [0.02, 0.08, 0.02, 0.08, 0.08, 0.02, 0.02, 0.08, 0.02], 'param_3': [0.8, 1.6, 2.5, 1.6, 1.6, 2.5, 0.8, 1.6, 0.8], 'param_4': [0, 1, 0, 0, 1, 0, 0, 1, 0], 'o...
<p>Try using <code>df.groupby(['param_1', 'param_2', 'param_3', 'param_4']).agg(['sum', 'count'])</code>, which returns:</p> <pre><code> output_value sum count param_1 param_2 param_3 param_4 1.0 0.02 0.8 0 ...
python|pandas
0
12,652
51,326,233
Image sequence processing ConvLSTM vs LSTM architecture in Keras
<p>I need to train a sequence based segmentation of 10x10 images. Following are the lstm and convlstm models that I want to use:</p> <pre><code>def lstmModel(): # Model definition model = Sequential() model.add(LSTM(50, batch_input_shape=(1, None, inp.shape[1]*inp.shape[2]), return_sequences=True, stateful...
<p><code>LSTM</code> layers are meant for "time sequences".<br> <code>Conv</code> layers are meant for "still images". </p> <p>One requires shapes like <code>(batch, steps, features)</code><br> The other requires: <code>(batch, witdh, height, features)</code> </p> <p>Now, <code>ConvLSTM2D</code> mixes both and re...
python|tensorflow|keras|lstm|keras-layer
6
12,653
51,494,967
How to count feature duplication (or Ridit feature engineering) individually on pandas
<p>This seems have multiple purpose by my machine learning project, it can be count duplication, and can be used as feature extraction as well, luckily can be use to both numerical and categoric, <a href="http://blog.rguha.net/?p=1368" rel="nofollow noreferrer">Ridit Analysys</a></p> <p>My data seems to much duplicati...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>value_counts</code></a> or <a href="http://pan...
python|pandas|dataframe|feature-extraction
1
12,654
70,975,646
Add values in columns if criteria from another column is met
<p>I have the following DataFrame</p> <pre><code>import pandas as pd d = {'Client':[1,2,3,4],'Salesperson':['John','John','Bob','Richard'], 'Amount':[1000,1000,0,500],'Salesperson 2':['Bob','Richard','John','Tom'], 'Amount2':[400,200,300,500]} df = pd.DataFrame(data=d) </code></pre> <div class="s-table-con...
<p>There can be multiple ways of solving this. One option is to use <code>Pandas Concat</code> to join required columns and use groupby</p> <pre><code>merged_df = pd.concat([df[['Salesperson','Amount']], df[['Salesperson 2', 'Amount2']].rename(columns={'Salesperson 2':'Salesperson','Amount2':'Amount'})]) merged_df.grou...
python|pandas|dataframe
3
12,655
70,922,875
How to convert a very large pyspark dataframe into pandas?
<p>I want to convert a very large pyspark dataframe into pandas in order to be able to split it into train/test pandas frames for the sklearns random forest regressor. Im working inside databricks with Spark 3.1.2.</p> <p>The dataset has a shape of (782019, 4242).</p> <p>When running the following command i run out of ...
<p>have you tried dask?</p> <pre class="lang-py prettyprint-override"><code>import dask.dataframe as dd data = dd.read_csv(...) # dask dataframe df = data.compute() #this is pandas dataframe </code></pre> <p>Parallel Dask XGBoost Model Training with xgb.dask.train() By default, XGBoost trains your model sequentially. ...
python|pandas|apache-spark|pyspark|databricks
1
12,656
51,700,673
Calculate mean every 5 rows specific column and select last data (fifth) of another column in pandas dataframe
<p>I have pandas df with say, 100 rows, 4 columns. I want to calculate mean in specific columns("Value") every 5 rows and select last data(Fifth) of another column("Date") to keep in new dataframe. How can I do that?</p> <p>My dataframe that looks like this :</p> <pre><code>&gt;&gt;df Date Product L...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with aggregate by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>agg</cod...
python|python-2.7|pandas|dataframe
1
12,657
51,690,823
Calculate non-integer frequency with NumPy FFT
<p>I would like to calculate the frequency of a periodic time series using NumPy FFT. As an example, let's say my time series <code>y</code> is defined as follows:</p> <pre><code>import numpy as np freq = 12.3 x = np.arange(10000) y = np.cos(x * 2 * np.pi * freq / 10000) </code></pre> <p>If the frequency is an intege...
<p>You can pad the data with zeros before computing the FFT.</p> <p>For example, here's your original calculation. It finds the Fourier coefficient with the maximum magnitude at frequency 12.0:</p> <pre><code>In [84]: freq = 12.3 In [85]: x = np.arange(10000) In [86]: y = np.cos(x * 2 * np.pi * freq / 10000) In [...
python|numpy|fft
1
12,658
36,006,248
forcing non-numeric characters to NAs in numpy (when reading a csv to a pandas dataframe)
<p>I have records where fields (called <code>INDATUMA</code> and <code>UTDATUMA</code>) are supposed to comprise numbers in the range of 20010101 and 20141231 (for the obvious reason). To allow missing values but retain precision up to the nearest dates, I would store them as floats (np.float64). I was hoping this woul...
<p>You can use parameter <code>converters</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_table.html" rel="nofollow"><code>read_table</code></a>:</p> <pre><code>def converter(num): try: return np.float(num) except: return np.nan #define each column converte...
python|numpy|pandas|casting|iopro
1
12,659
37,416,978
Efficient Double Sum of Products
<p>Consider two <code>ndarrays</code> of length <code>n</code>, <code>arr1</code> and <code>arr2</code>. I'm computing the following sum of products, and doing it <code>num_runs</code> times to benchmark:</p> <pre><code>import numpy as np import time num_runs = 1000 n = 100 arr1 = np.random.rand(n) arr2 = np.random...
<p>Rearrange the operation into an O(n) runtime algorithm instead of O(n^2), <em>and</em> take advantage of NumPy for the products and sums:</p> <pre><code># arr1_weights[i] is the sum of all terms arr1[i] gets multiplied by in the # original version arr1_weights = arr2[::-1].cumsum()[::-1] - arr2 sum_prods = arr1.do...
python|numpy
12
12,660
42,050,268
solving a sparse non linear system of equations using scipy.optimize.root
<p>I want to solve the following non-linear system of equations.</p> <p><a href="https://i.stack.imgur.com/EzY4U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EzY4U.png" alt="enter image description here"></a></p> <h3>Notes</h3> <ul> <li>the <code>dot</code> between <code>a_k</code> and <code>x<...
<p>I think the <code>scipy.optimize.root</code> approach holds water, but steering clear of the trivial solution might be the real challenge for this system of equations.</p> <p>In any event, this function uses <code>root</code> to solve the system of equations.</p> <pre><code>def solver(x0, alpha0, K, A, a): ''' x0 ...
numpy|scipy|sparse-matrix|mathematical-optimization|equation-solving
1
12,661
64,476,632
Same padding when kernel size is even
<p>When the kernel size is odd, we can manually calculate the necessary padding to get the output in the same dimension as input such that it creates same padding.</p> <p>But how can we calculate padding dimensions for kernels with even sizes (ex: (2x2)?</p>
<p>note these the 2 formula's</p> <ol> <li><strong><strong>pad</strong>= (<strong>filter_size</strong> - <strong>1</strong> )/ <strong>2</strong></strong></li> <li><strong><strong>o/p feature map dimension</strong>= (<strong>i/p feature map dimension</strong> - <strong>filter_size</strong> + <strong>2</strong></strong>...
deep-learning|pytorch|conv-neural-network|zero-padding
0
12,662
64,267,198
Pandas groupby custom aggregate calculation
<p>I have below dataframe which has <code>country wise orders data</code> of <strong>last 2 weeks</strong>. I wanted to calculate <strong>% change(increase or decrease) of food orders</strong> compared to last week on grouping by country, start_date and end_date.</p> <p><a href="https://i.stack.imgur.com/D08jh.png" rel...
<pre><code>df = pd.DataFrame({'start_date':['2020-09-21','2020-09-21','2020-09-28', '2020-09-28'], 'end_date':['2020-09-27', '2020-09-27', '2020-10-04', '2020-10-04'], 'Country':['Russia', 'India','Russia','India'], 'orders':[150,80,100,120]}) df['start_date'] =...
python|pandas|dataframe|group-by|aggregate
1
12,663
64,382,857
Python: How to return value in another cell from the same row if condition meet
<p>Here is my code:</p> <p>def value2(df): if df['condition'] == '-1': return df['value'] else: return 0</p> <p>Data['value2']=Data.apply(value2, axis=1)</p> <p>Here is my original table Data:</p> <pre><code> id condition value 1 1 10 2 0 5 3 -1 20 </code></pre> <p>Here is the desire output...
<p>I think it can be done simply with <code>np.where</code> instead of creating a new function. You can use <code>ge(0)</code> to evaluate values greater than &amp; equal to zero.</p> <pre><code>df['value2'] = np.where(df['condition'].ge(0),0,df['value']) </code></pre>
python|pandas
0
12,664
64,309,511
Ways to speed up Monte Carlo Tree Search in a model-based RL task
<p>This area is still very new to me, so forgive me if I am asking dumb questions. I'm utilizing MCTS to run a model-based reinforcement learning task. Basically I have an agent foraging in a discrete environment, where the agent can see out some number of spaces around it (I'm assuming perfect knowledge of its observa...
<p>I am working on a similar problem and so far the following have helped me:</p> <ol> <li>Make sure you are running tensorflow on you GPU (You will have to install CUDA)</li> <li>Estimate how many steps into the future your agent needs to calculate to still get good results</li> <li>(The one I am currently working on)...
python|tensorflow|monte-carlo-tree-search
0
12,665
64,331,531
Lambda function as callable in .iloc[]
<p>I wish to use <code>Lambda</code> as a callable into <code>.iloc[]</code></p> <p>Input:</p> <pre><code>df = pd.DataFrame({'A':['sdfg',23,'MrkA',34,0,56],'B':['jfgh',23,45,'Mrk1',0,56],\ 'C':['cvb',7,65,65,47,3],'D':['rrb',7,76,3,0,7],\ 'E':['dfg',7,'MrkA',5,12,1],'F':['dfg',7,2,...
<p>Two issues:</p> <ol> <li>Your code sample contains an error df.count('MrkA'). count expects an axis</li> <li>Use lambda c: [c, c+...] to specify desired columns.</li> </ol> <p>Following code based upon finding count of MrKA in the entire DataFrame.</p> <p><strong>Code</strong></p> <pre><code>import pandas as pd df...
python|pandas
2
12,666
47,957,240
Tensorflow file_io.read_file_to_string says unexpected keyword argument binary_mode
<p>I have just started using google cloud ml engine to train my models however, I keep running into a problem when trying to load the data: My data files are in a compressed .npz(numpy archive) format.</p> <pre><code>pathtodata = os.path.join(FLAGS.inputdir,'input_data_1.npz') f = file_io.read_file_to_string(pathtodat...
<p>I had this problem and for me it was a version mismatch problem as Guoqing Xu suggested. To diagnose, have this line in your script:</p> <pre><code>print("TensorFlow version", tf.__version__) </code></pre> <p>Then you can compare the local and remote version. The default version for the ML-engine I believe is 1.0....
python|numpy|tensorflow|google-cloud-ml
0
12,667
49,076,702
Python iterate through columns in a .csv
<p>How can I iterate through columns in a .csv of varying col numbers, performing calculations on the data? Here is what I have, the problem is that I really don't know where to start with this so I haven't tried much and Googling hasn't helped.</p> <pre><code>import pandas as pd file = r'C:\Users\cmcgrath\...' loopd...
<p>You can use <code>.diff()</code> function. This gives the percentage change of value of a row as compared to next row for every column:</p> <pre><code> df = pd.DataFrame({'col1':[1,5,9,14,15,16], 'col2':[2,22,33,54,66,77]}) df.apply(lambda x: x.diff() / x) col1 col2 0 NaN NaN 1 0.8...
pandas
0
12,668
70,191,354
How to Combine a lot of Columns in Pandas?
<p>How do I combine a lot of columns in Pandas?</p> <p>I Have 20 Columns that i want to turn in just one</p> <p>Exemple above w/ 4 Columns:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Type</th> <th>AB1</th> <th>AB2</th> <th>AB3</th> <th>AB4</th> </tr> </thead> <tbody> <tr> <...
<p>You can try something like that:</p> <pre><code>&gt;&gt;&gt; df.melt('ID', value_name='AB').dropna().rename_axis('ID')['AB'].reset_index() ID AB 0 0 AA 1 1 BB 2 2 CC 3 5 HH 4 6 ZZ 5 7 JU </code></pre>
python|pandas
0
12,669
70,131,912
Create new rows based on max rows of a column
<p>So I'm trying to create new data in a time series based on past data. For example I have player data here with each row being stats accumulated at a certain age. I want to create new row in the Dataframe where I increment the max age by one and then take the average of the <code>sa</code> and <code>ga</code> column ...
<p>You can define a function called <code>add_row</code> and pass it to a groupby. I'll assume that if there aren't two years of data for a player, you'll want the columns <code>sa</code> and <code>ga</code> to be populated with <code>NaN</code>:</p> <pre><code>def add_row(x): last_row = x.iloc[-1] last_row['se...
python|pandas|dataframe
3
12,670
70,214,214
How do I calculate time difference of rows passed on column value
<p>I have a pandas dataframe like</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Status</th> <th style="text-align: left;">Time Stamp</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">Passing</td> <td style="text-align: left;">2021-11-25 15:15:36</td>...
<p>below, you build up the column &quot;Downtime&quot;:</p> <pre><code>from datetime import datetime as dt,timedelta as td df.loc[:,'Downtime'] = dt.now() prevPassIdx = 0 prevOldest = dt.now() timestamps = [] for i in range(1, len(df['TimeStamp'])): if df['Status'][i] == 'Passing': if i!=0: ti...
python|pandas|dataframe|timestamp
0
12,671
55,632,432
Formatting duration as "hh:mm:ss" and write to pandas dataframe and to save it as CSV file
<p>I imported data from a CSV file to <code>pandas</code> dataframe.</p> <p>Then, created a duration column by taking difference of 2 <code>datetime</code> columns and which is as follows:</p> <pre><code>df['Drive Time'] = df['Delivered Time'] - df['Pickup Time'] </code></pre> <p>Now, I want to save it back to the C...
<p>If you know that <code>Delivered Time</code> is never greater than 24 hours, you can use this trick:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(columns=['Delivered Time', 'Pickup Time']) df['Delivered Time'] = pd.date_range('2019-01-01 13:00', '2019-01-02 13:00', periods=12) df['Pickup...
python-3.x|pandas|export-to-csv|timedelta
0
12,672
64,932,986
How to read csv with pandas - line format
<p>I have log files which look like this:</p> <pre><code>Datetime;Identifier;Description;Value;Unit 2020-06-18 00:02:55;var1;Gasflow meting 1;7.494;L/min 2020-06-18 00:02:55;var2;Dauwpunt meting 1;-53.119;grC 2020-06-18 00:08:55;var1;Gasflow meting 1;7.494;L/min 2020-06-18 00:08:55;var2;Dauwpunt meting 1;-53.119;...
<pre><code>df = pd.read_csv('filename', sep=';') </code></pre> <p>this will create a dataframe with the data in the file using ; as the sepator.</p>
python|pandas|dataframe|csv
1
12,673
40,128,884
Where to find the source code for pandas DataFrame __add__
<p>I am trying to understand what (how) happens when two <code>pandas.DataFrame</code>s are added/subtracted.</p> <pre><code>import pandas as pd df1 = pd.DataFrame([[1,2], [3,4]]) df2 = pd.DataFrame([[11,12], [13,14]]) df1 + df2 # Which function is called? </code></pre> <p>My understanding is <code>__add__</code...
<p>I think you need check <a href="https://github.com/pandas-dev/pandas/blob/master/pandas/core/ops/methods.py#L72" rel="nofollow noreferrer">this</a>:</p> <pre><code>def add_special_arithmetic_methods(cls, arith_method=None, comp_method=None, bool_method=None, ...
python|pandas
2
12,674
39,617,298
Make a table from 2 columns
<p>I'm fairly new on Python.</p> <p>I have 2 columns on a dataframe, columns are something like: </p> <pre><code>db = pd.read_excel(path_to_file/file.xlsx) db = db.loc[:,['col1','col2']] col1 col2 C 4 C 5 A 1 B 6 B 1 A 2 C 4 </code></pre> <p>I need them to be like this:</p> <pre><code>...
<p>Say your columns are called <code>cat</code> and <code>val</code>:</p> <pre><code>In [26]: df = pd.DataFrame({'cat': ['C', 'C', 'A', 'B', 'B', 'A', 'C'], 'val': [4, 5, 1, 6, 1, 2, 4]}) In [27]: df Out[27]: cat val 0 C 4 1 C 5 2 A 1 3 B 6 4 B 1 5 A 2 6 C 4 </code></pre> <p>Th...
python|pandas|group-by|aggregate|multiple-columns
2
12,675
44,118,359
How to plot specific data from a CSV file with matplotlib
<p>From all the rows of a csv file, I want to keep only two arithmetic values from each row and use them as X-Y pairs for a plot I want to make and later to "feed" them on the code I wrote to cluster them. Any help?</p>
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow noreferrer"><code>numpy.genfromtxt</code></a> to only load specific columns from a csv file, using <code>delimiter=','</code> and the <code>usecols</code> kwarg to select which columns to read.</p> <p>For ...
python|csv|numpy|matplotlib
0
12,676
44,159,422
Scientific notation being read as string in pandas
<p>I'm trying to read a .csv with a column containing numbers in scientific notation. No matter what I do, it ends up reading them as string:</p> <pre><code>def readData(path, cols): types = [str, str, str, str, np.float32] t_dict = {key: value for (key, value) in zip(c, types)} df = pd.read_csv(path, he...
<p>Your preprocess function applies the string transformation after the others were applied. Is this intended behavior?</p> <p>Could you try:</p> <pre><code>df = pd.read_csv(path, header=0, sep=';', encoding='latin1', usecols=cols, chunksize=5000) df["id_client"] = pd.to_numeric(df["id_client"]) </code></pre>
python|csv|pandas|scientific-notation
1
12,677
69,575,093
Modify `pd.read_html()` when reading from a website that requires you to hit "Accept" for Cookies - HTTPError: HTTP Error 500: Internal Server Error?
<p>I have always been able to run this line of code without issues to return the table from the <a href="https://www.bankofengland.co.uk/boeapps/database/Rates.asp?Travel=NIxIRx&amp;into=GBP" rel="nofollow noreferrer">Bank of England</a> as a dataframe:</p> <pre><code>import pandas as pd pd.read_html('https://www.banko...
<p>You need to inject User-Agent</p> <pre><code>import requests import pandas as pd headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'} url = &quot;https://www.bankofengland.co.uk/boeapps/database/Rates.asp?Travel=NIxIRx&amp;in...
python|pandas|web-scraping|beautifulsoup|python-requests
1
12,678
69,662,210
converting list of lists into 1-D numpy array of lists
<p>I have a list of lists (of variable len) that needs to be converted into a numpy array. Example:</p> <pre><code>import numpy as np sample_list = [[&quot;hello&quot;, &quot;world&quot;], [&quot;foo&quot;], [&quot;alpha&quot;, &quot;beta&quot;, &quot;gamma&quot;], []] sample_arr = np.asarray(sample_list) &gt;&gt;&gt...
<p>Yes, it's possible! You can define a function that converts the list of lists into a single list that contains all items as follows.</p> <pre><code>import numpy as np def flatten_list(nested_list): single_list = [] for item in nested_list: single_list.extend(item) return single_list sample_arr =...
python|arrays|numpy
2
12,679
69,385,064
What is the best way to create a custom federated image dataset for TFF in SQLite format?
<p>I went through the source for the CIFAR-100 inbuilt dataset and decided to create a compatible version for the FairFace dataset in order to be able to leverage the other built-in functions without many modifications everywhere once I convert FairFace into a structure very similar to CIFAR-100.</p> <p>I did search ar...
<p>Without more information about LZMA compression is being applied its hard to answer about the size increase.</p> <p>To directly use the same <code>tf.io.FixedLenFeature</code> as the CIFAR-100 dataset from <a href="https://www.tensorflow.org/federated/api_docs/python/tff/simulation/datasets/cifar100/load_data" rel="...
tensorflow|image-classification|tensorflow-federated|federated-learning
0
12,680
69,395,476
Pandas: rank() under groupby() returns "ValueError: Wrong number of items passed 2, placement implies 1"
<p>I have the following dataframe:</p> <pre><code>index, col_name, extra_col 1, item_1, stuff 2, item_2, stuff 3, item_3, stuff 4, item_4, stuff 5, item_5, stuff 6, item_6, stuff 7, item_7, stuff 8, item_8, stuff 9, item_9, stuff </code></pre> <p>on which I'm applying the following transformation:</p> <pre><code>df = d...
<p>Your code produced results of multiple columns when you attempt to assign it to one column <code>xPos</code>. Hence, the error. You can instead rank only on <code>yPos</code> to get the relative serial number in <code>xPos</code>.</p> <p>Change your codes as follows:</p> <pre><code>df = df.sort_values(by = 'col_na...
python|pandas|dataframe|pandas-groupby
2
12,681
69,537,251
Is there a Python analog to matlab's "save()" function?
<p>Say I ran some code that produces multiple arrays as its output. How might I save the entire output in one go as in matlab?</p> <p>In matlab I'd simply say <code>save(data)</code> -&gt; <code>load('data')</code>.</p> <p>Apologies if this is a basic quesiton.</p>
<h2>How to save a python object:</h2> <p>To save objects to file in Python, you can use <code>pickle</code>:</p> <ul> <li>Import the <code>pickle</code> module.</li> <li>Get a file handle in write mode that points to a file path.</li> <li>Use <code>pickle.dump</code> to write the object that we want to save to file via...
python|numpy
0
12,682
54,202,199
my linear regression model wont fit needs 2D array
<p>So I have two 1D arrays which I need to plot and I want to also plot their linear regression model to know their trend, so I have the following code:</p> <pre><code>from brian2 import * %matplotlib inline from sklearn.linear_model import LinearRegression start_scope() reg = LinearRegression() reg.fit(rates, R) re...
<p>As mentioned in the error, you resolve it by using </p> <pre><code>import numpy as np rates=np.array(rates).reshape(-1, 1) reg = LinearRegression() reg.fit(rates, R) reg.coef_ </code></pre> <p>P.S. I am guessing that you have only one feature as the predictor for the regression model. </p>
python|dataframe|sklearn-pandas
1
12,683
53,964,651
Groupby month parameter in Multi-level Index in pandas
<p>I have a large DF which is structured like this. It has multiple stocks in level 0 and Date is level 1. Starts monthly data at 12/31/2004 and continues to 12/31/2017 (not shown).</p> <pre><code> Date DAILY_RETURN A 12/31/2004 NaN 1/31/2005 -8.26 2/28/2005 8.55 3/31/2005 ...
<p>Here it is for a smaller data, using <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow noreferrer">datetime</a></p> <pre><code>import pandas as pd from datetime import datetime df = pd.DataFrame() df['Date'] = ['12/31/2004', '1/31/2005', '12/31/2005', '2/28/2006', '2/28/2007'] df['DAILY_RETUR...
pandas|dataframe|pandas-groupby|multi-index
0
12,684
53,922,893
Concatenate arrays of different sizes row-wise using numpy
<p>I managed to join two csv datasets of same size (i.e. same number of columns) row-wise using np.concatenate. </p> <pre><code>combined = np.concatenate((price1,price2)) </code></pre> <p>How can I join two csv datasets of different sizes (they contain common headers except that one of the datasets has an additional ...
<p>You can use <a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.delete.html" rel="nofollow noreferrer"><code>np.delete</code></a> to remove the extra column and then use <code>np.concatenate</code></p> <pre><code>headers = list('abcdefghik') a = np.arange(len(headers)).reshape(1, -1) #Output:...
python|numpy|join|merge|concatenation
0
12,685
38,092,632
Implementing fminunc function in Tensorflow
<p>Are there Fminunc function in Tensorflow? I'm trying to make my model converge faster and thought I would be able to use fminunc function as in Matlab. (<a href="http://www.mathworks.com/help/optim/ug/fminunc.html" rel="nofollow">http://www.mathworks.com/help/optim/ug/fminunc.html</a>)</p> <p>However I didn't find ...
<p>I don't believe there is a way to call out to a separate non-linear programming solver to solve a minimization problem (which it appears is what fminunc does) from Tensorflow.</p> <p>However, in some sense, finding minima of functions is precisely what Tensorflow's optimizers do (e.g., GradientDescentOptimizer), al...
tensorflow
1
12,686
38,138,722
Accessing objects and tuples from a function
<p>I have a feeling there should be a very easy way to access specific elements from an evaluated function. A very simple example of what I am trying to achieve is</p> <pre><code>def func(x): a = 2*x b = x*x return 1, 10, 100, (a,b) </code></pre> <p>I define a value for x and the function returns a set of...
<p>So you can unpack and ignore:</p> <pre><code>hello, _, _, cello = func(2) </code></pre> <p>But if the result is more complicated you can use <code>operator.itemgetter</code>:</p> <pre><code>from operator import itemgetter hello, cello, bello = itemgetter(0, 3, 15)(func(2)) </code></pre> <p>Or more verbosely:</p>...
python|numpy
3
12,687
38,444,480
How to prevent Pandas from converting my integers to floats when I merge two dataFrames?
<p>Here is my code:</p> <pre><code>import pandas as pd left = pd.DataFrame({'AID': [1, 2, 3, 4], 'D': [2011, 2011,0, 2011], 'R1': [0, 1, 0, 0], 'R2': [1, 0, 0, 0] }) right = pd.DataFrame({'AID': [1, 2, 3, 4], 'D': [2012, 0,0,...
<p>This bug was fixed in pandas <a href="https://pandas.pydata.org/docs/whatsnew/v0.19.0.html#merging-changes" rel="noreferrer">v0.19.0.</a>:</p> <blockquote> <p>Merging will now preserve the dtype of the join keys</p> </blockquote> <p>but note you can convert all columns in a dataframe to <code>int</code> dtype with:<...
python|pandas
7
12,688
66,179,517
Looking for solution on calculating distance between two curves
<p>I need to calculate minimum and maximum distance between two curves (normal) i.e. points from one curve have a perpendicular on another. What i have done so far:</p> <pre><code>from sympy import * from pandas import DataFrame init_printing(use_unicode=False, wrap_line=False) x = Symbol('x') F=x+1 #first curve G=x**...
<p>You are NOT finding the perpendicular distance. You are finding the minimum of the y-values with fixed x values. Your steps need to look like this:</p> <ol> <li>find all perpendicular lines to one of the curves.</li> <li>find the corresponding intersection point on the other curve.</li> <li>calculate the distance.</...
python|dataframe|numpy
0
12,689
46,626,764
TF record corrupted after several successful training epochs
<p>I was training a neural network and had run over all the training data for several epochs successfully. However, the tfrecord corrputed error suddenly came out as follows:</p> <pre><code>File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/lib/io/tf_record.py", line 77, in tf_record_iterator reader.Get...
<p>If someone is facing this problem, the above answer by @nwoye-cid worked for me plus the link below to install everything properly. <br> Also, restart your kernel from scratch if nothing works then only go for other solutions. <br> <a href="https://github.com/tensorflow/models/tree/master/official#requirements" rel=...
tensorflow|tfrecord
0
12,690
58,564,347
cleaning column with equivalent strings
<p>I have a list of football games that I would like to encode. The lain problem is that sometimes team names come in different forms for the same team. For example:</p> <pre><code>data = {'Match': ['FC Milan - Juventus','Juventus - Milan FC ', ' Juventus - Inter', 'Inter - Juventus F.C.', ...
<p>My approach would be to make a canonical list of team names, as descriptive as possible. Then, use difflib to match each team name with its canonical name.</p> <p>This could be optimized a bit, by making a set of team names from data, performing the matching over the entire set, then creating a dictionary from each...
python|pandas
1
12,691
58,469,952
why does numpy int16 give 26 bytes memory space?
<p>I want a fixed size (2 byte/16 bit) integer for further processing. But sys.getsizeof()prints a size of 26, I don't have anything larger or smaller than the max and min int16 can hold. Why is that, how can I fix it? Also when I changed int16 to int32, sys.getsizeof() prints 28 and int64 as 32.</p> <pre><code>def qu...
<p>You're looking at the size of a wrapper object, not the size of an array element. The array elements are 2 bytes, not 26. You can see this by examining the array's <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.itemsize.html#numpy.ndarray.itemsize" rel="nofollow noreferrer"><code>itemsiz...
python|numpy|type-conversion
1
12,692
68,950,535
Problem with deployment of AutoML model via docker using automl model server: "Not found: Op type not registered 'DecodeProtoSparseV4'"
<p>I have trained model in GC AutoML tables and deploying it using this instructions <a href="https://cloud.google.com/automl-tables/docs/model-export" rel="nofollow noreferrer">https://cloud.google.com/automl-tables/docs/model-export</a></p> <p>I have exported model folder with saved_model.pb inside and running docker...
<p>Can you delete the model_server image and try with latest</p> <pre><code>docker run -v `pwd`/my_model:/models/default/0000001 -p 8000:8080 -it gcr.io/cloud-automl-tables-public/model_server:latest </code></pre>
docker|google-cloud-platform|tensorflow-serving|google-cloud-ml|google-cloud-automl
0
12,693
69,024,982
Fastest way to find a Pandas index-column value pair
<p>I have a largish DataFrame with a date index ['Date'] and several columns. One column is a string identifier ['Type'], with related data in the remaining columns. I need to add newData to the DataFrame, but only if the date-type pair (i.e. index-ColumnValue pair) is not already present in the DataFrame. Checking ...
<p>Index value lookup is faster than column value lookup. I don't know the implementation details (it looks like lookup depends on number of rows). Here is a performance comparison:</p> <pre><code>def test_value_matches(df, v1, v2): # return True if v1, v2 found in df columns, else return False if any(df[(df....
python|pandas
1
12,694
44,549,284
groupby object in pandas python
<p>I have a problem using groupby object in pandas.</p> <p>For example, if I have a DataFrame named df, and I select a group in df.grouby('column'), when I try group.column[0] or group['column'][0], it doesn't work.</p> <p>How can I Solve this problem ? </p>
<p>I guess you want to reset the index of the filtered dataframe.</p> <pre><code>for name, subdf in df.groupby("column"): subdf = subdf.reset_index() print (subdf["column"][0]) </code></pre>
python-3.x|pandas
0
12,695
44,608,599
Efficient way for generating N arrays of random numbers between different ranges
<p>I want to generate N arrays of fixed length n of random numbers with numpy, but arrays must have numbers varying between different ranges.</p> <p>So for example, I want to generate N=100 arrays of size n=5 and each array must have its numbers between:</p> <ul> <li>First number between 0 and 10</li> <li>Second numb...
<p>Another possibility. Setting <code>ranges</code> indicates both what the ranges of the individual parts of each arrays must be and how many there are. <code>size</code> is the number of values to sample in each individual part of an array. <code>N</code> is the size of the Monte-Carlo sample. <code>arrays</code> is ...
python|python-2.7|numpy
0
12,696
61,116,702
replace function giving extra character at the end
<p>I'm trying to clean the data of a column in a dataframe by using the replace function. The output keeps giving me an extra character at the end. The more I run the same code, the more characters added at the end. Can anyone please help me on this, please?</p> <pre><code>owner = ['China' 'Chinese' 'Hong Kong' 'Hongk...
<p>In your case you are also replacing substrings (as explained in my comment). As you are trying to replace whole words you should add <code>^</code> and <code>$</code> at the beginning and end of the words respectively. Then, only whole words that match will be replaced. E.g.:</p> <p>The case above:</p> <pre><code>...
python|pandas|replace|where-clause|np
0
12,697
60,981,208
python write() function automatically creates newline in file
<p>I am using the write() to print arrays to a file which will be read by another script, like this:</p> <pre><code>file2write=open("arrays.txt",'w') file2write.write(str(array1)+'\n') file2write.write(str(array2)) file2write.close() </code></pre> <p>I want each array occupying only one line to be read by the other s...
<p>The<code>str(array1)</code> is splitting the numpy array into multiple lines.</p> <p>One way to avoid this is to use <code>str(list(array1))</code></p> <p>Another way is to use <code>numpy.array2string(array1, max_line_width=1000)</code>, or whatever is a reasonable line width.</p>
python|numpy|newline
0
12,698
71,631,237
Repeat and concatenate a DataFrame with constant step value increase
<p>I have a dataframe like the following example:</p> <pre><code> A B C D E F 0 1 4 7 10 13 16 1 2 5 8 11 14 17 2 3 6 9 12 15 18 </code></pre> <p>I want to repeat the all dataframe like it was one block, like I want to repeat the above dataframe 3 times and every element increases by 3 than ...
<pre><code>res = pd.concat([df + 3*i for i in range(3)], ignore_index=True) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; res A B C D E F 0 1 4 7 10 13 16 1 2 5 8 11 14 17 2 3 6 9 12 15 18 3 4 7 10 13 16 19 4 5 8 11 14 17 20 5 6 9 12 15 18 21 6 7 10 1...
python|pandas|dataframe
2
12,699
71,679,164
Extracting Specific Text From value from a nested dictionaries with python
<p>I have the following data structure, which I need to extract the word with <strong>[ft,mi,FT,MI]</strong> of the <strong>state key</strong> and stored in a new key called <strong>distance</strong>.</p> <p><strong>Reproducible Example of my data</strong></p> <pre><code>[ { &quot;id&quot;: 1243, &q...
<p>Please see the code which creates &quot;distance&quot; and gets the value from regex pattern &quot; (.*)&quot;.</p> <pre><code>import re pattern = &quot; (.*)&quot; for a in data: for k in a: #print(k) if &quot;class&quot; in k: #print(a[k]) for l in a[k]: ...
python|pandas|dictionary
-1