Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
5,700
73,388,298
How to broadcast based on an index specification?
<p>I have the following input and use-case, note the index are arrays and when <code>len</code> is greater than one then means broadcast:</p> <pre><code>import pandas as pd df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=pd.Index([[1], [2, 3], [4]]), ...
<p>You can temporarily set the index as column, <code>explode</code> it and set it back as index:</p> <pre><code>df.reset_index().explode('index').set_index('index') </code></pre> <p>output:</p> <pre><code> a b c index 1 1 2 3 2 4 5 6 3 4 5 6 4 7 8 9 </code></pre>
python|pandas
2
5,701
73,204,249
Output error if there is value under NaN header in Excel file
<p>I have inputed Excel table, that look like this:</p> <pre><code>head_1 head_2 head_3 val_1 val_2 val_3 val_4 val_5 val_6 val_7 </code></pre> <p>I need to output error, because under the NaN header there is value(val_7), but i have no idea how to implement it</p>
<p>try:</p> <pre class="lang-py prettyprint-override"><code>assert sum(['unnamed' in col.lower() for col in df.columns])==0, \ f&quot;Values present in {sum(['unnamed' in col.lower() for col in df_1.columns])} unnamed column(s)&quot; </code></pre> <p>result:</p> <pre class="lang-py prettyprint-override"><code>-----...
python|excel|pandas
0
5,702
73,372,699
More efficient way to build dataset then using lists
<p>I am building a dataset for a squence to point conv network, where each window is moved by one timestep. Basically this loop is doing it:</p> <pre><code> x_train = [] y_train = [] for i in range(window,len(input_train)): x_train.append(input_train[i-window:i].tolist()) y = target_train[i...
<p>You should use <code>pandas</code>. It still might take too much space, but you can try:</p> <pre><code>import pandas as pd # if input_train isn't a pd.Series already input_train = pd.Series(input_train) rolling_data = (w.reset_index(drop=True) for w in input_train.rolling(window)) x_train = pd.DataFrame(rolling_d...
python|list|numpy|keras
1
5,703
60,218,681
Tensorflow always gives me the same result while the outputs are normal
<p>I hope you are having a great day!</p> <p>I recently tried to train a regression model by using TensorFlow and I completed my code by following the instruction in <a href="https://www.tensorflow.org/tutorials/keras/regression" rel="nofollow noreferrer">here</a>.</p> <pre><code>data = pd.read_csv('regret.csv') max_...
<p>You can try this approach as below which split your data set into training and test set before fitting into the model. You can try this approach as below which split your data set into training and test set before fitting into the model.</p> <pre><code> import pandas as pd import keras from keras.m...
python|tensorflow
0
5,704
60,116,419
Extract entity from dataframe using spacy
<p><a href="https://i.stack.imgur.com/2Atis.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2Atis.png" alt="enter image description here"></a>I read contents from excel file using pandas::</p> <pre><code>import pandas as pd df = pd.read_excel("FAM_template_Update 1911274_JS.xlsx" ) df </code></pre> ...
<p>This is expected as <code>Spacy</code> is not prepared to deal with a dataframe as-is. You need to do some work before being able to print the entities. Start by identifying the column that contains the text you want to use <code>nlp</code> on. After that, extract its value as list, and now you're ready to go. Let's...
python|pandas|spacy
5
5,705
65,231,843
Is it possible to only load part of a TensorFlow dataset?
<p>I have a notebook in Google Colab with the following code:</p> <pre><code>batch_size = 64 dataset_name = 'coco/2017_panoptic' tfds_dataset, tfds_info = tfds.load( dataset_name, split='train', with_info=True) </code></pre> <p>I would like to know if it possible to only download part of the dataset (say...
<p>The original question was about how to <em>download</em> a subset of the dataset.</p> <p>And so the answer recommending the use of an argument like <code>split='train[:5%]'</code> as a way of downloading only 5% of the training data is mistaken. It seems that this still downloads the entire dataset, but then only lo...
python|tensorflow|tensorflow-datasets
5
5,706
65,374,774
Python: printed object has a type but returned object is NoneType?
<p>I have a function that returns a tuple containing a NumPy array and a list. At the end of the function I print out the array and the list and both look correct. Then I print their types and these also look correct. But when I return them, I get a NoneType error. I am very confused as to why this is happening. Code b...
<p>You must explicitly return results in the <code>else</code> section in optimize_theta.</p> <pre><code>def optimize_theta(N, R, delta, i, theta, risk): if N == 0: print(&quot;Theta : &quot; + str(type(theta))) print(&quot;= &quot; + str(theta)) print() print(&quot;Risk : &quot; + s...
python|list|typeerror|numpy-ndarray|nonetype
0
5,707
50,144,430
How to use a search window in numpy and retain the maximum value and all the other values to zero
<p>I have a two-dimensional array eg (101 rows and 100 columns). Now I want to create a search window or block of (3 rows x 3 columns) that will move around the array and determine the highest value, select it and retain all other values as zeros using python and numpy. For example </p> <pre><code>x = ([[1,2,3,4,5,6,...
<p>Here is an approach using <code>skimage.util.view_as_blocks</code>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import skimage.util as su &gt;&gt;&gt; &gt;&gt;&gt; def split_axis(N, n): ... q, r = divmod(N, n) ... left = ((np.s_[:q*n], n),) if q else () ... right = ((np.s_[q*n:], r),) i...
python|python-2.7|numpy
1
5,708
49,937,041
pandas exporting to excel without format
<p>I would like to export data from dataframe to an excel, that has already its format-layout (colours, cells, etc.)</p> <p>This code overwrite the all sheet, instead I would like the export data without changing excel layout.</p> <p>is that possible?</p> <h1>Create a Pandas Excel writer using XlsxWriter as the engi...
<p>Do it manually. </p> <p>Example:</p> <pre><code>WB = 'C:/pandas_positioning.xlsx' WS = 'my_data' writer = pd.ExcelWriter(WB, engine='openpyxl') wb = openpyxl.load_workbook(WB) wb.create_sheet(WS) writer.book = wb writer.sheets = {x.title: x for x in wb.worksheets} ws = writer.sheets[WS] for icol, col_name in z...
python|excel|pandas|pandas.excelwriter
1
5,709
50,085,381
pip install giving platform not supported error
<p>I have following python distribution installed.</p> <pre><code>Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32 </code></pre> <p>I downloaded <code>numpy-1.14.3+mkl-cp35-cp35m-win_amd64.whl</code> </p> <p>but upon installing, i got platform not supported error </p> <pr...
<p>I got the error resolved.</p> <p>python 3.6 supports only cp 36. </p>
python-3.x|numpy
0
5,710
64,140,283
I would like to calculate euclidian distance and put it in a list. I recive range error, what I'm missing?
<p>I would like to evaluate the euclidian distance from a fixed point to several points, I want to do it through a loop. Why is not working? I also tried without the '-1' for the range but still not working</p> <pre><code>from scipy.spatial import distance vettore = np.array(np.mat('1 2; 3 4;6,7;8,9;10,12')) posizione...
<p>How about <code>distance_matrix</code>:</p> <pre><code>from scipy.spatial import distance_matrix distance_matrix(vettore, posizione).ravel() </code></pre> <p>Output:</p> <pre><code>array([ 1. , 2.23606798, 6.40312424, 9.21954446, 12.80624847]) </code></pre>
python|numpy|loops
2
5,711
63,904,614
How to change dataframe row index to datetime.date while reading from csv?
<p><code>df.index[0]</code> I want to be <code>datetime.date(2006, 8, 27)</code>.</p> <p>While reading from file, <code>df = pd.read_csv(filePath,index_col=&quot;Date&quot;)</code>, <code>df.index[0]</code> appears as string <code>'2006-08-27'</code>.</p> <p>I tried:</p> <pre><code>dateparser = lambda s: datetime.datet...
<p>As per <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>pandas.read_csv</code></a>, you can also specify the <code>parse_dates = True</code> and the <code>infer_datetime_format = True</code> arguments to have pandas attempt to parse dates from ...
python|pandas|python-datetime
1
5,712
64,128,817
How to plot a min-max fill_between plot from multiple files
<p>Thank you in advance for your help! (Code Below) (<a href="https://github.com/the-datadudes/deepSoilTemperature/blob/master/AllDeepSoilData.zip" rel="nofollow noreferrer">Link to 1st piece of data</a>) (<a href="https://raw.githubusercontent.com/the-datadudes/deepSoilTemperature/master/allStationsDailyAirTemp1.csv...
<ul> <li>See inline notations with the new code</li> <li>Removed <code>plt.style.use('ggplot')</code> because it makes it difficult to see the <code>fill_between</code> colors</li> <li>Also see <a href="https://stackoverflow.com/questions/64067519/how-to-create-a-min-max-lineplot-by-month">How to create a min-max linep...
python|pandas|matplotlib|time-series
1
5,713
46,861,241
Analysis the correlation between age group and survived rate
<pre><code>#First, I divide the age group as follow , # 1. group A: 0-17years old; # 2. group B: 18-35years old # 3. group C: 36-50years old # 4. group D: 51-65years old # 5. group E: above 66 years old #Then I begin to write code extact the CVC data Passenger_Age={"PassengerId":titanic["PassengerId"][...
<p>You can use <code>pd.cut()</code> to group the age, for example:</p> <pre><code>group_names = ['A','B','C','D','E'] bins = [0,17,35,50,65,1000] df['Age_Group'] = pd.cut(df['Age'], bins=bins, labels=group_names) </code></pre> <p>More detail : <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.cu...
python|pandas|csv|numpy
0
5,714
46,767,724
Loop over grouped pandas df and export individual plots
<p><a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#iterating-through-groups" rel="nofollow noreferrer">The documentation</a> seems a little sparse, as to how every element works, so here goes:</p> <p>I have a bunch of files that I would like to iterate over and export a plot, for every single file.</...
<p>I think you need change:</p> <pre><code>for group in df_all.groupby("filename") </code></pre> <p>to:</p> <pre><code>for i, group in df_all.groupby("filename"): plot = sns.regplot(data = group, x = "Dem-Dexc", y = "frame") </code></pre> <p>for unpack <code>tuples</code>.</p> <p>Or select second value of tupl...
python|python-3.x|pandas|pandas-groupby
1
5,715
46,974,717
tf.train.replica_device_setter needed with tf.contrib.learn.Experiment?
<p>I built a distributed tensorflow program using <code>tf.estimator.Estimator</code>, <code>tf.contrib.learn.Experiment</code> and <code>tf.contrib.learn.learn_runner.run</code>. </p> <p>For now it seems to work fine. However, the <a href="https://www.tensorflow.org/deploy/distributed" rel="nofollow noreferrer">tenso...
<p>Variables and ops are defined in <code>tf.estimator.Estimator</code>, which actually uses <code>replica_device_setter</code> (<a href="https://github.com/tensorflow/tensorflow/blob/r1.3/tensorflow/python/estimator/estimator.py#L758" rel="nofollow noreferrer">defined here</a>). As you can see, it assigns variables to...
tensorflow|distributed-computing
0
5,716
63,026,510
How do you plot month and year data to bar chart in matplotlib?
<p>I have data like this that I want to plot by month and year using matplotlib.</p> <pre><code>df = pd.DataFrame({'date':['2018-10-01', '2018-10-05', '2018-10-20','2018-10-21','2018-12-06', '2018-12-16', '2018-12-27', '2019-01-08','2019-01-10','2019-01-11', '2019...
<p>Convert the <code>date</code> column to pandas datetime series, then use <code>groupby</code> on monthly <code>period</code> and aggregate the data using <code>sum</code>, next use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.resample.html" rel="nofollow noreferrer"><code>Data...
python|pandas|datetime|matplotlib
3
5,717
67,690,363
Pandas - Extracting value from a pandas column that has data as a dict
<p>I am trying to extract a details from a pandas column that is a dict as shown below:</p> <pre><code>id, details 101, {'title': '', 'phone': '', 'skype': '', 'real_name': 'Kevin'} 102, {'title': '', 'phone': '', 'skype': '', 'real_name': 'Scott'} </code></pre> <p>Expected output:</...
<p>Use the <code>str</code> accessor:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'id': [101, 102], 'details': [{'title': '', 'phone': '', 'skype': '', 'real_name': 'Kevin'}, {'title': '', 'phone': '', ...
pandas
1
5,718
67,718,805
Find the N smallest values in a pair-wise comparison NxN numpy array?
<p>I have a python NxN numpy pair-wise array (matrix) of double values. Each array element of e.g., (<em>i</em>,<em>j</em>), is a measurement between the <em>i</em> and <em>j</em> item. The diagonal, where <em>i</em>==<em>j</em>, is 1 as it's a pairwise measurement of itself. This also means that the 2D NxN numpy array...
<p>You can use <strong>np.triu_indices</strong> to keep only the values of the upper triangle.</p> <p>Then you can use <strong>np.argpartition</strong> as in the example below.</p> <pre><code>import numpy as np A = np.array([[1.0, 0.1, 0.2, 0.3], [0.1, 1.0, 0.4, 0.5], [0.2, 0.3, 1.0, 0.6], ...
python|numpy|numpy-ndarray|pairwise
3
5,719
61,393,745
Dataframe column: if cell contains string, return a range of digits starting at the index where string was found
<p>I have a dataframe set up where i'm looking to extract out 12 digits starting at "W" in column "test" "W" may fall at different indices throughout the column.</p> <p>Here is what my data looks like:</p> <pre><code> Text Result(I'd like to see) 1 ...
<p>IIUC you want <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html#pandas-series-str-extract" rel="nofollow noreferrer"><code>str.extract</code></a></p> <pre class="lang-py prettyprint-override"><code>df.Text.str.extract(r'(\w\w\/\w\w\/\d{5})') 0 0 WH/MO/0...
python|pandas|dataframe
1
5,720
61,447,388
Heatmap does not show all the rows
<p>I have a dataset with 399 rows (<code>Words</code>) and 5 columns (<code>Dates</code>). I would like to visualise some information by heat maps. I have created a pivot table by using: </p> <pre><code>pd.pivot_table(df, index='Words', columns='Date', values='frequency', aggfunc=np.sum) </code></pre> <p>Output: </p>...
<p>Your output <em>does</em> show all the rows, but the y-labels are reduced as they would overlap too much and be unreadable.</p> <p>If you don't have a frequency column, you can create one and set all values to <code>1</code> with <code>df['frequency'] = 1</code>. The aggregation function will then sum everything up...
python|pandas|seaborn
0
5,721
61,608,030
How can I export status of list of websites as 'Yes' or 'No' to csv from python?
<p>I've imported a list of websites from csv file. I then checked every website to see if this is developed in wordpress or not. Now, I wanted to export wordpress status of every websited as 'Yes' or 'No' into a csv. From this code I could get status as either all 'Yes' or all 'No'. It returns the wordpress status of ...
<pre><code>df['Status'] = 'Yes' </code></pre> <p>sets the variable 'Status' equal to Yes for all rows. If you want to change the value of a specific cell you need to use</p> <pre><code>df.at[i, 'Status'] = 'Yes' </code></pre> <p>Where i is the row index. If you want to add rows as the loop goes on, you can save the...
python|pandas|csv
0
5,722
61,546,771
summation pandas rows and cols for make a plot and a new column
<p>I have a csv file that represents the evolution of a trend in the market. But the data has a repetition of dates and city names like the df I show bellow. </p> <p>I have a pandas dataframe like this:</p> <pre><code> date city confirmed 0 2020-03-12 Florianópolis 2 1 2020-03-13 Florianópolis 2 2 ...
<p>Do you want this?</p> <pre><code>import pandas as pd df = pd.DataFrame([['2020-03-12','Florianópolis',2], ['2020-03-13', 'Florianópolis' , 2], ['2020-03-13', 'Joinville', 1], ['2020-03-14', 'Florianópolis', 2], ['2020-03-14', 'Joinvi...
python|pandas|pandas-groupby
0
5,723
61,449,222
tensorflow-addon not compatible with tensorflow 1.xx
<p>I am working with code that is using tensorflow 1.14. Also they used tensorflow-addons, but as far as I understand tensorflow-addons that are available to install support tensorflow >= 2 only, because when I tried to install an older version of tf addons it says: "Could not find a version that satisfies the require...
<p>According to the <a href="https://github.com/tensorflow/addons" rel="nofollow noreferrer">official repository</a> it only works with TensorFlow 2+. So, there are two options for your situation.</p> <ul> <li><a href="https://www.tensorflow.org/guide/migrate" rel="nofollow noreferrer">Manual upgrade</a> your code to ...
python|tensorflow
0
5,724
61,228,219
Use Pandas dataframe groupby.filter with own function and argument
<p>I would like to filter my dataframe with my own filter function which require an object as argument</p> <pre><code>def my_filter_function(df: pd.DataFrame, my_arg: object) -&gt; bool: </code></pre> <p>I know I can do the following</p> <pre><code>df.groupby('column_name').filter(lambda group_df: my_filter_function...
<p>According to the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.filter.html?highlight=filter#pandas.core.groupby.DataFrameGroupBy.filter" rel="nofollow noreferrer">documentation</a>, you can pass <code>*args</code> and <code>**kwargs</code> to the function. T...
pandas
1
5,725
68,708,984
keep only year month and day in datetime dataframe pandas
<p>Could anyone help me to delete the hours and minutes from this datetimes please? I used this code but it stills returning the same output!</p> <pre><code>data[&quot;expected_Date&quot;]=pd.to_datetime(data[&quot;Last_Date&quot;]+ timedelta(days=365*2.9),format = '%Y-%m-%d') </code></pre> <p>but it returns always th...
<pre><code>data[&quot;expected_Date&quot;].dt.date </code></pre>
python|pandas|datetime|datetime-format|python-datetime
2
5,726
68,525,688
modify column values other than a specific value is not working
<p>I have below dataframe and need to modify profession column except the value has doctor.</p> <pre><code>id firstname lastname email profession 0 100 Ekaterina Skell Ekaterina.Skell@yopmail.com developer 1 101 Judy Vernier Judy.Vernier@yopmail.com police officer 2 102 Tarra Diann Tarra.Dia...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a> with inverted mask by <code>~</code>:</p> <pre><code>#if need compare one scalar value m = src['profession'].eq('doctor') #if need compare by list of values m = s...
python|pandas|dataframe
1
5,727
68,674,468
Can you change the input shape of a trained model in Tensorflow?
<p>I trained a model with the input shape of (224, 224, 3) and I'm trying to change it to (300, 300, 3). For instance:</p> <pre class="lang-py prettyprint-override"><code>resnet50 = tf.keras.models.load_model(path_to_model) model = tf.keras.models.Model([Input(shape=(300, 300, 3))], [resnet50.output]) # or resnet50.in...
<p>This would only work for convolutional layers as they do not care about <code>input_shape</code> because they are just sliding filters. However, if your model is trained on RGB images then also <code>new_input</code> shape should have 3 as channels.</p> <p>Example:</p> <pre><code>first_model = VGG16(weights = None, ...
tensorflow|keras
1
5,728
63,442,203
How to do rolling calculation based a a subsets of rows
<p>I am doing rolling mean analysis on a pandas dataframe,</p> <pre><code>R1_Chr_Name distance count 0 chr1 100 163 1 chr1 101 203 2 chr1 102 194 3 chr1 103 193 4 chr1 104 154 5 chr2 100 150 6 chr2 101 152 7 chr2 102 163 8 chr2 103 161 9 chr2 104 170 10 chr3 100 ...
<p>Check with <code>groupby</code></p> <pre><code>df['ave_count']=df.groupby('R1_Chr_Name')['count'].rolling(3).mean().reset_index(level=0,drop=True) df Out[232]: R1_Chr_Name distance count ave_count 0 chr1 100 163 NaN 1 chr1 101 203 NaN 2 chr1 102...
pandas|rolling-computation
2
5,729
63,713,006
Moving arrays from cells to column headers and row values
<p>With below code:</p> <pre><code>import pandas as pd import numpy as np data = {'Brand': [['Honda', 'Toyota'],['Toyota', 'Honda', 'Ford'],['Ford','Toyota']], 'Price': [[10,12],[15,18,11],[11,12]]} df = pd.DataFrame(data) df </code></pre> <p>I have the following dataframe:</p> <pre><code> Brand ...
<p>Check with</p> <pre><code>s = pd.DataFrame([dict(zip(x, y)) for x , y in zip(df['Brand'], df['Price'])]) Out[403]: Honda Toyota Ford 0 10.0 12 NaN 1 18.0 15 11.0 2 NaN 12 11.0 </code></pre>
python|pandas
4
5,730
53,607,710
How does pytorch calculate matrix pairwise distance? Why isn't 'self' distance not zero?
<p>If this is a naive question, please forgive me, my test code like this:</p> <pre><code>import torch from torch.nn.modules.distance import PairwiseDistance list_1 = [[1., 1.,],[1., 1.]] list_2 = [[1., 1.,],[2., 1.]] mtrxA=torch.tensor(list_1) mtrxB=torch.tensor(list_2) print "A-B distance :",PairwiseDistance(...
<p>Looking at the documentation of <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.PairwiseDistance" rel="noreferrer"><code>nn.PairWiseDistance</code></a>, pytorch expects two 2D tensors of <code>N</code> vectors in <code>D</code> dimensions, and computes the distances between the <code>N</code> pairs. </p> ...
python|pytorch|pairwise-distance
5
5,731
71,941,116
Extract subset of dataframe by value of column - column datatypes are mixed
<p>I have a dataframe like this:</p> <pre><code>Seq Value 20-35-ABCDE 14268142.986651151 21-33-ABEDFD 4204281194.109206 61-72-ASDASD 172970.7123134008912 61-76-ASLDKAS 869238.232460215262 63-72-ASDASD string1 63-76-OIASD 20823821.49471747433 64-76-ASDAS(s)D string1 65-72-AS*AS 876247...
<p>The problem is that your column is storing the values as strings, so they will sort according to string sorting, not numeric sorting. You can sort numerically using the <code>key</code> of <code>DataFrame.sort_values</code>, which also allows you to preserve the string values in that column.</p> <p>Another option wo...
python|pandas
2
5,732
55,236,331
Custom grouping for all possible groups when having missing values
<p>I have a dictionary which represents a set of products. I need to find all duplicate products within these products. If products have same <code>product_type</code>,<code>color</code> and <code>size</code> -> they are duplicates. I could easily group by ('product_type','color','size') if I did not have a problem: so...
<p>You can create all possible keys that are not <code>None</code> and then check which item falls into what key - respecting the <code>None</code>s:</p> <pre><code>data= {'product_id' : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 'product_type': ['shirt', 'shirt', 'shirt', 'shirt', 'shirt', 'hat', ...
python|pandas|python-2.7|dataframe
0
5,733
55,392,261
Merging mulitple rows to one row of a dataframe column
<p>My Current dataframe was like below,</p> <pre><code> 0 1 2 0 HA-567034786 AB-1018724 None 1 AB-6348403 HA-7298656 None </code></pre> <p>After using the <code>apply()</code>, I just make it like,</p> <pre><code>def make_dict(row): s = set(x for x in row if x) ...
<p>Instead <code>apply</code> use dictionary comprehension with flattening:</p> <pre><code>print (df) 0 1 0 HA-567034786 AB-1018724 1 AB-6348403 HA-7298656 def make_dict(row): s = set(x for x in row if x) return {x: list(s - {x}) for x in s} result = {k:v for x in df.values for ...
python|pandas|dataframe
1
5,734
66,949,958
Set row in dataframe as column attributes or meta data
<p>I have a dataframe with survey data, where each column is labelled Q1-Q100. The first row in the dataframe contains the actual questions from the survey (one question for each column). I would like to set that row as an attribute or meta data for each column so I can reference it later.</p> <p>The dataframe looks li...
<p>Why can't you use a loop, simply?</p> <p>If you have the questions stored as a list, you can just do something like:</p> <pre class="lang-py prettyprint-override"><code>for column, question in zip(df.columns, questions): df.attrs[column] = question </code></pre> <p>PS: If you need to have the questions stored in...
python|pandas|dataframe
1
5,735
68,304,336
Plotting a Time Schedule with Business Hour
<p>I'm implementing a time schedule associated with business hour (8am to 5pm) using pd.offsets.CustomBusinessHour and attempting to plot the gantt chart or horizonal bar chart using matplotlib. At this point, I want to cut off the interval between x-axis ticks out of business hour which is unnecessary. It seems like b...
<p>You are trying to develop a Gantt chart and are having issues with spacing of the x axis labels. Your x-axis is representing Timestamps and you want them evenly spaced out (hourly).</p> <p>Axis tick locations are determined by <a href="https://matplotlib.org/stable/gallery/ticks_and_spines/tick-locators.html" rel="n...
python|pandas|matplotlib|scheduling|xticks
0
5,736
68,113,477
pandas how to iteratively count instances of a category by row and reset them when the other category appears?
<p>I have a DataFrame that shows the behavior of a machine. This machine can be in two states: Production or cleaning. Hence, I have a dummy variable called &quot;Production&quot;, that shows 1 when the machine is producing and 0 when it is not. I would like to know the production cycles (how many hours does the machin...
<p>You can first detect the turning points by looking at the points where it <code>diff</code>ers from the previous one. Then cumulative sum of this gives the needed groupings. We <code>transform</code> this with <code>count</code> to get the size of each group:</p> <pre><code>&gt;&gt;&gt; grouper = df.production.diff(...
python|pandas|count|categories
2
5,737
57,011,658
ConvNet with missing output data for weather forecast
<p>I am using ConvNets to build a model to make weather forecast. My input data is 10K samples of a 96x144 matrix (which represents a geographic region) with values of a variable Z (geopotential height) in each point of the grid at a fixed height. If I include 3 different heights (Z is very different in different heigh...
<p>There are various things to consider in order to improve the model:</p> <p><strong>Your choice of loss</strong></p> <p>You could do various things here. Using a L2 loss (squared distance minimization) is an option, where your targets are no rain (0) or rain (1) for each station. Another (more accurate) option woul...
python|tensorflow|keras|neural-network|conv-neural-network
0
5,738
51,064,217
Combine multiple CSV files using Python and Pandas
<p>I have the following code:</p> <pre><code>import glob import pandas as pd allFiles = glob.glob("C:\*.csv") frame = pd.DataFrame() list_ = [] for file_ in allFiles: print file_ df = pd.read_csv(file_,index_col=None, header=0) list_.append(df) frame = pd.concat(list_, sort=False) print list_ frame.to_...
<p>Change <code>frame.to_csv("C:\f.csv")</code> to <code>frame.to_csv("C:\f.csv", index=False)</code></p> <p>See: <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer">pandas.DataFrame.to_csv</a></p>
python|pandas
2
5,739
57,475,296
How can we plot two different dictionaries in a single x axis with one plot up and the other plot down, like a head to tail format?
<p>I need to plot two different dictionaries with varying keys and values (since a few keys might be present in one while missing in other) in a single plot like one on top while the other on the bottom, so that one can compare between the two.</p> <p>Something like what has been given here, but I have two different d...
<p>I recommend to use <code>pandas</code>:</p> <pre><code>import pandas as pd dicts = { 'dict_1': {'1': 10, '2': 20, 'a': 5, 'b': 10}, 'dict_2': {'1': 5, '2': 5, '3': 30, 'a': -5, 'c': -5}} df = pd.DataFrame(dicts) df.plot.bar(subplots=True) # one line to perform the task </code></pre> <p>Result looks kind...
python|pandas|matplotlib|spectra
0
5,740
73,042,044
Panda multiply dataframes using dictionary to map columns
<p>I am looking to multiply element-wise two dataframes with matching indices, using a dictionary to map which columns to multiply together. I can only come up with convoluted ways to do it and I am sure there is a better way, really appreciate the help! thx!</p> <p>df1:</p> <div class="s-table-container"> <table class...
<p>You can use:</p> <pre><code># only if not already the index df1 = df1.set_index('Index') df2 = df2.set_index('Index') df1.mul(df2[df1.columns.map(d)].set_axis(df1.columns, axis=1)) </code></pre> <p>or:</p> <pre><code>df1.mul(df2.loc[df1.index, df1.columns.map(d)].values) </code></pre> <p>output:</p> <pre><code> ...
python|pandas
3
5,741
72,875,433
How to predict time series with limited data
<p>I have a dataset with four columns: date, category, product, rate(%). I would like to be able to forecast the rate for every product in my data. The major issue I'm having is that because products constantly come in an out of production, certain products have very little historical data making predictions difficult....
<p>I think you are looking for a simulation, which you can do based on statistics.</p> <p>You could &quot;randomize&quot; the produced data using a mean rate +- a variance between the mean minus the max value. Never done this, but i think it's doable. I would try the machine learning way to be honest.</p> <p>Anyways, i...
time-series|hierarchical-clustering|hierarchical-bayesian|multivariate-time-series|numpyro
0
5,742
51,535,925
Add two tensor in keras
<p>I got two tensors with shape <code>(X,y)</code> and <code>(y,)</code> respectively, is there any function in keras can add them togher? I only found the <code>K.bias_add</code> in <a href="https://keras.io/backend/" rel="nofollow noreferrer">doc</a> but it does not work. The error is:</p> <pre><code>TypeError: Fail...
<p>Just compute the sum within a <a href="https://keras.io/layers/core/#lambda" rel="nofollow noreferrer">Lambda</a> layer. For example:</p> <pre><code>from keras.layers import Input, Lambda from keras.models import Model X = 3 y = 2 x = Input(shape=(X, y)) b = Input(shape=(y,)) out = Lambda(lambda a: a[0] + a[1])([...
python|tensorflow|keras
2
5,743
51,499,161
Keras layer.weights and layer.get_weights() give different values
<p>My Keras model have Dense layers which I need to access the weights and bias values. I can access them using get_weights() method. It returns me expected sized matrices (57X50 for the weights) for weights and biases.</p> <pre><code>model.layers[0].get_weights()[0] </code></pre> <p>However the following code snippe...
<p>With <code>init_op</code>, you initialize all trainable variables, which means zeros for biases and random values for the other weights of your model. Try:</p> <pre><code>import keras.backend as K with K.get_session() as sess: print(sess.run(model.layers[0].weights[0])) </code></pre>
tensorflow|keras
2
5,744
71,056,462
Groupby A column and bring up the A value, only if the B values differ from the other ones, including nulls
<p>I have this example, dataset:</p> <pre><code> A B 11 A 11 V 11 C 12 A 12 A 12 A 12 A 13 A 13 A 13 B 13 B 14 C 14 C 14 14 </code></pre> <p>And I want it to return, the grouped A values, that has different values on the B column. So in this example, the expected output is:</p> <pre><cod...
<p>You could <code>groupby</code> &quot;A&quot; and use <code>nunique</code> to count the number of unique &quot;B&quot;s per &quot;A&quot;. Then evaluate if it's greater than 1 to filter the &quot;A&quot;s that have more than one corresponding &quot;B&quot;:</p> <pre><code>msk = df.groupby('A')['B'].nunique()&gt;1 out...
python|pandas|dataframe|pandas-groupby
2
5,745
70,752,223
Python Pandas - Calculate total mean, group by field, then calculate grouped means and append
<p>Let's say I have a pd.DataFrame with the columns &quot;dir&quot; and &quot;speed&quot;:</p> <pre><code>import pandas as pd df = pd.DataFrame({'dir': ['fwd', 'fwd', 'fwd', 'bwd', 'bwd'], 'speed': [10, 5, 1, 6, 8]}) # or with more columns: df = pd.DataFrame({'dir': ['fwd', 'fwd', 'fwd', 'bwd', 'bwd'...
<p>You can aggregate <code>median</code> and then add new column for <code>median</code>:</p> <pre><code>f = lambda x: f'median_{x}_speed' df1=df.groupby('dir')[['speed']].median().rename(f).T.assign(median = df['speed'].median()) print (df1) dir median_bwd_speed median_fwd_speed median speed 7 ...
python|pandas|dataframe
1
5,746
70,842,345
When I try to replace strings out of pandas series from a dictionary some half strings get converted into some value that resonates with half string
<h1>My try is to replace keys in strings of pandas dataframe series in a loop from a dictionary.</h1> <h1>My code is botching up the replace in one instance where there are common characters of two replaced with values candidates.</h1> <pre><code>mapped_lookup={'Ardy=': '0', 'is=': '1', 'Hais':'22', 'the=': '2', 'be...
<p>Here is the revised code after reordering the dictionary keys in mapped_lookup.</p> <pre><code>import pandas as pd import numpy as np mapped_lookup={'Ardy=': '0', 'HAis':'22', 'is=': '1', 'the=': '2', 'best=': '3', 'est=': '4', 'est2=': '5'} df = pd.DataFrame(columns=['Header']) df['Header'] = pd.Series([&q...
python|regex|pandas|string|replace
1
5,747
51,733,223
Getting error while converting to pandas dataframe from a list
<p>I am trying to convert a list of values to a dataframe in a single row so the output should be a pandas dataframe with single row but getting <code>object of type 'int' has no len()</code> I tried other SO posts but same error.</p> <pre><code>metadata = [var1, var2, var3, var4, var5] df = pd.DataFrame(columns=['co...
<pre><code>import numpy as np import pandas as pd metadata = ["var1", "var2", "var3", "var4", "var5"] arr = np.array(metadata).reshape(1,5) df = pd.DataFrame(columns=['col1', 'col2', 'col3', 'col4', 'col5'], data = arr) </code></pre> <p>Output:</p> <pre><code> col1 col2 col3 col4 col5 0 var1 var2 var3 ...
python|list|pandas|dataframe
0
5,748
51,851,684
Easier way to combine all these binary columns into categorical columns?
<p>These are the categories that I want to change to one columns. The values in each list are the current binary columns present in the dataframe. </p> <pre><code>housesitu = ['tipovivi1', 'tipovivi2', 'tipovivi3', 'tipovivi4', 'tipovivi5'] educlevels = ['instlevel1', 'instlevel2', 'instlevel3', 'instlevel4', 'instlev...
<p>I can only think about a <code>groupby</code> with <code>idxmax</code>, since you column named as XXXddd </p> <pre><code>df.groupby(df.columns.to_series().str.replace('\d+',''),axis=1).idxmax(1) Out[1100]: A B 0 A2 B2 1 A1 B1 2 A1 B1 </code></pre> <p>Data Input </p> <pre><code>df=pd.DataFrame({'A1':[...
python|pandas
1
5,749
51,702,229
numpy mask using np.where then replace values
<p>I've got two 2-D numpy arrays with same shape, let's say (10,6).</p> <p>The first array <code>x</code> is full of some meaningful float numbers.</p> <pre><code>x = np.arange(60).reshape(-1,6) </code></pre> <p>The second array <code>a</code> is sparse array, with each row contains ONLY 2 non-zero values.</p> <pre...
<p>Thanks to the comment by @Divakar, the problem happens because the shapes of the two variables on both side of the assignment mark <code>=</code> are different.</p> <p>To the left, the expression <code>x[np.where(a!=0)]</code> or <code>x[a!=0]</code> or <code>x[np.nonzero(a)]</code> are not structured, which has a ...
python|arrays|numpy
1
5,750
35,875,617
Why the cross spectra is differ in mlab and scipy.signal?
<p>I have two signals</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib import mlab import mpld3 from scipy import signal mpld3.enable_notebook() nfft = 256 dt = 0.01 t = np.arange(0, 30, dt) nse1 = np.random.randn(len(t)) * 0.1 # white noise 1 nse2 = np.random.randn(len...
<p>Because the two functions have different default values for some parameters.</p> <p>For example, if you pass in to <code>plt.cohere()</code> the option <code>noverlap=128</code> you get an almost perfect match with the <code>numpy.signal()</code> solution: <a href="https://i.stack.imgur.com/5FQil.png" rel="nofollow...
python|numpy|matplotlib|scipy|signal-processing
4
5,751
37,279,260
Why doesn't pandas allow a categorical column to be used in groupby?
<p>I would like to create a custom sorted DataFrame. To do this I have used <code>pandas.Categorical()</code> however if I then use the result of this in a groupby <code>NAN</code> values are returned.</p> <pre><code># import the pandas module import pandas as pd # Create an example dataframe raw_data = {'Date': ['2...
<p><code>as_index=False</code> is messing something up. If I run just:</p> <pre><code>dfs = df.groupby(['Date','Portfolio']).sum() </code></pre> <p>I get:</p> <pre><code> Duration Yield Date Portfolio 2016-05-13 C 18 6.0 B 10 ...
python|pandas
1
5,752
37,226,330
Deploy Tensorflow on a web server with Flask
<p>I am trying to deploy a Flask web app with tensorflow on an AWS server ( AMI ID: Deep Learning (ami-77e0da1d)), for an image classification app.</p> <p>When I use tensorflow in the server, it works normally, but when I try to use it with the app, I get: </p> <blockquote> <p>No data received ERR_EMPTY_RESPONSE </...
<p>The value of <code>LD_LIBRARY_PATH</code> is being cleared before starting your web app starts, for security reasons. See for example <a href="https://stackoverflow.com/q/28712022/3574081">this question</a>, which observes that the value of <code>os.environ['LD_LIBRARY_PATH']</code> is empty inside the Flask app, ev...
apache|flask|tensorflow|tensorflow-serving
1
5,753
38,012,050
Replacing column of inf values with 0
<p>I am new to numpy but i cannot seem to get this piece of code to work.</p> <pre><code>item3.apply(lambda x : (x[np.isneginf(x)] = 0)) </code></pre> <p>item3 is a vector of numpy arrays with 300 dimensions in each array.</p> <p>The error thrown is invalid syntax. How do i get to achieve this function.</p> <p>Howe...
<p>You could make something like that :</p> <pre><code>import numpy as np from numpy import inf x = np.array([inf, inf, 0]) # Create array with inf values print x # Show x array x[x == inf] = 0 # Replace inf by 0 print x # Show the result </code></pre> <p><a href="https://i.stack.imgur.com/YbshY.png" rel="nofollo...
python|numpy
0
5,754
37,610,757
How to remove nodes from TensorFlow graph?
<p>I need to write a program where part of the TensorFlow nodes need to keep being there storing some global information(mainly variables and summaries) while the other part need to be changed/reorganized as program runs. </p> <p>The way I do now is to reconstruct the whole graph in every iteration. But then, I have t...
<p>Changing the structure of TensorFlow graphs isn't really possible. Specifically, there isn't a clean way to remove nodes from a graph, so removing a subgraph and adding another isn't practical. (I've tried this, and it involves surgery on the internals. Ultimately, it's way more effort than it's worth, and you're as...
neural-network|tensorflow
7
5,755
64,617,223
Using entrywise sum of boolean arrays as inclusive `or`
<p>I would like to compare many <em>m</em>-by-<em>n</em> boolean numpy arrays and get an array of the same shape whose entries are <code>True</code> if the corresponding entry in at least one of the inputs is <code>True</code>.</p> <p>The easiest way I've found to do this is:</p> <pre><code>In [5]: import numpy as np ...
<p>You can use <code>np.logical_or</code></p> <pre><code>a = np.array([True, False, True]) b = np.array([True, True, False]) np.logical_or(a,b) </code></pre> <p>it also works for <code>(m,n)</code> arrays</p> <pre><code>a = np.random.rand(3,4) &lt; 0.5 b = np.random.rand(3,4) &lt; 0.5 print('a\n',a) print('b\n',b) np.l...
python|numpy
1
5,756
47,564,932
how to show all the x-axis label with panda/matplotlib
<p>I make a simple scraper for a company's stock price history. The problem I have is when I use matplotlib to make graph, most of the x-axis labels (date in this case) are missing. How can I force pandas/matplotlib to display all labels?</p> <pre><code>import pandas as pd import urllib.request from bs4 import Beautif...
<p>The formatting with <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="nofollow noreferrer">pandas.DataFrame.plot</a> is rarely perfect in my experience. The function returns an np.array of the axes. You can just use <strong>set_xlabel()</strong> on each axis after. </p>...
python|pandas|matplotlib
-1
5,757
49,288,651
Tensorflow: gradients are zero for LSTM and GradientDescentOptimizer
<p>Gradients which are computed by GradientDescentOptimizer for LSTM network are always zero. They are zero even on the first step, so, I think it is not vanishing gradient problem. The same issue happens for AdamOptimizer.</p> <p>I have reduced input to one point of time series and label (expected output) to just nex...
<p>Implementation is correct. Input and label results into vanishing gradients.</p> <p>If input and label are as follows, gradients are not zeros.</p> <pre><code>input = [[3], [0.70089], [0.70089], [0.70086], [0.70089], [0.70071], [0.70071], [0.7007], [0.70071]] label = [[10], [0.70086], [0.7009], [0.70084], [0.70092...
python|tensorflow|machine-learning|lstm|recurrent-neural-network
0
5,758
49,034,291
Integer multiplication result is negative
<p>My multiplication of two positive integers results in a negative value and thus i cant calculate the sqrt but get a <code>math domain error</code>. My variables can be of size 10^10 and higher.</p> <pre><code>sum = math.sqrt ( np.power( x , 2 ) * np.power( y , 2 ) ) </code></pre> <p>Which dtype works for my needs ...
<p>As stated in the comments your problem is that the result is overflowing and becoming negative due to using integer variables.</p> <p>The solution that should solve your issue should be to convert the numbers to floats (Before the operations do: <code>x=x.astype(np.float32)</code>) and then do the operations.</p> ...
python|python-3.x|numpy
0
5,759
70,036,839
How to use "load_model" in Keras after trained using as metric "tf.keras.metrics.AUC"?
<p>After training using that metric on my <code>model.fit()</code>. When I try to load the model using &quot;load_model&quot;. It don't recognize the metric AUC, so I add it on <code>custom_objects={&quot;auc&quot;:AUC}</code>.</p> <p>I get this error:</p> <blockquote> <p>ValueError: Unknown metric function: {'class_na...
<p>I found the answer. When you have no defined metrics, you can load the model without compiling it. Just set <code>compile=False</code> like this:</p> <pre><code>model.compile(..., metrics=[&quot;accuracy&quot;, AUC(name=&quot;auc&quot;, curve=&quot;PR&quot;)] load_model(checkpoint, custom_objects={&quot;auc&quot;: A...
python|tensorflow|keras|metrics|auc
0
5,760
56,131,080
How to save a part of a network?
<p>I have made an autoencoder, consisting of an encoder and a decoder part. I have managed to get the encoder separated from the full network, but I have some troubles with the decoder part. </p> <p>This part works:</p> <pre><code>encoder = tf.keras.Model(inputs=autoencoder.input, outputs=autoencoder.layers[5].output...
<p>I would approach the problem the other way:</p> <pre class="lang-py prettyprint-override"><code># Encoder model: encoder_input = Input(...) # Encoder Hidden Layers encoded = Dense()(...) encoder_model = Model(inputs=[encoder_input], outputs=encoded) # Decoder model: decoder_input = Input(...) # Decoder Hidden L...
tensorflow|keras
0
5,761
55,957,147
Reorder columns in groups by number embedded in column name?
<p>I have a very large dataframe with 1,000 columns. The first few columns occur only once, denoting a customer. The next few columns are representative of multiple encounters with the customer, with an underscore and the number encounter. Every additional encounter adds a new column, so there is NOT a fixed number of ...
<p>You need to split you column on '_' then convert to int:</p> <pre><code>c = ['A_1','A_10','A_2','A_3','B_1','B_10','B_2','B_3'] df = pd.DataFrame(np.random.randint(0,100,(2,8)), columns = c) df.reindex(sorted(df.columns, key = lambda x: int(x.split('_')[1])), axis=1) </code></pre> <p>Output:</p> <pre><code> A_...
python-3.x|pandas
1
5,762
64,651,866
Create DataFrame from list of dicts in Pandas series
<p>I have a pandas series with string data structured like this for each &quot;row&quot;:</p> <pre><code>[&quot;[{'id': 240, 'name': 'travolta'}, {'id': 378, 'name': 'suleimani'}, {'id': 730, 'name': 'pearson'}, {'id': 1563, 'name': 'googenhaim'}, {'id': 1787, 'name': 'al_munir'}, {'id': 10183, 'name': 'googenhaim'}, {...
<p>You can use json module to load that structure:</p> <pre><code>import json data = [&quot;[{'id': 240, 'name': 'travolta'}, {'id': 378, 'name': 'suleimani'}, {'id': 730, 'name': 'pearson'}, {'id': 1563, 'name': 'googenhaim'}, {'id': 1787, 'name': 'al_munir'}, {'id': 10183, 'name': 'googenhaim'}, {'id': 13072, 'name'...
python|pandas
2
5,763
65,013,199
StopIteration error while trying to build data input for a model
<pre><code>from __future__ import print_function import tensorflow as tf import os #Dataset Parameters - CHANGE HERE MODE = 'folder' # or 'file', if you choose a plain text file (see above). DATASET_PATH = &quot;D:\\Downloads\\Work\\&quot; # the dataset file or root folder path. # Image Parameters N_CLASSES = 7 # CH...
<p><code>StopIteration</code> means the iterable is empty, you also get it in a case like this:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; next(iter([])) Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; StopIteration </code></pre> <p>Most likely the pa...
python|tensorflow|stopiteration
0
5,764
64,747,422
iterate on non zero columns to get cost
<p>I have a data with weekly sale quantity, amount and cost and i want to find out the cost price for each product row by dividing the weekly quantity sold with the cost, however it is possible that the latest row has zero values, so i wish to skip it i it has zero value and use the previous week to calculate for the c...
<p>The problem arises when there is a division by zero. So, to short-cut that (or deal with it) would could try this:</p> <pre><code>try: Product_price = wk_cost/wk_qty except ZeroDivisionError: Product_price = 0 </code></pre>
python|pandas
0
5,765
39,948,935
Multiplying pandas dataframe and series, element wise
<p>Lets say I have a pandas series:</p> <pre><code>import pandas as pd x = pd.DataFrame({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] }) y = pd.Series([-1, 1, -1]) </code></pre> <p>I want to multiply x and y in such a way that I get z:</p> <pre><code>z = pd.DataFrame({0: [-1,2,-3], 1: [-4,5,-6], 2: [-7,8,-9] }) </code></pre> ...
<p>You can do that:</p> <pre><code>&gt;&gt;&gt; new_x = x.mul(y, axis=0) &gt;&gt;&gt; new_x 0 1 2 0 -1 -4 -7 1 2 5 8 2 -3 -6 -9 </code></pre>
python|pandas
11
5,766
40,002,760
Why is my data not recognized as time series?
<p>I have daily (<code>day</code>) data on calories intake for one person (<code>cal2</code>), which I get from a Stata <code>dta</code> file. </p> <p>I run the code below:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pylab as plt from pandas import read_csv from matplotlib.pylab import rcP...
<p>There is a discrepancy between the code provided, the data and the types shown. This is because irrespective of the type of <code>cal2</code>, the <code>index = 'day'</code> argument in <code>pd.read_stata()</code> should always render <code>day</code> the index, albeit not as the desired type.</p> <p>With that sa...
python-3.x|pandas|import|time-series|stata
0
5,767
39,504,885
Estimate memory requirements for tensorflow model
<p>How can I estimate the memory requirements of my tensorflow model? Should the below give a somewhat accurate representation?</p> <pre><code>size = 0 for variable in tf.all_variables(): size += int(np.prod(variable.get_shape())) print(size) </code></pre> <p><code>size</code> should be the number of variables. ...
<p>No, you also have to account for your other tensors (e.g. <code>tf.placeholder</code> and <code>tf.constant</code>), and you should also have room for the gradients, as I believe a bunch of values are cached during the forward pass so that backprop doesn't become too slow.</p>
python|tensorflow
0
5,768
43,935,336
How to rename file and copy it with the new name in a new folder (Python)?
<pre><code>import numpy as np import os import matplotlib.pyplot as plt # Loading Data Srcpath ='/mnt/SrcFolder' Destpath='/mnt/DestFolder' traces= os.listdir(path) with open(File_Sensitive_Value, 'wb') as fp: for trace in traces: Plaintext = Extract_Plaintext(trace) print(Plaintext) Ciphertext= Extrac...
<p>This is the structure I use when I need to COPY files en bulk:</p> <pre><code>import os import shutil shutil.copy("OriginalFileAddress", "NewFileAddress") print("Files moved!") </code></pre> <p>If you need to copy the metadata for the files, then use</p> <pre><code>shutil.copy2(src, dst) </code></pre> <p>instea...
python|numpy
0
5,769
69,340,680
Pandas Long to Wide for Categorical Dataframe
<p>Usually when we want to transform a dataframe long to wide in Pandas, we use <em>pivot</em> or <em>pivot_table</em>, or <em>unstack</em>, or <em>groupby</em>, but that works well when there are aggregatable elements. How do we transform in the same manner a categorical dataframe?</p> <p>Example:</p> <pre><code>d = {...
<p>Try <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>cumcount</code></a> with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> to get the counts, then...
python|pandas
4
5,770
69,512,802
replace nan with random value between the existing max and min values in its column in pandas
<p>I have missing data and would like to replace the NaN's with random values from between the existing min and max for that column (different filled values for each NaN). I have been trying things like <strong>the below</strong> but it doesn't work and I am not sure how to loop through the columns correctly as the min...
<p>You can use:</p> <pre><code>numeric_cols = df.select_dtypes([np.number]).columns df[numeric_cols] = df[numeric_cols].apply(lambda x: x.fillna(np.random.uniform(x.min(), x.max(), 1)[0])) </code></pre> <p>Output:</p> <pre><code> Date col2 col3 col4 0 2015-09-01 09:00:00 100.00000 1...
pandas
1
5,771
69,489,255
How to do Pandas stacked bar chart on number line instead of categories
<p>I am trying to make a stacked bar chart where the x-axis is based on a regular number line instead of categories. Maybe bar chart is not the right term?</p> <p>How can I make the stacked bars, but have the x number line be spaced &quot;normally&quot; (with a big relative gap between 5.0 and 10.6)? I also want to set...
<p>In a matplotlib bar chart, the <code>x</code> values are treated as categorical data, so matplotlib always plots it along <code>range(0, ...)</code> and relabels the ticks with the <code>x</code> values.</p> <p>To scale the bar distances, <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.reindex...
python|pandas|matplotlib|bar-chart
1
5,772
69,566,776
Pandas Dataframe - Search by index
<p>I have a dataframe where the index is a timestamp.</p> <pre><code>DATE VALOR 2020-12-01 00:00:00 0.00635 2020-12-01 01:00:00 0.00941 2020-12-01 02:00:00 0.01151 2020-12-01 03:00:00 0.00281 2020-12-01 04:00:00 0.01080 ... ... 2021-04-30 19:00:00 0.77059 2021-04-30 20:00:00 0.49285 2021-04-30 21:00:0...
<p>It looks like you want to subset <code>drop</code> up to index <code>'2020-12-01 04:00:00'</code>.</p> <p>Then simply do this: <code>drop.loc[:'2020-12-01 04:00:00']</code></p> <p>No need to manually get the line number.</p> <p>output:</p> <pre><code> VALOR DATE 2020-12-...
python|pandas
2
5,773
69,477,694
A shorter, more compact alternative to loc multiple variables into separate columns in a loop
<p>Is there a shorter, more compact alternative to loc multiple variables into separate columns in a loop?</p> <p>The code that I am using now is looping through each polygon by index, then finding which point (from point file) is located in which polygon by ID. Then find some metrics or any other variable by equation ...
<p>You could update your rows by using a dictionary like so:</p> <pre class="lang-py prettyprint-override"><code> polygon.loc[n] = {'max': maxv, 'mean': mean, 'median': median, 'std': std, 'half_std': half_std, 'max1': max1} </code></pre> <p>If there are other rows with values you don't want to overwrite you should ad...
python|loops|geopandas
0
5,774
69,644,874
Does @tf.function decorator work with class attributes?
<p>I'm currently developing an Autoencoder class - one of the methods is as follows:</p> <pre class="lang-py prettyprint-override"><code>@tf.function def build_ae(self, inputs): self.input_ae = inputs self.encoded = self.encoder(self.input_ae) self.decoded = self.decoder(self.encoded) self.auto...
<p>The following methods both seem to do the job:</p> <pre class="lang-py prettyprint-override"><code>tf.config.run_functions_eagerly class Test: @tf.function def build_test(self, inputs): self.inp = inputs t = Test() input_t = tf.keras.layers.Input(shape=(3,3,3)) t.build_test(input_t) </...
python|tensorflow|keras
0
5,775
69,609,192
using a tensorflow model trained on google colab on my PC
<p>I am using colab to train a <code>tensorflow</code> model. I see that google colab installs the following version by default:</p> <pre><code>import tensorflow tensorflow.__version__ 2.6.0 ... [train model] ... model.save('mymodel.h5') </code></pre> <p>However, when I download the model to my windows pc and try to l...
<p>hacky solution for now...</p> <ol> <li>download tensorflow 2.1 + CUDA and CuDNN using <code>conda install tensorflow-gpu</code></li> <li>upgrade using <code>pip install tensorflow-gpu==2.6 --upgrade --force-reinstall</code></li> </ol> <p>The GPU does not work (likely because the CUDA versions are not the right ones)...
python|tensorflow|conda
0
5,776
41,058,534
failed to read inch symbol in pandas read_csv
<p>I have csv with below details</p> <pre><code>Name,Desc,Year,Location Jhon,12&quot; Main Third ,2012,GR Lew,&quot;291&quot; Line (12,596,3)&quot;,2012,GR ,All, 1992,FR </code></pre> <p>...</p> <p>It is very long file. i just showed problematic lines.I am confused how can i read it in Pandas data frame, I tried</p>...
<p>You can do something like this. Try if this works for you:</p> <pre><code>import pandas as pd import re l1=[] with open('/home/yusuf/Desktop/c1') as f: headers = f.readline().strip('\n').split(',') for a in f.readlines(): if a: q = re.findall("^(\w*),(.*),\s?(\d+),(\w+)",a) ...
python|csv|pandas|dataframe
1
5,777
41,076,619
How can I read *.csv files that have numbers with commas using pandas?
<p>I want to read a *.csv file that have numbers with commas.</p> <p>For example,</p> <p>File.csv</p> <pre><code>Date, Time, Open, High, Low, Close, Volume 2016/11/09,12:10:00,'4355,'4358,'4346,'4351,1,201 # The last value is 1201, not 201 2016/11/09,12:09:00,'4361,'4362,'4353,'4355,1,117 # The last value is 1117, n...
<p>You can do all of it in Python without having to save the data into a new file. The idea is to clean the data and put in a dictionary-like format for pandas to grab it and turn it into a dataframe. The following should constitute a decent starting point:</p> <pre><code>from collections import defaultdict from colle...
python|csv|pandas
2
5,778
38,160,637
Python: single colon vs double colon
<p>What is the difference between single and double colon in this situation? <code>data[0:,4]</code> vs <code>data[0::,4]</code></p> <pre><code>women_only_stats = data[0::,4] == "female" men_only_stats = data[0::,4] != "female" </code></pre> <p>I tried to replace <code>data[0::,4]</code> with <code>data[0:,4]</...
<p><strong>No</strong>, there is no difference.</p> <p>See the Python documentation for <a href="https://docs.python.org/2/library/functions.html#slice" rel="noreferrer">slice</a>:</p> <p>From the docs: <code>a[start:stop:step]</code></p> <blockquote> <p>The start and step arguments default to None. Slice objects ...
python|numpy|slice|colon
12
5,779
66,004,135
How to print out the tensor values of a specific layer
<p>I wish to exam the values of a tensor after <code>mask</code> is applied to it.</p> <p>Here is a truncated part of the model. I let <code>temp = x</code> so later I wish to print <code>temp</code> to check the exact values.</p> <p>So given a 4-class classification model using acoustic features. Assume I have data in...
<p>You want to output after mask. lescurel's <a href="https://stackoverflow.com/questions/51949208/get-output-from-a-non-final-keras-model-layer">link</a> in the comment shows how to do that. This <a href="https://github.com/keras-team/keras/issues/4205#issuecomment-257284099" rel="nofollow noreferrer">link to github</...
python|tensorflow|machine-learning
0
5,780
66,195,425
Encoding a list column to the legend of a plot
<p>Apologies in advance, I am not sure how to word this question best:</p> <p>I am working with a large dataset, and I would like to plot Latitude and Longitude where the colour of the points (actually the opacity) is encoded to a 'FeatureType' column binded to the legend. This way I can use the legend to highlight on ...
<p>It is not possible for Altair to generate the labels you want from your current column format. You will need to turn your comma-separated string labels into lists and then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer">explode the column</...
python|pandas|data-visualization|altair
0
5,781
52,465,868
TypeError: 'int' object is not iterable when iterating through pandas column
<p>I have a simple use case. I want to read a text file into a pandas file and iterate through the unique <strong><em>id</em></strong> s to plot a <strong><em>x-y graph</em></strong>. Worked for me fine at many other projects but now i get the <code>TypeError: 'int' object is not iterable</code>. At first I got <code>...
<p>IMHO, your code reduces to</p> <pre><code>df = pd.read_table(file, sep=" ") fig, ax = plt.subplots() grpd = df.groupby('id') for i, g in grpd: g.plot(x='x',y='y', marker='o', ax=ax, title="Evaluation") </code></pre> <p><strong><em>Explanation:</em></strong><br> I'll step through the code step by step:</p> <p...
python|pandas|loops|iteration|typeerror
0
5,782
52,739,240
Extend a pandas dataframe to include 'missing' weeks
<p>I have a pandas dataframe which contains time series data, so the index of the dataframe is of type datetime64 at weekly intervals, each date occurs on the Monday of each calendar week.</p> <p>There are only entries in the dataframe when an order was recorded, so if there was no order placed, there isn't a correspo...
<p>Ok given your original data you can achieve the expected results by using <code>pivot</code> and resample for any missing weeks, like the following:</p> <pre><code>results = df_all_products.groupby( ['Week','Product Name'] )['Qty'].sum().reset_index().pivot( index='Week',columns='Product Name', values='Qty'...
python|pandas|dataframe
2
5,783
52,557,357
Changed value in numpy array based on index and on criteria
<p>I have a numpy array:</p> <pre><code>arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) &gt;&gt; arr [[ 1 2 3 4 5] [ 6 7 8 9 10]] </code></pre> <p>I want to take a portion of the array based on indices (not slices):</p> <pre><code>ix = np.ix_([0, 1], [0, 2]) &gt;&gt; arr[ix] [[1 3] [6 8]] </code></pre...
<p>Fancy indexing returns a copy; hence your original array will not be updated. You can use <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> to update your values:</p> <pre><code>arr[ix] = np.where(arr[ix] &lt; 5, 0, arr[ix])...
python|arrays|python-2.7|numpy|indexing
4
5,784
46,347,623
Reading data from csv file with different number of columns and mixed datatype - python
<p>i've got an CSV-file with the following input:</p> <blockquote> <p>Title;High Data</p> <p>Date save;01.01.2000;00:00</p> <p>Comment;</p> <p>Magnification;1;[m]</p> <p>Counts;4931</p> <p>Length;5583;[m]</p> <p>Start 1;0;1475</p> <p>End 1;4931;1475</p> <p>Profil 1[µm]</p> <p>529</p> <p>528</p> <p>and so on ...</p> </b...
<p>This is not really a CSV file. If you want to parse a file into a pandas dataframe, you usually want to be looking at something like a table (for example: each column is one feature, each row is one sample/item/person).</p> <p>It seems like you have three types of data annotation formats here:</p> <p>1</p> <pre><...
python-3.x|pandas|numpy
1
5,785
46,200,506
How to convert [0,0,0,1,2,2] to [0,1,2,0,0,1]?
<p>Using standard TensorFlow operators, how can I convert a 1D tensor which has values in ascending order to a 1D tensor in which each value is the number of times the value at the same index in the input tensor has appeared when scanning from left to right? An example is given in the question title.</p>
<p>You can achieve this using <a href="https://www.tensorflow.org/api_docs/python/tf/while_loop" rel="nofollow noreferrer">tf.while_loop</a>. I suggest the following solution:</p> <pre><code>import tensorflow as tf def scan_accum(a): def condition(a): def c(counts, acc, i): return tf.less(i, ...
tensorflow
0
5,786
46,424,912
tf.contrib.legacy_seq2seq.embedding_rnn_seq2seq output projection
<p>The official documentation for <code>tf.contrib.legacy_seq2seq.embedding_rnn_seq2seq</code> has the following explanation for the output_projection argument: <br></p> <p><code>output_projection</code>: None or a pair (W, B) of output projection weights and biases; W has shape [output_size x num_decoder_symbols] and...
<p>Alright! So, I have found the answer to the question. <br> The main source of confusion was in the dimensions <code>[output_size x num_decoder_symbols]</code> of the W matrix itself. <br></p> <p>The <code>output_size</code> here doesn't refer to the <strong>output_size</strong> that you want, but is the output_siz...
python|tensorflow|lstm|embedding|rnn
0
5,787
46,420,007
Numpy sum() got an 'keepdims' error
<p>This is a paragraph of a neural network code example:</p> <pre><code>def forward_step(X, W, b, W2, b2): hidden_layer = np.maximum(0, np.dot(X, W) + b) scores = np.dot(hidden_layer, W2) + b2 exp_scores = np.exp(scores) probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) ... </code></pr...
<p>Note that under the <code>keepdims</code> argument in the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html#numpy.sum" rel="nofollow noreferrer">docs for <code>numpy.sum()</code></a> it states:</p> <blockquote> <p><strong>keepdims</strong> : <em>bool, optional</em><br> If this is set ...
python|numpy|matrix|sum|numpy-ndarray
10
5,788
58,454,736
How do I delete the spaces (trailing and ending) using a python code
<p>This is my string "INDUSTRIAL, PARKS, PROPERTY" I want to delete the spaces trailing parks, property. I want the output as "INDUSTRIAL,PARKS,PROPERTY"</p>
<p>For your example you can do:</p> <pre><code>strr = "INDUSTRIAL, PARKS, PROPERTY" ','.join(strr.split(', ')) </code></pre> <p>Otherwise if you have something like:</p> <pre><code>strr = "INDUSTRIAL, PARKS, PROPERTY" ','.join([s.strip() for s in strr.split(', ')]) </code></pre>
python|python-3.x|pandas|data-science|data-analysis
0
5,789
58,209,644
How do I remove a MultiIndex from my DataFrame?
<p>I try pulling the columns from my dataframe using <em>df.columns</em> and I get:</p> <pre><code>MultiIndex([( 'time', ''), ('numbers', 11), ('numbers', 12), ('numbers', 13), ('numbers', 14)], names=[None, 'letters']) </code></pre> <p>I have never used a MultiIndex before ...
<p>IIUC you have this:</p> <pre><code>dd = {('time', ''): {0: '22:45:00', 1: '23:00:00', 2: '23:15:00', 3: '23:30:00', 4: '23:45:00', 5: '00:00:00'}, ('numbers', 'a'): {0: 1016.0, 1: 1006.0, 2: 1084.0, 3: 1095.0, 4: 1098.0, 5: 1044.0}, ('numbers', 'b'): {0: 1059.0, 1: 10507.0, 2: 1058.0, 3:...
python|pandas|multi-index
1
5,790
58,369,033
Getting list is unhashable when use apply on a pandas DataFrame
<p>I have a <code>DataFrame</code> <code>df</code> that that has a list in each row, and I want to apply the <code>remove_stops</code> function to each row.</p> <pre><code>import pandas as pd from nltk.corpus import stopwords stop = stopwords.words('english') def remove_stops(row): meaningful_words = [w for w in ...
<p>After explicitly using the name of the column I wanted to applycode as expected</p> <pre><code>df['original'].apply(remove_stops) </code></pre> <p>I was able to run the as intended. Thanks for the prompt replies.</p>
python|pandas|dataframe|apply
1
5,791
69,105,604
Effective way to determine position of two lines
<p>I am trying to determine the position of two lines, so far using numpy but I am open to use opencv if necessary.</p> <p>First look at the pic <a href="https://i.stack.imgur.com/TNWDD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TNWDD.png" alt="lines" /></a></p> <p>I am using the means of the X ...
<p>This idea works if the intersection of the lines does not matter to you if they extend.</p> <pre class="lang-py prettyprint-override"><code>im = cv2.imread(sys.path[0]+'/im.png') gr = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) bw = cv2.threshold(gr, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1] cnts, _ = cv2.findContours...
python|numpy|opencv|image-processing
1
5,792
60,831,722
Fit 3d ellipsoid to a distribution of 3d points?
<p>I have a number of points in 3d space (cartesian x,y,z) and would like to fit a ellipsoid to that in order to determine the axis ratios. The issue here is that I have a distribution of points (not points on a surface), and the solutions to this problem mainly consider the points on a surface. Also would this fit be...
<p>I assume that you are not after the tightest bounding ellipsoid nor some best fit ellipsoid based on the "outer" points (such as an ellipsoid fit on the convex hull).</p> <p>I understand that you are after a distribution, i.e. a unit-sum positive function of the coordinates, which you want to have "ellipsoidal" sym...
python|numpy|scipy|computational-geometry|mcmc
-1
5,793
71,638,200
How to fix IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
<p>I am working on generating a simple sine function defined over the range [0,1] as shown below. However I got an index error when assigning <code>function[i]</code>. I tried to set <code>x_n = int(x_n)</code> as some questions with the same error suggest but that only creates further errors.</p> <pre><code>import num...
<p>The problem is that i is a float, while array indices are ints. You should change your code to</p> <pre class="lang-py prettyprint-override"><code>import numpy as np function = np.zeros(20) x_n=np.arange(0,1,0.05) #[0,1] for i in x_n: function[int(i*20)] = np.sin(2*np.pi*i) </code></pre>
python|numpy
1
5,794
71,563,914
What is the best solution to comparing specific columns against two pandas dataframes here?
<p>I have two pandas dataframes with the same columns, one is old and one is new. They have a subset set of matching account numbers and I have done the following changes to create versions of these two dataframes which have the same account numbers/row length:</p> <pre><code>#Merge and find out where the commonality i...
<p>IIUC, simply use equality and aggregate per row with <code>any</code>:</p> <pre><code>new_df['equal'] = old_df.eq(new_df).all(1) </code></pre> <p>Output:</p> <pre><code> Account number Residence equal 0 1234568 VIRGIN ISLANDS, BRITISH True 1 1111111 SINGAPORE True 2...
python|pandas
0
5,795
42,308,270
Python - numpy mgrid and reshape
<p>Can someone explain to me what the second line of this code does?</p> <pre><code>objp = np.zeros((48,3), np.float32) objp[:,:2] = np.mgrid[0:8,0:6].T.reshape(-1,2) </code></pre> <p>Can someone explain to me what exactly the np.mgrid[0:8,0:6] part of the code is doing and what exactly the T.reshape(-1,2) part of th...
<p>The easiest way to see these is to use smaller values for <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.mgrid.html" rel="noreferrer"><code>mgrid</code></a>:</p> <pre><code>In [11]: np.mgrid[0:2,0:3] Out[11]: array([[[0, 0, 0], [1, 1, 1]], [[0, 1, 2], [0, 1, 2]]]) In [1...
numpy
6
5,796
43,231,649
Julia: Products of sequences in a vectorized way
<p>Learning to pass from Python to Julia, I am trying to convert an old code that I have, that is calculating a product of sequence of this expression:</p> <p><a href="https://i.stack.imgur.com/z9jAd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z9jAd.jpg" alt="enter image description here"></a></...
<p>Also, take a look at <a href="https://github.com/JuliaLang/julialang.github.com/blob/master/blog/_posts/moredots/More-Dots.ipynb" rel="nofollow noreferrer">More-Dots</a> and <a href="https://julialang.org/blog/2017/01/moredots" rel="nofollow noreferrer">Loop Fusion</a> where vectorization is described with examples....
python|algorithm|numpy|julia|array-broadcasting
1
5,797
43,211,893
How to calculate a index series for a event window
<p>Suppose I have a time series like so:</p> <pre><code>pd.Series(np.random.rand(20), index=pd.date_range("1990-01-01",periods=20)) 1990-01-01 0.018363 1990-01-02 0.288625 1990-01-03 0.460708 1990-01-04 0.663063 1990-01-05 0.434250 1990-01-06 0.504893 1990-01-07 0.587743 1990-01-08 0.412223 19...
<p>Leveraging your previous solution from 'Event Study in Pandas' by @jezrael:</p> <pre><code>import numpy as np import pandas as pd s = pd.Series(np.random.rand(20), index=pd.date_range("1990-01-01",periods=20)) date1 = pd.to_datetime('1990-01-05') date2 = pd.to_datetime('1990-01-15') window = 2 dates = [date1, d...
python|pandas
1
5,798
72,198,871
How to create a new column with the percentage of the occurance of a particular value in another column in a DataFrame?
<p>I have a column, it has A value either 'Y' or 'N' for yes or no. i want to be able to calculate the percentage of the occurance of Yes. and then include this as the value of a new column called &quot;Percentage&quot;</p> <p>I have come up with this so far, Although this is what i need i dont know how to get the info...
<p>IIUC, you can use:</p> <pre><code>df1['Shellfish Licence licence (Y/N)'].eq('Y').groupby(df1['Port']).mean() </code></pre> <p>output:</p> <pre><code>Port NORTH SHIELDS 0.2 Name: Shellfish Licence licence (Y/N), dtype: float64 </code></pre> <p>For all columns:</p> <pre><code>df1.filter(like='Y/N').apply(lambda c: ...
python|pandas|dataframe
0
5,799
72,370,399
Pandas: Search and replace a string across all columns in a dataframe
<p>I'm trying to search for a string 'NONE' that is in uppercase across all columns in a dataframe and replace it with 'None'. If it is already 'None' I don't do anything.</p> <p>I tried using the lambda function but its not working.</p> <p>ps: In the data <code>None</code> is not a keyword. It is a string eg: &quot;No...
<p>Try this</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'A': ['None', 'NONE', '565'], 'B': ['234', 'NONE', '347']}) # replace NONE by None df = df.replace('NONE', 'None') print(df) </code></pre> <pre><code> A B 0 None 234 1 None None 2 565 347 </code></pr...
python|pandas|numpy|contains
2