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 |
|---|---|---|---|---|---|---|
375,000 | 64,957,026 | numpy 3D array vectorized access with arrays of indices | <p>I have a 3D numpy array A representing a batch of images:
A.shape -> (batch_size, height, width)</p>
<p>I want to access this array using two other arrays Hs,Ws, of size batch_size.
They contain the x index and y index of each image that I want to access.</p>
<p>Example 2 images of size 3x3:</p>
<p>A.shape(2,3,3)... | <p>Do you mean this:</p>
<pre><code>In [6]: A = np.array(A); Hs=np.array(Hs); Ws=np.array(Ws)
In [7]: A.shape
Out[7]: (2, 3, 3)
In [8]: A[np.arange(2), Hs, Ws]
Out[8]: array([ 2, 100])
</code></pre>
<p>When using indexing arrays, they 'broadcast' against each other. Here with (2,),(2,),(2,) the broadcasting is eash.<... | python|arrays|python-3.x|numpy|numpy-ndarray | 2 |
375,001 | 64,768,822 | pandas plot ylabel feature names doesn't fit | <p>I use pandas DataFrame to show feature importance plot.</p>
<p>However some features doesn't fit to ylabel due to their long names.</p>
<pre><code>data = pd.DataFrame({'feature': feature,'importance': importance}).sort_values(by='importance', ascending=False)[0:10]
ax = data.plot(kind='barh', x='feature', y='importa... | <p>You can adjust the <code>left</code> parameter with <a href="https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.subplots_adjust.html" rel="nofollow noreferrer">matplotlib.pyplot.subplots_adjust</a>:</p>
<pre><code>from matplotlib import pyplot as plt
ax = data.plot(kind='barh', x='feature', y='importance')
... | python|pandas|dataframe|matplotlib | 1 |
375,002 | 64,620,236 | Error "ValueError: Graph disconnected" in Keras/Tensorflow | <p>I am getting an error in Tensorflow 2. How can I solve it?</p>
<p>Here is my code (assume all the relevant modules/objects of Keras have been imported):</p>
<pre><code>dense1 = 2**7
dense2 = 2**8
dense3 = 2**9
dropout = 0.8
price_loss = 1
cut_loss = 1
activation= LeakyReLU()
#=======================================... | <p>pay attention to not override the input variables. you overrode <code>color</code>, <code>clarity</code> and <code>x</code> input inside the network</p>
<p>here a possible solution:</p>
<pre><code>dense1 = 2**7
dense2 = 2**8
dense3 = 2**9
dropout = 0.8
price_loss = 1
cut_loss = 1
activation= LeakyReLU()
batch_size =... | python|tensorflow|machine-learning|keras|deep-learning | 0 |
375,003 | 64,921,166 | TenserFlow, How to save style transfer model for later use? | <p>I've been using <a href="https://www.tensorflow.org/tutorials/generative/style_transfer#calculate_style" rel="nofollow noreferrer">this</a> tutorial from TensorFlow's site to create a <a href="https://gist.github.com/daniel-keller/1d36b4e225b161cc375a3c26d27e0be6" rel="nofollow noreferrer">script</a> (python3) that ... | <p>Use <code>model.save()</code> method.</p>
<p>Read this tutorial: <a href="https://www.tensorflow.org/guide/keras/save_and_serialize" rel="nofollow noreferrer">https://www.tensorflow.org/guide/keras/save_and_serialize</a></p> | python|tensorflow|style-transfer | 0 |
375,004 | 64,871,496 | change row values with list comprehension | <p>I have a column where I want to apply a function to each item (row) in that column. When the function is applied, the function returns a <code>result</code>. I want to replace the original value of that cell with the value returned from the function. How can I do so?</p>
<pre><code>result = [f(x) for x in df['col']]... | <p>You can assign back output to column:</p>
<pre><code>df['col'] = [f(x) for x in df['col']]
</code></pre>
<p>What working same like <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer"><code>Series.apply</code></a> or <a href="http://pandas.pydata.org/... | python|python-3.x|pandas|dataframe|data-analysis | 1 |
375,005 | 64,631,665 | What is the difference in RobertaTokenizer() and from_pretrained() way of initialising RobertaTokenizer? | <p>I am a newbie to <strong>huggingface transformers</strong> and facing the below issue in training a <code>RobertaForMaskedLM</code> LM from scratch:</p>
<p>First, I have trained and saved a <code>ByteLevelBPETokenizer</code> as follows:</p>
<pre><code>tokenizer = ByteLevelBPETokenizer()
print('Saving tokenizer at:',... | <p>When you compare the property <code>unique_no_split_tokens</code>, you will see that this is initialized for the <code>from_pretrained</code> tokenizer but not for the other.</p>
<pre class="lang-py prettyprint-override"><code>#from_pretrained
t1.unique_no_split_tokens
['</s>', '<mask>', '<pad>', '... | pytorch|huggingface-transformers|huggingface-tokenizers | 1 |
375,006 | 64,691,551 | How get the predicted label from a Convolution Neural Net in image classification | <p>I have built a <code>CIFAR-10</code> image classification model with <code>Convolution Neural Net</code> or <code>CNNs</code>.
<br>
The model fully completed and has got around 59% accuracy, but my problem is that how to get the predicted label from the model. it can predict these classes(10):</p>
<pre><code>['airpl... | <p>What you are getting are the <code>indexes</code> of the classes, that is the number each class is represented by. In your example, 0 means 'airplane', 1 means 'automobile' and so on.</p>
<p>To get the names you just need to access the class names.</p>
<pre><code>classes=['airplane', 'automobile', 'bird', 'cat', 'de... | python|tensorflow|machine-learning|conv-neural-network|predict | 2 |
375,007 | 64,953,862 | ValueError: cannot handle a non-unique multi-index | <p>I'm trying to concatenate 2 dataframes with hierarchical indexes on axis=1, each one for a different year composed of four quarters (03, 06, 09, 12). Just to give you an idea, the following is for 2018:</p>
<pre><code> 201803 | 201806 | 201809 | 201812
Open ... | <p>My mistake: after counting the indexes with the code:</p>
<pre><code>df.columns.value_counts()
</code></pre>
<p>I've discovered that the issue is in the index level 1, not in the index level 0. The level 1 has more than 100 items and one is duplicated in the json file I was working on.
I have just dropped the duplic... | pandas|dataframe|multi-index | 0 |
375,008 | 64,765,815 | Python Pandas trimming whitespace of column with dynamic name | <p>I have several csv files which I want to process using Pandas.
The complication is that every file has different header of the 1st column (its data should be read as string) and all other columns' values should be read as numbers.</p>
<p>I want to trim the trailing whitespaces in the values of the first column, but ... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer">.iloc[:, 0]</a> to select rows and columns by index position.<br>
In this case <code>.loc[:, 0]</code> means: select all rows and select the first column.<br>
<br>
To remove only the trailing... | python-3.x|pandas | 1 |
375,009 | 64,906,272 | Slice rows with same index number pandas | <p>So i have this dataframe that has same index number for a reason. when i am trying to slice the select rows using the code below i get the error.</p>
<pre><code>df = pd.read_excel('18nov.xlsx')
df = pd.DataFrame(df)
df = df.loc[120:140]
KeyError: 'Cannot get left slice bound for non-unique label
</code></pre>
<p>Da... | <p>You are getting error as their are duplicate entries. But you can achieve your desired result by trying this code.</p>
<pre><code>desired_df=df[(df.index>=120)&(df.index<=140)]
print(desired_df)
Name Age Time
120 krish 19 01:00
130 jack 18 01:00
140 Rick 26 0... | python|pandas | 4 |
375,010 | 64,876,637 | Plotting candlestick and volume candels in Bokeh | <p>I have plotted the candlestick using bokeh. Now i want to plot the volume candles in the same chart?
How do I achieve that. I am reading the data from csv which has open,high,low,close and volume.</p> | <p>This is an extension of the example of the offical documentation for a <a href="https://docs.bokeh.org/en/latest/docs/gallery/candlestick.html" rel="nofollow noreferrer">candlestick</a>.</p>
<p>If you don't have the data yet, run this snippet first.</p>
<pre><code>import bokeh
bokeh.sampledata.download()
</code></pr... | python|pandas-bokeh | 0 |
375,011 | 64,938,549 | How to use NaN values as a hue with a defined color in seaborn barplot | <p>Assuming I have a DataFrame (<code>df</code>) similar to the one in the image below, with missing values in Score column:</p>
<p><a href="https://i.stack.imgur.com/BC784.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BC784.png" alt="enter image description here" /></a></p>
<p>I would like to plot... | <p>How about a quick <code>for</code> loop:</p>
<pre><code>for i,r in df.iterrows():
color = 'k' if np.isnan(r['Score']) else bwrNan(r['Score'])
plt.barh(r['Labels'],r['Pvalue'], color=color, edgecolor='k', alpha=0.6)
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/dOfM0.png" rel="nofollow no... | python|pandas|seaborn|bar-chart|nan | 0 |
375,012 | 64,646,867 | Downloading huggingface pre-trained models | <p>Once I have downloaded a pre-trained model on a Colab Notebook, it disappears after I reset the notebook variables.
Is there a way I can download the model to use it for a second occasion?</p>
<pre><code>tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
</code></pre> | <p>Mount your google drive:</p>
<pre class="lang-py prettyprint-override"><code>from google.colab import drive
drive.mount('/content/drive')
</code></pre>
<p>Do your stuff and save your models:</p>
<pre class="lang-py prettyprint-override"><code>from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pre... | python|nlp|google-colaboratory|huggingface-transformers | 9 |
375,013 | 64,873,796 | How to store result of pip command into Pandas Datafarme | <p>For getting the list of installed libraries, I run the following command in Jupyter Notebook:</p>
<pre><code>!pip list
</code></pre>
<p>and I get the following as output:</p>
<pre><code>Package Version
---------------------------------- ---------
alabaster 0.7.12
a... | <p>We can use <code>os</code> module to create the pip list, then we use <code>pandas.read_csv</code> with <code>\s+</code> as seperator to read the pip list into a dataframe:</p>
<pre class="lang-py prettyprint-override"><code>import os
import pandas as pd
# create pip list txt
os.system('pip list > pip_list.txt')... | python|pandas|dataframe|pip|jupyter-notebook | 2 |
375,014 | 64,796,914 | Zooming in on cartopy map and adding the ocean feature changes the entire plot to blue? | <p>I have a plot of Europe however, for some reason, when I include the <code>ax.add_feature(cartopy.feature.OCEAN)</code> it turns the entire plot blue. I am not sure how to fix this, any help is appreciated!</p>
<p>This only happened when I changed the extent to zoom in more on Europe.</p>
<pre><code>plt.figure(figsi... | <p><code>cartopy.feature.OCEAN</code> is a simple version of more complex <code>NaturalEarthFeature</code> function that is safer to use. Here is a few lines of code that you can use to replace the troublesome part.</p>
<p>Replace</p>
<pre><code>ax.add_feature(cartopy.feature.OCEAN)
</code></pre>
<p>with</p>
<pre><code... | python|matplotlib|geopandas|cartopy | 0 |
375,015 | 64,994,248 | Selecting several different ranges with df.iloc? | <p>So I need to select the 1. and the 4-15. row in an excel dataframe with df.iloc, but I just can't get the correct syntax, now I'm not even sure if its possible to do?
I tried: df.iloc[1,4:15:,:] and df.iloc[1:4:15:,:], I also tried to input the variables as a list of: [1,4,5....15] but neither work, could anyone hel... | <p>Combine list and slices with numpy's <a href="https://numpy.org/doc/stable/reference/generated/numpy.r_.html" rel="nofollow noreferrer"><code>np.r_</code></a></p>
<pre><code>df = df.iloc[np.r_[1,4:15], :]
</code></pre> | python-3.x|pandas | 1 |
375,016 | 64,995,595 | Pandas append function adds new columns | <p>I want to append one row to my dataframe.
Here's the code</p>
<pre><code>import pandas as pd
citiesDataFrame=pd.read_csv('cities.csv')
citiesDataFrame=citiesDataFrame.append({
'LatD': 50,
'"LatM"' : 70,
'"LatS"' : 40,
'"NS"': '"S"',
'"LonD"': 200,
'"LonM"':... | <p>Notice it works for <code>LatD</code>. The reason is your column names aren't identical to the existing names. Seems like a quoting issue. Not sure why you have the double quotes inside the single quotes. Make the column names match and then the append will work.</p> | pandas | 2 |
375,017 | 64,883,903 | Add hours to a timestamp that is formatted as a string | <p>I have a dataframe (df) that has employee start and end times formatted at strings</p>
<pre><code>emp_id|Start|End
001|07:00:00|04:00:00
002|07:30:00|04:30:00
</code></pre>
<p>I want to add two hours to the Start and 2 hours to the End on a set of employees, not all employees. I do this by taking a slice of the mai... | <p>You can use <code>.applymap()</code> on the <code>Start</code> and <code>End</code> columns of your selected subset. Hour addition can be done by string extraction and substitution.</p>
<h2>Code</h2>
<pre><code>df1 = pd.DataFrame({
"emp_id": ['001', '002'],
"Start": ['07:00:00', '07:30:00... | pandas|datetime | 1 |
375,018 | 64,919,831 | Compare two dataframes in pandas | <p>I am a beginner. I have two dataframes in pandas, I would like to identify what are the changes from the original to the new dataframe.</p>
<ul>
<li>Rows: products</li>
<li>Columns: demand for future periods</li>
</ul>
<p>dataframe differences could be: new rows, deleted rows, and changed demand.</p>
<p>Ideally I wo... | <pre><code>def dataframe_difference(df1: DataFrame, df2: DataFrame, which=None):
"""Find rows which are different between two DataFrames."""
comparison_df = df1.merge(
df2,
indicator=True,
how='outer'
)
if which is None:
diff_df = comparison_... | pandas|forecast | 0 |
375,019 | 65,051,834 | Selecting the higher of two data | <p>I'm working with Python Pandas trying to sort some student testing data. On occasion, students will test twice during the same testing window, and I want to save only the highest of the two tests. Here's an example of my dataset.</p>
<p><strong>Name</strong> <strong>Score</strong> <br>
Alice 32 <br>
Alice ... | <p>You can do this with <code>groupby</code>. It works like this:</p>
<pre><code>df.groupby('Name').agg({'Score': 'max'})
</code></pre>
<p>It results in:</p>
<pre><code> Score
Name
Alice 75
Amy 60
John 89
Mark 70
</code></pre>
<p>Btw. in that special setup, you could also use <code>dro... | pandas|dataframe | 0 |
375,020 | 64,763,524 | IndexError: index out of bounds when using 'and' operators | <p>I'm trying to create support and resistance for the stocks chart. However, I got this error.
Here is my code:</p>
<pre><code>def isResistance(df,i):
resistance = df['High'][i] > df['High'][i-1] and df['High'][i] > df['High'][i+1] \
and df['High'][i] > df['High'][i+2] and df['High'][i] > df['High... | <p>In Python, the logic are executed in order, that is,</p>
<p>for <code>a and b and c</code>, a will be evaluated first, then b, and lastly c. If a is <code>False</code>, b and c won't be executed and checked.</p>
<p>Therefore, in your case, since the clauses before <code>df['High'][i] > df['High'][i+3] and df['Hig... | python|pandas | 0 |
375,021 | 64,821,642 | Read CSV with non-ascii character set in pandas and then store in PGSQL | <p>Is there any ways so that I can process non ascii character set reading in pandas df from a csv and after that store in postgresql from pandas df?</p>
<p>I want to keep all the information intact while storing in postgresql.</p> | <p>First of all, I believe your biggest issue is reading the non-ASCII character. However, this has been solved here</p>
<p><a href="https://gist.github.com/glennzw/bc9cdca912bd08d30f66211d538c293d" rel="nofollow noreferrer">https://gist.github.com/glennzw/bc9cdca912bd08d30f66211d538c293d</a></p>
<p>The second part is ... | python|pandas|postgresql|csv|ascii | 0 |
375,022 | 64,734,224 | trying to create a pivot table with pandas and numpy | <p>I'm using the following to try and get a pivot table that multiplies the quantity times the effective price and groups it by Product name:</p>
<p><code>df_sorted.pivot_table(values=['Quantity', 'EffectivePrice'], index=['ProductName'], aggfunc=np.multiply )</code></p>
<p>This is the stack trace - not sure why this i... | <p>My understanding is you cannot apply multi-column operation in pivot table. Maybe using <code>groupby + transform</code> can do. Based on the explanation I recommend this code (I am not sure the expected result is what you want):</p>
<pre><code>df_sorted['TotalPrice'] = df_sorted['Quantity']*df_sorted['EffectivePric... | python|pandas|numpy | 0 |
375,023 | 64,893,652 | Basic Python: an equation and a plot using Jupyter Notebook not working | <p>I keep getting error messages such as invalid syntax, or something is not defined.</p>
<p>here I defined the dependencies</p>
<pre><code>import math #Basic math library
import numpy as np #Numpy -> tools for working with arrays
import matplotlib.pyplot as plt #Matplotlib -> tools for plotting
</code></pre>
<p>... | <p>There are several errors here. First, you're missing a bracket in this line:</p>
<pre><code>A = (2*xi*beta*np.cos(omega_n*t)*math.e**(-xi* omega_n* t))
</code></pre>
<p>Then you're using the variable <code>t</code> in the same line but you haven't defined <code>t</code> yet. You're defining <code>t</code> after this... | python|numpy|matplotlib | 1 |
375,024 | 64,944,066 | Python / Pandas; How to hold value of column until next event | <p>I've been struggling with a problem for a while and haven't been able to find something similar elsewhere. I'm pretty new to Python so appologies if this is pretty straight forward.</p>
<p>So I have a series that I put into a pandas df:</p>
<pre><code>series_ = [0, 0, 0, 1, 0, 0, 0, 4, 4, 0, 0, 0, 0, 0, 1, 1, 0, 0, ... | <p>I am certain, that there is a better way to do this but here is a quick and dirty solution, not sure if speed is important to you...</p>
<pre><code>df['Expected']=df['Values'].replace(0,np.NaN).ffill().replace({1:'NO', 4: 'YES'}).fillna('UNDECLARED')
</code></pre> | python|pandas | 2 |
375,025 | 64,892,229 | How to replace all numbers (with letters/symbols attached, i.e. 43$) in a dataframe column? | <p>I have a dataframe of online comments related to the stock market.
Here's an example:</p>
<pre><code>df = pd.DataFrame({'id': [1, 2, 3],
'comment': ["I made $425",
"I got mine at 42c. per share",
"Stocks saw a... | <p>This should work:</p>
<pre><code>import re
def repl(x):
return re.sub(r'\S*\d+\S*', lambda m: "NUMBER", x)
print(repl("I made 428c with a 52% increase"))
</code></pre>
<p>Output:</p>
<pre><code>I made NUMBER with a NUMBER increase
</code></pre> | python|regex|pandas | 4 |
375,026 | 65,003,159 | Opencv import issue in windows 10 | <p>I have an issue with OpenCV in windows 10. Whenever I try to import OpenCV I get following error.</p>
<pre><code>import cv2
** On entry to DGEBAL parameter number 3 had an illegal value
** On entry to DGEHRD parameter number 2 had an illegal value
** On entry to DORGHR DORGQR parameter number 2 had an illegal... | <p>First, you can find help here: <a href="https://stackoverflow.com/questions/51853018/how-do-i-install-opencv-using-pip">How do I install opencv using pip?</a></p>
<p>Then, try the following steps:</p>
<ol>
<li>Downgrade your current python version to python 3.8. Go there for more informations: <a href="https://stack... | python|numpy|opencv|opencv3.0 | 0 |
375,027 | 64,741,656 | Changing Date Type of Pandas Dataframe | <p>I have a large pandas dataframe. One of my columns is a time column, and it currently looks like this <code>2014-01-01T00:52:00Z</code>.</p>
<p>I want it to look like
<code>1/1/14 00:55</code>, but I have no idea how to make the dates look like this for an entire column of a dataframe?</p>
<hr />
<p>Another example:... | <p>Try making a for loop similar to the following. It should work well for you!</p>
<pre><code>for item in file['Date_Time']:
if item[5] != "0": #Oct, Nov, Dec
newdat = item[5:7] + "/" + item[8:10] + "/" + item[2:4] + " " + item[11:16]
else:
... | python|pandas|string|dataframe|date | 2 |
375,028 | 64,713,684 | how to transform json into dataframe as in a specific format in python | <p>while hitting an API I got JSON response which is as below</p>
<pre><code>res_data_dict= {
"states": [
{
"state_code": "U.P",
"state_name": "UTTAR PRADESH"
},
{
"state_code": "U.K",
... | <pre><code>>>> df = pd.DataFrame([{'State_{}'.format(k.split('_')[1]):v for k,v in dicts.items()} for dicts in res_data_dict['states']])
>>> print(df)
State_code State_name
0 U.P UTTAR PRADESH
1 U.K UTTARAKHAND
</code></pre> | python|json|pandas|dataframe | 0 |
375,029 | 65,037,475 | Merge two data frames by matching one column from the first data frame with two columns from the second data frame | <p>I'm working with two data frames :</p>
<pre><code>df1 = {'Metropolitan area': {0: 'New York City',
1: 'Los Angeles',
2: 'San Francisco Bay Area',
3: 'Chicago',
4: 'Dallas–Fort Worth'},
'token_nhl': {0: 'Devils',
1: 'Ducks',
2: 'Sharks',
3: 'Blackhawks',
4: 'Stars'}}
</code></pre>
<pre><code>df2 = {'... | <p>For this you need to merge two times:</p>
<p>1: renaming columns, becuase after merge pandas is not giving two different columns</p>
<pre><code>df1 = df1.rename(columns = {"token_nhl":"token_nhl_left"})
df2 = df2.rename(columns = {"token_nhl":"token_nhl_right"})
# creating var... | python|pandas|merge | 0 |
375,030 | 64,905,409 | How to select multiple rows that have certain values in numpy? | <p>I have a numpy array that looks like this:</p>
<pre><code>array([(1596207300, 1), (1596207300, 35), (1596207300, 36),
(1596207300, 41), (1596207300, 42), (1596207300, 44),
(1596207300, 49), (1596207300, 50), (1596207300, 51),
(1596207300, 60), (1596207300, 68), (1596207300, 69),
... | <p>You almost got what you want. Just add uTime to the array construction:</p>
<pre><code>[ [uTime, arr[ arr['time'] == uTime ]['value'].max()] for uTime in np.unique( arr['time']
</code></pre>
<p><strong>Update</strong><br />
If you want the entire row to be in the result, I would suggest iterating manually. The follo... | python|numpy | 2 |
375,031 | 64,811,828 | Python - Transpose/Pivot a column based based on a different column | <p>I searched it and indeed I found a lot of similar questions but none of those seemed to answer my case.</p>
<p>I have a pd Dataframe which is a joined table consist of products and the countries in which they are sold.
It's 3000 rows and 50 columns in size.</p>
<p>I'm uploading a photo (only part of the df) of the c... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer">.cumcount()</a> to count the number of countries that a product has.<br>
Then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.htm... | python-3.x|pandas | 2 |
375,032 | 65,012,046 | Split column containing list of tuples into new columns pandas | <p>I have a dataframe:</p>
<pre><code>a b
jon [(age,12), (gender,1), (marital,1)]
sam [(age,34), (gender,1), (marital,2)]
el [(age,14), (gender,2), (marital,1)]
</code></pre>
<p>I want to split the b column into 3 different columns, such that i get</p>
<pre><code>a b1 b2 b3
jon (... | <p>Another (similar) approach that works regardless of the list lengths, update the dataframe, and also handles the column names automatically in one-step:</p>
<pre class="lang-py prettyprint-override"><code>col = 'b' # your target column
df.join(pd.DataFrame(df[col].tolist()).rename(columns=lambda x: col+str(x+1))).dr... | python|pandas | 1 |
375,033 | 64,715,912 | Element-wise operation of columns in Pandas | <p>I want to average element-wise of three columns with different lengths from three different dataframes in Pandas. For example:</p>
<p><strong>df_1:</strong></p>
<pre><code>c1 | c2 | c3
0 | 1 | 2
1 | 2 | 3
2 | 3 | 4
</code></pre>
<p><strong>df_2:</strong></p>
<pre><code>c1 | c2 | c3
1 | 2 | 3
1 | 2 | 3
1 |... | <p>Try the following (given your description, i consider that c1,c2 columns of df_4 are same with df_3):</p>
<pre><code>df_4=df_3.copy()
df_4['c3']=[sum(i)/3 for i in zip(df_1.c3, df_2.c3, df_3.c3)]
</code></pre> | python|pandas|dataframe | 0 |
375,034 | 64,959,037 | What could I do to change the time intervals on the x-axis | <pre><code>import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader as web
#This makes a chart w/3 hour intervals and I would need something like 30 minutes
style.use("ggplot")
start = dt.datetime(2019,4,24)
end = dt.datetime(2019,5,25)
d... | <p>The following example shows how to set the primary scale at 7-day intervals and hide the secondary scale as an example. Other variations can be found on
<a href="https://matplotlib.org/3.2.0/gallery/ticks_and_spines/tick-formatters.html" rel="nofollow noreferrer">formatter page</a> and <a href="https://matplotlib.or... | python|pandas|matplotlib|pandas-datareader | 0 |
375,035 | 64,854,878 | Best way to generate a custom field across a Pandas dataframe using other columns which vary? | <p>I'm looking to generate a personal identifier variable across a dataframe which carries many people. This would exist of 10 characters of their surname, if their surname is under 10 characters it would fill those cells with '2'.</p>
<p>i.e. <code>people['surname'].astype(str).str[0] + people['surname'].astype(str).s... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.ljust.html" rel="nofollow noreferrer"><code>Series.str.ljust</code></a>, get first 10 values by indexing <code>str[:10]</code> with convert column <code>dob</code> to datetimes and extract <code>year, month, day</code>s to new c... | python|pandas|dataframe | 1 |
375,036 | 64,929,443 | Python: Find maxima and discontinuities in a numpy array | <p>I have a question related to finding maxima or more preciseley discontinuities in a <code>numpy</code> array?
My exemplary data looks for example like this</p>
<pre><code>a = np.array([3,4,5,8,7,6,5,4,1])
</code></pre>
<p>In general, I am interested in every maximum/jump in the data. For array <code>a</code>, I want... | <p>Let's try this:</p>
<pre><code>threshold = 1
a = np.array([3, 4, 5, 8, 7, 6, 5, 4, 1])
discontinuities_idx = np.where(abs(np.diff(a))>threshold)[0] + 1
</code></pre>
<p><code>np.diff(a)</code> gives the difference between every component of <code>a</code>:</p>
<pre><code>>>> array([ 1, 1, 3, -1, -1, -1... | python|numpy|scipy|maxima | 4 |
375,037 | 64,985,120 | Setting Date depending on column in dataframe | <p>I want to set a Date depending on the value of the Column <code>sourcename</code>.</p>
<p>I have a Dataframe like this</p>
<pre><code>sourcename date
2008 2020-12-12
2009 2020-12-12
2010 2020-12-12
2012 2020-12-12
</code></pre>
<p>I tried the following</p>
<pre><code>df['date'] = da... | <p>You can iterate over the rows of your dataframe with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.itertuples.html" rel="nofollow noreferrer">df.itertuples()</a> (see below). Then, with each row tuple, you can access the value of each column.</p>
<p>For example, you can use <co... | python|pandas | 0 |
375,038 | 64,648,116 | MATLAB conversion to python? Error in python due to shapes of arrays | <p><em><strong>Question</strong></em></p>
<p>I have a Brownian motion vectorized path given below that I am trying to replicate in python. My problem is that one of the functions, highlighted as the first function in yellow is not working. Instead it is giving me an error (<code>operands could not be broadcast together... | <p>You shouldn't need to import and use <code>mb.repmat</code>. That's used in MATLAB because it doesn't do <code>broadcasting</code> (or at least didn't until recently). To add to the (500,1000) shape <code>W</code>, <code>t</code> needs to be (500,), expended to <code>(500,1)</code>. I'd suggest using <code>linspa... | python|matlab|numpy|matplotlib | 2 |
375,039 | 64,766,752 | Reading from CSV and assigning to variables | <p>I have a pandas DataFrame constructed from a CSV. A column in it has values of different data types.</p>
<p>for example:</p>
<pre><code>data =
val
key
0 6
1 y
2 1.0
</code></pre>
<p>I used</p>
<pre><code>a, b, c = pd.data.val.tolist()
</code></pre>
<p>It treats every value as string.</p>
<p>How d... | <p>You can use <code>pd.to_numeric</code> and then <code>combine_first</code>:</p>
<pre><code>pd.to_numeric(data['val'],errors='coerce').combine_first(data['val']).values.tolist()
</code></pre> | python|pandas|list|dataframe|csv | 0 |
375,040 | 64,649,910 | Is it possible to use the randint() function in numpy without the prefix np? | <p>I am not using</p>
<pre><code>import numpy as np
</code></pre>
<p>Using this -</p>
<pre><code>From numpy import*
</code></pre>
<p>How do I use the np random included functions without the np prefix?</p> | <p>The <code>*</code> import works ok:</p>
<pre><code>In [1]: from numpy import *
In [2]: random
Out[2]: <module 'numpy.random' from '/usr/local/lib/python3.8/dist-packages/numpy/random/__init__.py'>
In [3]: random.randint(10)
Out[3]: 6
</code></pre>
<p>That said, we strongly recommend that you use</p>
<pre><co... | python|numpy|random | 0 |
375,041 | 65,011,613 | How to correctly fetch data from API endpoint with multiple parameter in python? | <p>I tried to fetch data from API endpoints which has multiple parameters and build big pandas dataframe from it. In my attempt, I passed the root URL and iterate the thought API endpoint's multiple parameters with a customized values list. My goal is to fetch the data from specific API endpoints but passing different ... | <p>Two issues:</p>
<ol>
<li>Pandas' <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.append.html" rel="nofollow noreferrer">append</a> returns a new object, it doesn't modify the original dataframe</li>
<li>you append in the outer loop, not in the inner loop</li>
</ol>
<hr />
<pre><code>finaldf = ... | python|json|pandas | 1 |
375,042 | 64,948,696 | For loop not properly appending values | <p>Im trying to store 60 values to x and the next one to the y and then shift it 1 up and store 60 values to x and the next one to the y. But the for loop only works once for the x values the y values some how do get stored properly. And the size of my dataset is not the problem as storing the y values work. It's just ... | <p>I think that you should try to avoid using a for loop, in numpy it is often faster to create masks and work with that. If i understand your question correctly, you want to store 0-59 in x, then 60 in y, then 61-119 in x, then 120 in y and so on.</p>
<p>If that is the correct understanding i would try this instead:<... | python|pandas|numpy | 0 |
375,043 | 64,838,939 | return next(self._sampler_iter) # may raise StopIteration | <p>Instead of using <code>enumerate(data loader)</code> for some reason, I am creating iterator for the data loader. In the <code>while</code> loop shown below, it gives me <code>StopIteration</code> error.</p>
<p>Minimalistic code that depicts the cause:</p>
<pre><code>loader = DataLoader(dataset, batch_size=args.batc... | <p>In Python it's standard in a lot of cases to use exceptions for control flow.</p>
<p>Just wrap it in a try-except:</p>
<pre class="lang-py prettyprint-override"><code>loader = DataLoader(dataset, batch_size=args.batch_size)
dataloader_iter = iter(loader)
try:
while True:
x, y = next(dataloader_iter)
... | python|iterator|pytorch | 2 |
375,044 | 40,311,620 | Break values of one column into two columns | <p>I have a data frame with a column "last_updated", with type datetime64[ns]:</p>
<pre><code>df = pd.DataFrame({'last_updated': ['11/12/14 2:44 PM','5/18/15 11:36 AM','11/12/14
3:09 PM']})
</code></pre>
<p>I want to create two columns out of this one single column - "last_updated_date" and "last_updated_time". Also... | <p>try this:</p>
<pre><code>In [89]: df['last_updated_date'] = pd.to_datetime(df.last_updated).dt.normalize()
In [90]: df['last_updated_time'] = pd.to_datetime(df.last_updated).dt.time
In [91]: df
Out[91]:
last_updated last_updated_date last_updated_time
0 11/12/14 2:44 PM 2014-11-12 14:44:00... | python|pandas|dataframe | 5 |
375,045 | 40,007,120 | Python or Numpy Approach to MATLAB's "cellfun" | <p>Is there a python or numpy approach similar to MATLABs "cellfun"? I want to apply a function to an object which is a MATLAB cell array with ~300k cells of different lengths. </p>
<p>A very simple example:</p>
<pre><code>>>> xx = [(4,2), (1,2,3)]
>>> yy = np.exp(xx)
Traceback (most recent call l... | <p>The most readable/maintainable approach will probably be to use a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p>
<pre><code>yy = [ np.exp(xxi) for xxi in xx ]
</code></pre>
<p>That relies on <code>numpy.exp</code> to implicitly conver... | python|numpy|elementwise-operations | 5 |
375,046 | 40,056,498 | Is it required to build tensorflow from source to use inception? | <p>I have already asked <a href="https://github.com/tensorflow/models/issues/534" rel="nofollow">this question </a> in their repository, but they redirected me here on stack overflow. So, is it required to build <code>tensorflow</code> from the sources to use <code>inception</code>? Or a binary install of <code>tensorf... | <p>It works fine from the binary install. </p>
<p>The <a href="https://github.com/tensorflow/models/" rel="nofollow noreferrer">tensorflow-models repo</a> has an <a href="https://github.com/tensorflow/models/blob/master/slim/slim_walkthrough.ipynb" rel="nofollow noreferrer">example notebook</a> with the boiler-plate ... | tensorflow | 0 |
375,047 | 39,996,575 | Fine-Tuning the Inception model in TensorFlow | <p>I want to use the pre-trained Inception model on my own data-set AND I also want to fine-tune the variables of the Inception model itself.</p>
<p>I have downloaded the pre-trained Inception model for TensorFlow from the following link:</p>
<p><a href="http://download.tensorflow.org/models/image/imagenet/inception-... | <p>I have exactly the same question too. First of all you can fine-tune the whole network according to this: <a href="https://github.com/tensorflow/models/tree/master/inception#adjusting-memory-demands" rel="nofollow">https://github.com/tensorflow/models/tree/master/inception#adjusting-memory-demands</a>
I figured out ... | tensorflow | 2 |
375,048 | 40,174,721 | read excel and convert index to datatimeindex pandas | <p>I read an excel in pandas like this</p>
<pre><code>df = pd.read_excel("Test.xlsx", index_col=[0])
</code></pre>
<p>The dataframe look like this with the index containing a date and time and one column:</p>
<pre><code>01.01.2015 00:15:00 47.2
01.01.2015 00:30:00 46.6
01.01.2015 00:45:00 19.4
01.01.2015... | <p>I think you need add parameter <code>format</code> - see <a href="http://strftime.org/" rel="nofollow">http://strftime.org/</a>:</p>
<pre><code>df.index = pd.to_datetime(df.index, format='%d.%m.%Y %H:%M:%S')
print (df)
a
2015-01-01 00:15:00 47.2
2015-01-01 00:30:00 46.6
2015-01-01 00:45:0... | python|excel|pandas | 1 |
375,049 | 40,133,016 | How to group pandas DataFrame by varying dates? | <p>I am trying to roll up daily data into fiscal quarter data. For example, I have a table with fiscal quarter end dates:</p>
<pre><code>Company Period Quarter_End
M 2016Q1 05/02/2015
M 2016Q2 08/01/2015
M 2016Q3 10/31/2015
M 2016Q4 01/30/2016
WFM 2015Q2 04/12/2015
WFM 2015Q3 07/05/201... | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge_ordered.html" rel="nofollow"><code>merge_ordered</code></a>:</p>
<pre><code>#first convert columns to datetime
df1.Quarter_End = pd.to_datetime(df1.Quarter_End)
df2.Date = pd.to_datetime(df2.Date)
df = pd.merge_ordered... | python|pandas|numpy | 6 |
375,050 | 40,134,637 | Getting column values from multi index data frame pandas | <p>I have a multi index data frame shown below:</p>
<pre><code> 1 2
panning sec panning sec
None 5.0 None 0.0
None 6.0 None 1.0
Panning 7.0 None 2.0
None 8.0 Panning 3.0
None 9.0 None 4.0
Panning 10.0... | <p>consider the <code>pd.DataFrame</code> <code>df</code> in the setup reference below</p>
<p><strong><em>method 1</em></strong> </p>
<ul>
<li><code>xs</code> for cross section</li>
<li><code>any(1)</code> to check if any in row</li>
</ul>
<hr>
<pre><code>df.loc[df.xs('Panning', axis=1, level=1).eq('Panning').any(... | python|pandas | 2 |
375,051 | 40,229,367 | Color coding or labelling the scatter plot of a pandas dataframe? | <p>I have a data frame that I am plotting in pandas: </p>
<pre><code>import pandas as pd
df = pd.read_csv('Test.csv')
df.plot.scatter(x='x',y='y')
</code></pre>
<p>the data frame has 3 columns </p>
<pre><code> x y result
0 2 5 Good
1 3 2 Bad
2 4 1 Bad
3 1 1 Good
4 2 23 Bad
5 1 ... | <p>One approach is to plot twice on the same axes. First we plot only the "good" points, then we plot only the "bad". The trick is to use the <code>ax</code> keyword to the <code>scatter</code> method, as such:</p>
<pre><code>ax = df[df.result == 'Good'].plot.scatter('x', 'y', color='green')
df[df.result == 'Bad'].plo... | python|pandas|matplotlib|plot|dataframe | 4 |
375,052 | 40,049,456 | Exclude between time in pandas | <p>I know that you can select data from <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html" rel="noreferrer">pandas.DatetimeIndex</a> using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.between_time.html" rel="noreferrer">pandas.DataFrame.between_t... | <p>You can combine <code>between_time</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="noreferrer"><code>drop</code></a>:</p>
<pre><code>df2 = df.drop(df.between_time("16:00", "17:00").index)
</code></pre>
<p><strong>Edit</strong></p>
<p>An alternate method ... | python|pandas|numpy | 11 |
375,053 | 39,986,567 | pandas read json not working on Multiple index | <p><strong>Hi i have the below data set in dataframe:</strong></p>
<pre><code>app_id | mob | qtr | amt_fin | net_loss
------------------------------------------------
59101378 | 0 | 20143 | 32387.99 | 1.47
-----------------------------------------------
59101378 | 1 | 20143 | 32387.99 | 3.6
------------... | <p>This generates a correct json string in the orientation/order you're searching for:</p>
<pre><code>df.to_json(orient='records')
</code></pre> | json|python-2.7|pandas | 2 |
375,054 | 40,203,224 | Convert type from BigFloat to Float in python | <p>I'm computing exp using BigFloat library in python. But then I have to compute the inverse of a matrix of BigFloats. I use function <code>numpy.linalg.inv</code> but I'm getting the following error:</p>
<blockquote>
<p>No loop matching the specified signature and casting was found for
ufunc inv</p>
</blockquote... | <p>Considering a 2D list of Bigfloat values (with exp): </p>
<pre><code>from bigfloat import *
import numpy as np
row = 4
col = 4
mat = []
with precision(1000):
for i in range(0,row):
row = []
for j in range(0,col):
row.append(exp(1./(i+j+1)))
mat.append(row)
print "A single el... | python|numpy|bigfloat | 0 |
375,055 | 40,251,256 | Comparing two columns in pandas | <p>I'm trying to compare the values of two columns with the following code:</p>
<pre><code>if df['predicted_spread'] > df['vegas_spread']:
total_bet += 1
</code></pre>
<p>It is returning the following error:</p>
<pre><code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.an... | <p>First, the result of <code>df['predicted_spread'] > df['vegas_spread']</code> is also a Series consist of boolean value, e.g., <code>[True, True, False, ...]</code>, so you get error message <code>The truth value of a Series is ambiguous</code>.</p>
<p>So what should you do? That's depended on your application.<... | python|pandas | 4 |
375,056 | 40,193,795 | How to subplot multiple graphs when calling a function that plots the graph? | <p>I have a function that plots a graph. I can call this graph with different variables to alter the graph. I'd like to call this function multiple times and plot the graphs along side each other but not sure how to do so</p>
<pre><code>def plt_graph(x, graph_title, horiz_label):
df[x].plot(kind='barh')
plt.ti... | <p>In case you know the number of plots you want to produce beforehands, you can first create as many subplots as you need</p>
<pre><code>fig, axes = plt.subplots(nrows=1, ncols=5)
</code></pre>
<p>(in this case 5) and then provide the axes to the function</p>
<pre><code>def plt_graph(x, graph_title, horiz_label, ax... | python|pandas|matplotlib|graph | 1 |
375,057 | 39,998,262 | Append an empty row in dataframe using pandas | <p>I am trying to append an empty row at the end of dataframe but unable to do so, even trying to understand how pandas work with append function and still not getting it.</p>
<p>Here's the code:</p>
<pre><code>import pandas as pd
excel_names = ["ARMANI+EMPORIO+AR0143-book.xlsx"]
excels = [pd.ExcelFile(name) for nam... | <p>Add a new pandas.Series using pandas.DataFrame.append(). </p>
<p>If you wish to specify the name (AKA the "index") of the new row, use:</p>
<pre><code>df.append(pandas.Series(name='NameOfNewRow'))
</code></pre>
<p>If you don't wish to name the new row, use:</p>
<pre><code>df.append(pandas.Series(), ignore_index=... | python|python-2.7|pandas | 71 |
375,058 | 40,134,604 | How to copy content of a numpy matrix to another? | <p>I have a simple question about basics of <code>python</code> and <code>numpy</code> module. I have a function as following:</p>
<pre><code>def update_x_last(self, x):
self.x_last = x
</code></pre>
<p>The class attribute x_last and function argument x are both initialized as of type <code>numpy.matrix</code> an... | <pre><code>import numpy as np
self.x_last = np.copy(x)
</code></pre> | python|numpy|matrix | 3 |
375,059 | 39,882,809 | How can I get a list of the days in a year and follow this form? | <p>This code not work at all, and I'm still confusing with the pandas datetime method...</p>
<pre><code>def date_list():
list = []
for i in pd.date_range(datetime(2016, 1, 1), datetime(2016, 12, 31)):
list.append(datetime[1], datetime[2])
return list
</code></pre>
<p>This is the example for the... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.strftime.html" rel="nofollow"><code>strftime</code></a> to directly do the formatting:</p>
<pre><code>dt_list = pd.date_range('2016-01-01', '2016-12-31').strftime('%m%d')
</code></pre>
<p>Use <a href="http://docs.scipy.... | python|python-3.x|pandas|anaconda|miniconda | 1 |
375,060 | 39,640,936 | parsing a dictionary in a pandas dataframe cell into new row cells (new columns) | <p>I have a Pandas Dataframe that contains one column containing cells containing a dictionary of key:value pairs, like this:</p>
<pre><code>{"name":"Test Thorton","company":"Test Group","address":"10850 Test #325\r\n","city":"Test City","state_province":"CA","postal_code":"95670","country":"USA","email_address":"test... | <p>consider <code>df</code></p>
<pre><code>df = pd.DataFrame([
['a', 'b', 'c', 'd', dict(F='y', G='v')],
['a', 'b', 'c', 'd', dict(F='y', G='v')],
], columns=list('ABCDE'))
df
A B C D E
0 a b c d {'F': 'y', 'G': 'v'}
1 a b c d {'F': 'y', 'G': 'v'}
</code></pre>... | python|pandas|dictionary|append|multiple-columns | 18 |
375,061 | 39,454,542 | Divide two dataframes with python | <p>I have two dataframes : <code>df1</code> and <code>df2</code></p>
<p><code>df1</code>: </p>
<pre><code>TIMESTAMP eq1 eq2 eq3
2016-05-10 13:20:00 40 30 10
2016-05-10 13:40:00 40 10 20
</code></pre>
<p><code>df2</code>: </p>
<pre><code>TIMESTAMP eq1 eq2 eq3
2016-05-10 13:20:00 10 20 30... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="noreferrer"><code>div</code></a>, but before <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="noreferrer"><code>set_index</code></a> from both columns <code>T... | python|pandas|dataframe|multiple-columns|division | 8 |
375,062 | 39,420,430 | ValueError: Domain error in arguments scipy rv_continuous | <p>I was trying to sample random variables subject to a given probability density function (pdf) with scipy.stats.rv_continuous:</p>
<pre><code>class Distribution(stats.rv_continuous):
def _pdf(self,x, _a, _c):
return first_hitting_time(x, _a, _c)
</code></pre>
<p>where the function <em>first_hitting_time... | <p>From <a href="https://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.rv_continuous.html" rel="nofollow">the documentation</a>:</p>
<blockquote>
<h3>Subclassing</h3>
<p>New random variables can be defined by subclassing the rv_continuous
class and re-defining at least the <code>_pdf</code> ... | python|numpy|scipy | 2 |
375,063 | 39,578,656 | Update Pandas dataframe value based on present value | <p>I have a Pandas dataframe with values which should lie between, say, <code>11-100</code>. However, sometimes I'll have values between <code>1-10</code>, and this is because the person who was entering that row used a convention that the value in question should be multiplied by 10. So what I'd like to do is run a Pa... | <p>I think you can use:</p>
<pre><code>my_dataframe[my_dataframe['column_name']<10] *= 10
</code></pre> | python|pandas|indexing|dataframe|multiplication | 3 |
375,064 | 39,469,395 | Tensorflow - shape error when reading data from file | <p>I am trying to train a single layer perceptron (basing my code on <a href="https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/multilayer_perceptron.py" rel="nofollow">this</a>) on the following data file in tensor flow:</p>
<pre><code>1,1,0.05,-1.05
1,1,0.1,-1.1
....
</code><... | <p>Your graph expects X to be a tensor of shape (?, 3). Your example data is of the shape (3,) i.e. a 1 dimensional vector of length 3. Either reshape example to (1, 3), or pass a batch of examples in one shot (e.g. 10, giving a shape of (10, 3))</p> | python|tensorflow | 1 |
375,065 | 39,504,888 | Why would you want to use the state_saving_rnn() function in TensorFlow? | <p>TensorFlow provides the following functions to create an RNN: <code>rnn()</code>, <code>dynamic_rnn()</code>, <code>state_saving_rnn()</code> and <code>bidirectional_rnn()</code>. I am wondering when you would want to use the <code>state_saving_rnn()</code> function?</p>
<p>I am guessing that this is for large RNNs... | <p>There's some documentation on its use with examples here:
<a href="https://www.tensorflow.org/versions/master/api_docs/python/contrib.training.html" rel="nofollow">https://www.tensorflow.org/versions/master/api_docs/python/contrib.training.html</a></p>
<p>Look for the tf.contrib.training.SequenceQueueingStateSaver ... | out-of-memory|tensorflow|recurrent-neural-network | 1 |
375,066 | 39,692,769 | Efficient numpy indexing: Take first N rows of every block of M rows | <pre><code>x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
</code></pre>
<p>I want to grab first 2 rows of array x from every block of 5, result should be:</p>
<pre><code>x[fancy_indexing] = [1,2, 6,7, 11,12]
</code></pre>
<p>It's easy enough to build up an index like that using a for loop.</p>
<p>Is there a on... | <p><strong>Approach #1</strong> Here's a vectorized one-liner using <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow"><code>boolean-indexing</code></a> -</p>
<pre><code>x[np.mod(np.arange(x.size),M)<N]
</code></pre>
<p><strong>Approach #2</strong... | python|numpy|vectorization | 4 |
375,067 | 39,842,623 | get index value from merged pandas time series? | <p>I have various time series pandas data frames which look like:</p>
<p>data['F_NQ'] = </p>
<p><code>OPEN HIGH LOW CLOSE VOL OI P R RINFO
DATE<br>
1996-04-10 12450 12494 12200 12275 2282 627 0 0 0
1996-04-11 12200 12360 12000 12195 1627 920 0 0 0</code></p>
<p>I... | <p>This helped me find the solution... <a href="https://stackoverflow.com/questions/18327624/find-elements-index-in-pandas-series">post</a></p>
<p>I basically need to call: <code>timeSlice.index[-1]</code> to get the last date from whichever time block I've selected.</p> | python|pandas|time-series | 0 |
375,068 | 39,783,045 | discrete distribution in tensorflow | <p>I need discrete distribution in tensorflow。</p>
<ul>
<li>But when I search the documentation from tensorflow,I can only find
normal distribution and so on. </li>
<li>In theano, I often use<br>
theano.tensor.shared_randomstreams.RandomStreams.choice method to<br>
generate discrete distribution。</li>
<li>And also, I ... | <p>Maybe one of these fit the bill?</p>
<pre><code> ds = tf.contrib.distributions
ds.Bernoulli
ds.Binomial
ds.Categorical
ds.Deterministic
ds.OneHotCategorical
</code></pre> | tensorflow | 0 |
375,069 | 39,670,445 | Efficiently select random matrix indices with given probabilities | <p>I have a numpy array of probabilities, such as:</p>
<pre><code>[[0.1, 0, 0.3,],
0.2, 0, 0.05],
0, 0.15, 0.2 ]]
</code></pre>
<p>I want to select an element (e.g., select some indices (i,j)) from this matrix, with probability weighted according to this matrix. The actual matrices this will be working w... | <p>You don't need a list of tuple to choice. Just use a <code>arange(n)</code> array, and convert it back to two dimension by <code>unravel_index()</code>.</p>
<pre><code>import numpy as np
p = np.array(
[[0.1, 0, 0.3,],
[0.2, 0, 0.05],
[0, 0.15, 0.2]]
)
p_flat = p.ravel()
ind = np.arange(len(p_flat))
re... | python|numpy|matrix | 3 |
375,070 | 39,515,152 | Python, Pandas - How can I get something printed in a data range? | <p>I suppose to create a function that allows user pick a range and it will print out the number within the range. however, I keep getting empty DataFrame with my code. can anyone help me? </p>
<p>` import pandas as pd</p>
<pre><code>if __name__ == "__main__":
file_name = "sales_rossetti.xlsx"
# Formatting ... | <p>You're overwriting the <code>your_sales</code> variable as you're reusing it, so you should use a different variable name for the min and max params. You then need to generate a proper boolean mask using <code>loc</code> and enclosing your boolean conditions using parentheses and <code>&</code> to <code>and</cod... | python|pandas|dataframe | 0 |
375,071 | 39,429,297 | Statsmodels fit distribution among 0 and 1 | <p>I am trying to fit a beta distribution that should be defined between 0 and 1 on a data set that only has samples in a subrange. My problem is that using the <code>fit()</code> function will cause the fitted PDF to be defined only between my smallest and largest values.
For instance, if my dataset has samples betwe... | <p>So:</p>
<ul>
<li>you know that the distribution has a=0 and b=1 lower and upper bounds, </li>
<li>but the sample does not contain any values close to these limits.</li>
</ul>
<p>This may happen if the distribution truly is a Beta distribution and the alpha and beta parameters are so that the density near 0 and 1 i... | python|numpy|statistics|statsmodels | 1 |
375,072 | 39,485,848 | Python: How to read csv file with different separators? | <p>This is the first line of my txt.file</p>
<pre><code>0.112296E+02-.121994E-010.158164E-030.158164E-030.000000E+000.340000E+030.328301E-010.000000E+00
</code></pre>
<p>There should be 8 columns, sometimes separated with '-', sometimes with '.'. It's very confusing, I just have to work with the file, I didn't genera... | <p>As stated in comments, this is likely a list of numbers in scientific notation, that aren't separated by anything but simply glued together.
It could be interpreted as:</p>
<pre><code>0.112296E+02
-.121994E-010
.158164E-030
.158164E-030
.000000E+000
.340000E+030
.328301E-010
.000000E+00
</code></pre>
<p>or as </p>... | python|csv|pandas | 4 |
375,073 | 39,457,762 | Python pandas: conditionally select a uniform sample from a dataframe | <p>Say I have a dataframe as such</p>
<pre><code>category1 category2 other_col another_col ....
a 1
a 2
a 2
a 3
a 3
a 1
b 10
b 10
b 10
b 11
b 11
b 11
</code></pre>
<p>I want to obtain a sample from... | <p>This is straightforward when you use the weights keyword in <code>df.sample</code>:</p>
<pre><code>>>> df.sample(n = 5, weights = (df['category2'].value_counts()/len(df['category2']))**-1)
</code></pre>
<p>output:</p>
<pre><code> category1 category2
2 "a" 2
1 "a" 2
10 "b" ... | python|pandas|dataframe|uniform | 2 |
375,074 | 44,252,759 | Pandas: How to concatenate dataframes with different columns? | <p>I tried to find the answer in the official <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="noreferrer">Pandas documentation</a>, but found it more confusing than helpful. Basically I have two dataframes with overlapping, but not identical column lists:</p>
<pre><code>df1:
A B
0 22 34
... | <p>If you just want to concatenate the dataframes you can use.</p>
<pre><code>pd.concat([df1,df2])
</code></pre>
<p>output:</p>
<pre><code> A B C
0 22.0 34 NaN
1 78.0 42 NaN
0 NaN 76 11.0
1 NaN 11 67.0
</code></pre>
<p>Then you can reset_index to recreate a simple incrementing index.</p>
... | python|pandas|dataframe | 11 |
375,075 | 43,997,138 | python class if value == 'ALL' get all value | <p>I'm a newbie to use the class. I encounter a problem when I use the class. the code like this:</p>
<pre><code>import numpy as np
import pandas as pd
class Weather(object):
@property
def url(self):
return self._url
@url.setter
def url(self, value):
if value == 'GZ' or value == 'ZH'... | <p>the simplest way to fix your code is to replace:</p>
<pre><code>for self._url in ['GZ', 'ZH']:
df['val'] = self._url
</code></pre>
<p>with </p>
<pre><code>for url in ['GZ', 'ZH']:
df['val'] = url
</code></pre>
<p>Then it works.</p>
<p>It didn't work, because you are changing your protected attribute <co... | python|class|pandas | 2 |
375,076 | 44,102,261 | Put entries of numpy matrix of differing column length into a 1D array | <p>I'm working in Python. I have a numpy array of length L, called "arr", <code>arr = np.empty(L, dtype = object)</code> where every entry of arr contains another numpy array, but <strong>each with a different length</strong> (that's why I used dtype = object). Now I want to most efficently take every entry contained i... | <p>Sounds like you want to flatten a nested list. That is, your array of arrays is effectively a list of lists. There's a standard Python idiom for that, <code>itertools.chain</code>:</p>
<p>Make a sample array of arrays:</p>
<pre><code>In [828]: arr = np.array([np.arange(i) for i in range(1, 5)])
In [829]: arr
Out... | python|arrays|python-2.7|numpy | 1 |
375,077 | 44,360,084 | Multiplying numpy 2d Array with 1d Array | <p>I have a numpy 2d array:</p>
<pre><code>[[1,1,1],
[1,1,1],
[1,1,1],
[1,1,1]]
</code></pre>
<p>How can I get it so that it multiplies the indices from top to bottom with the corresponding values from a 1d array when the row length of the 2d array is smaller than length of 1d array ? For example multiply above with... | <p><code>*</code> in <code>numpy</code> does element-wise multiplication, for example multiply 1d array by another 1d array:</p>
<pre><code>In [52]: np.array([3,4,5]) * np.array([1,2,3])
Out[52]: array([ 3, 8, 15])
</code></pre>
<p>When you multiply a 2d array by 1d array, same thing happens for every row of 2d arra... | python|arrays|numpy | 2 |
375,078 | 44,134,353 | Input to the command tf.nn.conv2d | <p>I type the following lines in Syder (Anaconda): </p>
<pre><code>inlay=np.random.random(size=(1,10,10,3)).astype('float32')
layer=tf.nn.conv2d(inlay,filter=np.array([1,1,3,1]).astype('float32'),strides=[1,1,1,1],padding='SAME')
</code></pre>
<p><code>'inlay</code>' suppose to be the input for <code>tf.nn.conv2d</co... | <p>I think the problem is your filter, not your input. Currently it is [1, 1, 3, 1], i.e. it has rank 1. I think you meant a filter with kernel width 1, height 1, input dim 3 and output dim 1? If so try something like this:</p>
<pre><code>with tf.variable_scope('conv'):
w = tf.get_variable(
'weights',
... | tensorflow | 0 |
375,079 | 43,990,910 | pandas data frame add columns with function by year and company | <p>I have pandas dataframe called 'sm' like below with many lines, and I want to calculate sales growth rate by company and year and insert it into new column name 'sg'. </p>
<pre><code> fyear ch conm sale ipodate
0 1996 51.705 AAR CORP 589.328 NaN
1 1997 17.222 AAR CORP 782.123 ... | <p>Take a look at <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow noreferrer">pct_change</a></p>
<pre><code>df['sg'] = df[['sale']].pct_change()
</code></pre> | python|pandas|dataframe|slice | 2 |
375,080 | 44,101,981 | Python2.7 numpy Histogram: only length-1 arrays can be converted to Python scalars | <p>I'm trying to create a histogram out of some measurement data. The data have the format below and are saved in a txt-file (altogether about 2000 lines):</p>
<pre><code>17.05.2017 06:22:49;144;-1;550;-12
17.05.2017 06:23:19;143;-1;537;-13
</code></pre>
<p>I would like to write the data in column 3 (550, 537 ...) a... | <p><code>int</code> is a python command which can only work with scalars (i.e. single numbers). This is what the error message tells you. </p>
<p>To convert a numpy array <code>a</code> to integer use </p>
<pre><code>a.astype(int)
</code></pre> | python|arrays|numpy|matplotlib | 0 |
375,081 | 44,124,376 | TensorFlow Dataset Shuffle Each Epoch | <p>In the <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/data" rel="noreferrer">manual</a> on the Dataset class in Tensorflow, it shows how to shuffle the data and how to batch it. However, it's not apparent how one can shuffle the data <em>each epoch</em>. I've tried the below, but th... | <p>My environment: Python 3.6, TensorFlow 1.4.</p>
<p>TensorFlow has added <code>Dataset</code> into <code>tf.data</code>.</p>
<p>You should be cautious with the position of <code>data.shuffle</code>. In your code, the epochs of data has been put into the <code>dataset</code>'s buffer before your <code>shuffle</code>... | python|tensorflow | 11 |
375,082 | 44,130,865 | Pandas: How to read a CSV with newlines in fields? | <p>I have a CSV having newlines inside fields. Like:</p>
<pre><code>COL1,COL2,COL3,COL4
...
1234567,"New Age Music","Line1
Line2
Line3: an so on",123-456-789
...
</code></pre>
<p>So it actually has to be read according to number of columns figured out from header. Is it possible in Pandas/Python?</p>
<p><strong>P.S.... | <p>Pandas is smart enough to do it for you (if it's properly quoted):</p>
<pre><code>In [74]: data
Out[74]: 'COL1,COL2,COL3,COL4\n1234567,"New Age Music","Line1\nLine2\nLine3: an so on",123-456-789'
In [75]: print(data)
COL1,COL2,COL3,COL4
1234567,"New Age Music","Line1
Line2
Line3: an so on",123-456-789
In [76]: pd... | python|pandas | 0 |
375,083 | 43,926,479 | Update a dataframe within apply after using groupby | <p>I have a pandas dataframe that I want to group on and then update the original dataframe using <code>iterrows</code> and <code>set_value</code>. This doesn't appear to work.</p>
<p>Here is an example.</p>
<pre><code>In [1]: def func(df, n):
...: for i, row in df.iterrows():
...: print("Updating {... | <p>The way you have things written, you seem to want the function <code>func(df, n)</code> to modify <code>df</code> in place. But <code>df.groupby('A')</code> (in some sense) creates another set of dataframes (one for each group), so using <code>func()</code> as an argument to <code>df.groupby('A').apply()</code> only... | python|pandas|dataframe | 3 |
375,084 | 44,243,958 | Python pandas dataframe sort_values does not work for second term | <p>I have a dataframe contains sales data</p>
<pre><code>Order ID Order Date Order Priority Order Quantity Sales
928.0 1/1/2009 High 32.0 180.36
10369.0 1/2/2009 Low 43.0 4,083.19
10144.0 1/2/2009 Critical 16.0 137.63
32323... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> with parameter <code>thousands</code> for remove <code>,</code> in floats and <code>parse_dates</code> for convert column to datetime, because values of column <code>Sales</cod... | python-2.7|sorting|pandas|dataframe | 1 |
375,085 | 44,124,483 | How to reshape a DataFrame with a existed column? | <p>I am new to data analysis with python, there is a simple problem here looking for solution. I'm using <code>pandas</code> module.</p>
<p>An example subset of which is shown below:</p>
<p><a href="https://i.stack.imgur.com/qREmU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qREmU.png" alt=""></... | <p>Consider the sample dataframe <code>df</code></p>
<pre><code>df = pd.DataFrame(dict(
record_date=pd.date_range('2015-01-01', periods=24, freq='2M'),
user_id=np.arange(8).repeat(3) + 1,
power_consumption=np.random.randint(100, 500, size=24)
))[['record_date', 'user_id', 'power_consumption... | python|pandas|dataframe | 0 |
375,086 | 44,272,637 | Python Pandas - weekly line graph from yearly data | <p>i have a yearly dataset with energy consumption readings in 30min intervals:</p>
<pre><code> data
2012-11-01 00:00:00 0.177
2012-11-01 00:30:00 0.141
2012-11-01 01:00:00 0.112
2012-11-01 01:30:00 0.082
2012-11-01 02:00:00 0.080
...
</code></pre>
<p>how do i plot a multiple line graph show... | <p><strong>Consider the dataframe <code>df</code> with index <code>tidx</code></strong></p>
<pre><code>tidx = pd.date_range('2016-01-01', '2017-01-01', freq='30T')
df = pd.DataFrame(dict(data=(np.random.randn(len(tidx)) + .01).cumsum()), tidx)
</code></pre>
<p><strong>Create time deltas relative to first date</strong><... | python|pandas|visualization | 4 |
375,087 | 44,313,306 | DCGANs: discriminator getting too strong too quickly to allow generator to learn | <p>I am trying to use <a href="https://github.com/carpedm20/DCGAN-tensorflow/blob/master/model.py" rel="nofollow noreferrer">this version of the DCGAN code</a> (implemented in Tensorflow) with some of my data. I run into the problem of the discriminator becoming too strong way too quickly for generator to learn anythin... | <p>I think there are several ways to decrease discriminator:</p>
<ol>
<li><p>Try leaky_relu and dropout in discriminator function:</p>
<p><code>def leaky_relu(x, alpha, name="leaky_relu"):
return tf.maximum(x, alpha * x , name=name)</code></p></li>
</ol>
<p>Here is entire definition:</p>
<pre><code>def discrimi... | python|tensorflow|dcgan | 5 |
375,088 | 44,252,741 | OpenAI baselines: Why simultaneously use `tf.stop_gradient` and specify `var_list`? | <p>In OpenAI baselines code on <a href="https://github.com/openai/baselines/blob/master/baselines/deepq/simple.py" rel="nofollow noreferrer">DQN</a>, <code>tf.stop_gradient</code> is used on the q values of the target network during building the operation graph to prevent the contributions of the target q values to the... | <p>It's redundant. IMO code reads better - you know that gradient will not flow through that expression, and also you know exactly which variables will be affected.</p>
<p>One would indeed suffice to achieve equivalent effect.</p> | machine-learning|tensorflow|openai-gym | 2 |
375,089 | 43,996,265 | Plot separate learning curves with tensorboard | <p><a href="https://i.stack.imgur.com/58qA1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/58qA1.png" alt="myplot: accuracy"></a></p>
<p>Running a NN model with tensorflow, I want to plot the accuracy score on both training set and test set. However, the plot tensorboard showed me looked weird: the... | <p>You need to create two different summary writers:</p>
<pre><code>train_summary_writer = tf.summary.FileWriter(os.path.join(SUMMARIES_DIR, "train"), sess.graph)
validation_summary_writer = tf.summary.FileWriter(os.path.join(SUMMARIES_DIR, "validation"), sess.graph)
...
train_summary_writer.add_summary(summary_los... | tensorflow|tensorboard | 3 |
375,090 | 44,028,898 | A value is trying to be set on a copy of a slice from a DataFrame. - pandas | <p>I'm new to <code>pandas</code>, and, given a data frame, I was trying to drop some columns that don't accomplish an specific requirement. Researching how to do it, I got to this structure:</p>
<pre><code>df = df.loc[df['DS_FAMILIA_PROD'].isin(['CARTOES', 'CARTÕES'])]
</code></pre>
<p>However, when processing the f... | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html" rel="noreferrer"><code>copy</code></a>, because if you modify values in <code>df</code> later you will find that the modifications do not propagate back to the original data (<code>df</code>), and that Pandas does war... | python|pandas|dataframe | 7 |
375,091 | 43,929,702 | How do I merge 2 dataframes with an index in only 1 dataframe? | <p>I have created 2 panda data frames, the first called 'dfmas' with an index 'Date', then dates, data and 3 moving average columns;</p>
<pre><code> OPEN HIGH LOW LAST ma5 ma8 ma21
Date
11/23/2009 88.84 89.19 88.58 88.97 NaN ... | <p>If dataframes have same length simply add <code>index</code> from original <code>DataFrame</code> for align indexes:</p>
<pre><code>maX = pd.DataFrame(ma, index=df.index).astype('float')
</code></pre> | python|pandas|dataframe|merge|concat | 1 |
375,092 | 44,341,715 | Create large DataFrame with limited resource(RAM) | <p>I have a very large <code>pandas.Series</code> of shape <code>(200000, )</code> containing <code>dict</code>(s) </p>
<pre><code>In[11]: series.head()
Out[12]:
train-1 {u'MI vs KKR': 7788, u'India vs Australia 2nd ...
train-10 {u'England Smarter with the Ball': 92, u'Dhoni...
train-100 {u'Star Spo... | <p>Your dataframe would have 200k*10k=2 billion elements, which roughly translates to 2GB if every element was only 1 byte. Clearly a dense representation won't work, so you need to use a <code>SparseDataFrame</code>:</p>
<pre><code>pd.SparseDataFrame.from_records(small_series.values)
</code></pre> | python|pandas|dataframe|python-2.x | 1 |
375,093 | 44,368,421 | Pandas - Merge Two Dataframes - sum across column | <p>I am trying to merge two dataframes (call them DF1 & DF2) that basically look like the below. My goal is:</p>
<ul>
<li>I want open/close/low/high to all come from DF1. </li>
<li>I want numEvents and Volume = DF1 + DF2. </li>
<li>In cases where DF2 has rows that don't exist in DF1, I want open/close/low/high... | <p>use <code>pd.merge</code>:</p>
<p>it's outer join since you want data from both dfs.</p>
<p><code>pd.merge([A,B],how='outer', on=<mutual_key>)</code></p> | python|pandas | 0 |
375,094 | 44,299,391 | How to do a weighted sum when using groupBy in pandas | <p>I have made up an example because the context and details of my dataset might be too much/unnecessary to explain to deliver my question. While my example might be silly, just know that the example does illustrate what I am hoping to achieve (although at a much much larger scale) and is very important to the given pr... | <p>First multiple columns by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mul.html" rel="nofollow noreferrer"><code>mul</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> + <... | python|pandas|sum|grouping | 4 |
375,095 | 43,985,277 | VisibleDeprecationWarning when creating random array of size 2e5 | <p>I defined var1, var2 as the following arrays:</p>
<pre><code>N = 2e5
var1 = np.array(50 * np.random.normal(size=N) + 0.1)
var2 = np.array(0.01 * np.random.normal(size=N) - 300)
</code></pre>
<p>Upon running these 3 statements in python I get the following two warnings:</p>
<blockquote>
<p><code>__main__:7:</code> Vi... | <p>The <code>size</code> must be an integer. You used <code>N=2e5</code> but that's a float, you can instead just use <code>2 * 10**5</code>:</p>
<pre><code>>>> type(2e5)
float
>>> type(2*10**5)
int
</code></pre>
<p>Or otherwise convert the value to an integer.</p> | python|arrays|numpy|scipy | 3 |
375,096 | 44,075,273 | Tensorflow install: No matching distribution | <p>Already switched to Python 3.5 as Tensorflow only supports 3.5.</p>
<p>I'm trying to use the Tensorflow install guide with the following command: </p>
<pre><code> pip3 install --upgrade tensorflow
</code></pre>
<p>Which results in the following:</p>
<pre><code> Could not find a version that satisfies the requi... | <p>Edit - I miss that it's 32 bit, my answer is for 64 bit.</p>
<p>I had similar problem on windows, I install python 3.5 but got the same error.<br>
This is the steps I did to fix this issue:<br>
first check that you have the exact same problem that I got, by checking your python version, by typing <code>python -V</c... | python|tensorflow|pip|installation | 1 |
375,097 | 44,360,162 | How to access a column in a list of lists in python | <p>I have a 2D array in python modeled by a list of lists and I want to extract the column. I made a quick research and I found a way that uses numpy arrays. The problem is that <strong>I do not want to use numpy</strong> so I don't want to convert my list of lists into a numpy array and then use [:,1] syntax. I tried ... | <p>List comprehensions are your friend when working with lists of lists:</p>
<pre><code>In [111]: alist
Out[111]:
[[0, 1, 2, 3, 4, 5],
[6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]]
In [112]: [row[1] for row in alist]
Out[112]: [1, 7, 13, 19]
</code></pre>
<p>There's also a handy 'idiom... | python|arrays|numpy|multiple-columns | 85 |
375,098 | 44,061,984 | Get latitude & longitude from address geopandas | <p>I have a csv of about 100 million logs. Where one of the column is address and I am trying to get latitude and longitude of the address. I want to try something like mentioned in the Solution , But the <a href="https://stackoverflow.com/questions/31252863/geocoding-using-geopy-and-python">solution</a> given is <code... | <pre><code>import csv
from geopy.geocoders import Nominatim
#if your sites are located in France only you can use the country_bias parameters to restrict search
geolocator = Nominatim(country_bias="France")
with open('c:/temp/input.csv', 'rb') as csvinput:
with open('c:/temp/output.csv', 'wb') as csvoutput:
... | python|pandas|latitude-longitude|arcgis|geopandas | 4 |
375,099 | 43,983,754 | Separate Validation and Training Graph when using queues to feed data to network in Tensorflow | <p>I have been doing lots of research regarding how to use the queues for feeding the data to the network properly. However, I could not find any solutions on the internet.</p>
<p>Currently my code is able to read the training data and perform training, but without validation and testing. Here some important lines for... | <p>Provided you already have your data split into training and validation data sets, all you have to do is create another input pipeline for the validation data. Using the code you provided it should look something like this</p>
<pre>
images, volumes = utils.inputs(FLAGS.train_file_path, FLAGS.batch_size, FLAGS.num_ep... | python|tensorflow|deep-learning | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.