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,600
48,620,057
Keras loss weights
<p>I've model with two output layers, age and gender prediction layers. I want to assign different weight values for each output layer's loss. I've the following line of code to do so.</p> <pre><code>model.compile(loss=[losses.mean_squared_error,losses.categorical_crossentropy], optimizer='sgd',loss_weights=[1,10]) <...
<p>As stated in the book <a href="https://www.manning.com/books/deep-learning-with-python" rel="noreferrer">Deep Learning with Python</a> by François Chollet:</p> <blockquote> <p>The mean squared error (MSE) loss used for the age-regression task typically takes a value around 3–5, whereas the crossentropy loss use...
python|tensorflow|machine-learning|keras
7
5,601
48,465,333
Pandas interpolation /MSE
<p>I know that there is an easy solution for my problem with pandas (hopefully) but I just don't know how to find it. Let's say I've two dataframes: </p> <pre><code>df1 = pd.DataFrame({'x1': [1, 2, 3], 'y1': [1, 4, 9]}) df2 = pd.DataFrame({'x2': [1.5, 2, 3.1, 3.9], 'y2': [1, 3, 5.5, 8]}) </code></pre> <p>I want to ca...
<p>If I understand correctly, you need to bring them to a common grid (abscissa) in order to perform the subtraction and the statistics on it.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd df1 = pd.DataFrame({'x1': [1, 2, 3], 'y1': [1, 4, 9]}) df2 = pd.DataFrame({'x2': [1.5, 2...
python|pandas
1
5,602
48,843,357
python pandas - select particular values after groupby
<p>I have groupby table:</p> <pre><code>df.groupby(['Age', 'Movie']).mean() User Raitings Age Movie 1 1 4.666667 7.666667 2 4.666667 8.000000 3 2.000000 7.500000 4 2.000000 5.500000 5 3.000000 7.000000 18 1 3.000000 7.500000 ...
<p>This gets all of them in one go.</p> <pre><code>df.groupby('Age').Raitings.idxmin().str[-1] Age 1 4 18 1 25 4 45 4 60 1 Name: Raitings, dtype: int64 </code></pre> <p>If you want a function, I'd use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.xs.html" rel="nofol...
python|pandas|pandas-groupby|multi-index
4
5,603
48,454,312
Python (Pandas) Error IndexError: single positional indexer is out-of-bounds
<p>Here is the error I can't seem to squash, dropping down my count to be one less than my actual rows fixes it, but that means it can't even read the last row. The error is coming from me attempting to parse data from my .csv I have saved in the same directory.</p> <p>Here is the code that seems to be causing the iss...
<p>Forgot to add the header row when creating the csv on application start, that resolved all of it.</p> <pre><code> writer.writeheader() </code></pre> <p>That's all it needed.</p>
python|python-3.x|pandas|runtime-error
0
5,604
51,845,480
Error when using tf.get_variable as alternativ for tf.Variable in Tensorflow
<p>Hi I'm new to neural networks and I'm currently working on Tensoflow. First I did the MNIST tutorial which worked quite well. Now I wanted to deepen the whole by means of an own network for Cifar10 in Google Colab. For this purpose I wrote the following code:</p> <pre><code>def conv2d(input, size, inputDim, outputC...
<p>I found my mistake. I forgot the keyword <code>initializer</code>.</p> <p>the correct line looks like this:</p> <pre><code>weight = tf.get_variable("weight",initializer=tf.truncated_normal([size, size, inputDim, outputCount], stddev=anpassung)) </code></pre>
python|tensorflow|conv-neural-network|google-colaboratory
1
5,605
41,971,322
Pandas: How to select the minimum value of a series of rows grouped by a key
<p>Suppose I have the followin dataframe:</p> <pre><code>Key | Amount | Term | Other | Other_2 ----+--------+--------+-------+-------- A | 9999 | Short | ABC | 100 A | 261 | Short | ABC | 100 B | 281 | Long | CDE | 200 C | 140 | Long | EFG | 300 C | 9999 | Long | EFG | 300 </...
<p>To get the min value within each key, you can use <code>groupby.apply</code> to create a boolean Series where the min value takes true and other values take false; then you can use the boolean series for subsetting:</p> <pre><code>df[df.Amount.groupby(df.Key).apply(lambda x: x == x.min())] # Key Amount Term ...
python|pandas|data-cleaning
1
5,606
41,864,024
Why is pyplot.imshow() changing color channels in arrays
<p>For the life of me I have been struggling with this for the last 24 hours. I am doing a Neural Net--storing images in a 4D-array. The first index of the array is bascially the "sample" aka sample 1,2,3, etc. dimenions 2,3,4 are 128x128 x3 rgb pictures. Now in the process of this, i take the input pictures (which...
<p><code>OpenCV</code> stores color images using the <code>BGR</code> convention while <code>matplotlib</code> uses the <code>RGB</code> convention.</p> <p>You should simply flip the channels order when displaying the images using <code>pyplot</code>:</p> <pre><code> plt.imshow(img[:,:,[2,1,0]) plt.imshow(train[0][:...
opencv|numpy|image-processing|matplotlib
8
5,607
64,248,962
How to calculate number of rows per group in pandas dataframe and add it to original data
<p>I have dataframe df like below</p> <pre><code>ID COMMODITY_CODE DELIVERY_TYPE DAY Window_start case_qty deliveries. 6042.0 SCGR Live 1.0 15:00 15756.75 7.75 6042.0 SCGR Live 1.0 18:00 15787.75 5.75 6042.0 SCGR ...
<p>You are looking for a <code>transform</code>:</p> <pre><code>df['window_count'] = df.groupby(['ID','CHAMBER_TYPE','COMMODITY_CODE','DELIVERY_TYPE','DAY'])['ID'].transform('size') </code></pre> <p>By the way, there is no <code>'CHAMBER_TYPE'</code> columns in your sample data.</p>
python|pandas|numpy|pandas-groupby|aggregate-functions
0
5,608
64,370,308
Create pandas MultiIndex DataFrame from multi dimensional np arrays
<p>I am trying to insert 72 matrixes with dimensions (24,12) from an np array into a preexisting MultiIndexDataFrame indexed according to a np.array with dimension (72,2). I don't care to index the content of the matrixes (24,12), I just need to index the 72 matrix even as objects for rearrangemnet purposes. It is like...
<p>After a bot of careful research, I found that my question <a href="https://stackoverflow.com/questions/48482256/what-is-the-pandas-panel-deprecation-warning-actually-recommending">has been already answered here</a> (the right answer) and <a href="https://stackoverflow.com/questions/43427189/3-dimensional-numpy-array...
pandas|dataframe|multi-index
0
5,609
47,835,879
What is different between RNN output and rule based output?
<p>I am new in machine learning and i got a question , I am <a href="https://towardsdatascience.com/lstm-by-example-using-tensorflow-feb0c1968537" rel="nofollow noreferrer">following this tutorial</a> , I read about LSTM and RNN. i use the code provided by tutorial and run it , it completed the training and now i gave ...
<p>Your training dataset only has ~180 words, and is achieving a 84.6% (training) accuracy, so it is overfitting quite a bit. Essentially, the model is simply predicting the next most likely word based on the training data.</p> <p>Usually language models are trained on much larger datasets, such as PTB or the 1B word ...
machine-learning|tensorflow|deep-learning|artificial-intelligence|lstm
0
5,610
49,135,821
Pandas: How to add number of the row within grouped rows
<p>so I have DataFrame:</p> <pre><code>&gt;&gt;&gt; df2 text 0 0 a 0 1 b 0 2 c 0 3 d 1 4 e 1 5 f 1 6 g 2 7 h 2 8 1 </code></pre> <p>How do I create another column, which contains counter for each row within an level=0 index?</p> <p>I have tried the following code (i need to get df['co...
<p>I believe you're looking for <code>groupby</code> along the 0<sup>th</sup> column index + <code>cumcount</code>: </p> <pre><code>df['counter'] = df.groupby(level=0).cumcount() + 1 df text counter 0 0 a 1 1 b 2 2 c 3 3 d 4 1 4 e 1 5 f 2 6 ...
python|pandas|dataframe|group-by|pandas-groupby
2
5,611
49,088,447
Input pipeline using TensorFlow Dataset API and Pandas?
<p>I am trying to create a TensorFlow Dataset that takes in a list of path names for CSV files and create batches of training data. First I create a parse function which uses Pandas to read the first n rows. I give this function as argument for the 'map' method in Dataset</p> <pre><code>def _get_data_for_dataset(file_...
<p>I finally got the answer from <a href="https://stackoverflow.com/questions/49116343/dataset-api-flat-map-method-producing-error-for-same-code-which-works-with-ma/49140725#49140725">Dataset API &#39;flat_map&#39; method producing error for same code which works with &#39;map&#39; method</a> I am posting the full code...
pandas|tensorflow|tensorflow-datasets
1
5,612
49,107,912
How to use for loop on pandas.core.groupby.DataFrameGroupBy in reverse order?
<p>I have a <code>pandas.core.groupby.DataFrameGroupBy</code> object,iter_gb contains customer Itinerary. The sample data looks like. After Itinerary it contains 6 columns, those columns are not important. </p> <pre><code>Customer_id YEAR Itinerary A1, B1, ... 38915672 2015 B12345 38915672 2012 B12345 3...
<p>It seems you need first reverse <code>DataFrame</code> and then loop:</p> <pre><code>for i, x in df[::-1].groupby('Itinerary', sort=False): print (x) Customer_id YEAR Itinerary 16 38915672 2011 B86451 15 38915672 2012 B86451 14 38915672 2012 B86451 13 38915672 2012 B86451 12...
python|pandas
2
5,613
49,057,107
how to add headers to a numpy.ndarray
<p>I have a numpy.ndarray having dimensions of 23411 x 3. I would like to add headers to the top of the matrix called: "summary", "age", and "label". In that order. </p> <p>In:</p> <pre><code>matrix.shape </code></pre> <p>Out:</p> <pre><code>(23411L, 3L) </code></pre> <p>In:</p> <pre><code>type(matrix) </code></p...
<p>You can achieve this with <a href="https://pandas.pydata.org/" rel="nofollow noreferrer">pandas</a>.</p> <pre><code>import pandas as pd matrix = [...] # your ndarray matrix = pd.DataFrame(data=matrix, columns=["summary", "age", "label"]) </code></pre>
python|numpy
4
5,614
49,308,330
get the same order after applying group by on data frame
<p>I've a situation where before applying a group by on a data frame, the order was in ascending, however after applying the data frame order gets changed and its changing internally.</p> <p><strong>here is the code sample:</strong> <strong>DataFrame:</strong> `</p> <pre><code>final_day_wise = daily_sales_data.loc [ ...
<p>Is this what you are looking for?</p> <pre><code>processed_df = df.groupby('col').agg(...).reset_index() processed_df.sort_values(['col', 'Placement#'], ascending=True, inplace=True) </code></pre>
python|python-2.7|pandas|pandas-groupby
0
5,615
58,679,115
Pandas - Modify by string values in each cell by using search
<p>I have pandas dataframe include a column a with content like this <code>'&lt;152/abcx&gt;' ,'&lt;42/da&gt;', '&lt;2/kiw&gt;'</code>. What I want to do is based on the content , remove "&lt;",">", and create two new separate column like this column b : <code>152 ; 42; 2</code>, column c: <code>'abcx', 'da', 'kiw'</co...
<p>Try using this code:</p> <pre><code>df = pd.DataFrame({'a': ['&lt;152/abcx&gt;' ,'&lt;42/da&gt;', '&lt;2/kiw&gt;']}) df = df['a'].str.strip('&lt;&gt;').str.split('/', expand=True) df.columns = ['columnb', 'columnc'] print(df) </code></pre> <p>Output:</p> <pre><code> columnb columnc 0 152 abcx 1 42 ...
string|pandas
2
5,616
58,868,775
Can't initialize Bokeh dashboard with Select widget
<p>This is my first Bokeh experience, so I apologize if I'm asking a very silly question here. So, here's the code. I have a dataframe that contains scores for several individuals. I want to plot a time series line with years on the x-axis, and scores on y-axis and a select menu to pick a player. </p> <p>This is what...
<p>Using <em>real Python callbacks</em>, as you have done above, requires running your code as an application on a Bokeh server. That is because web browsers have no knowledge of, nor ability to run, Python code. Real Python callbacks imply there is some actually running Python process that can run the Python callback ...
python|pandas|bokeh
1
5,617
58,651,762
Summarize a column if values in another column are inferior (without for loop)
<h2>The dataframe</h2> <p>I have dataframe with many items.</p> <p>The items are identified by a code "Type" and by a weight.</p> <p>The last column indicates the quantity.</p> <pre><code>|-|------|------|---------| | | type |weight|quantity | |-|------|------|---------| |0|100010| 3 | 456 | |1|100010| 1 ...
<p>First sort your values by <code>weight</code> and <code>type</code>, then do a <code>groupby</code> for <code>cumsum</code>, and finally do a merge on index:</p> <pre><code>df = pd.DataFrame([[100010, 3, 456],[100010, 1, 159],[100010, 5, 735], [100024, 3, 153], [100024, 7, 175], [100024, 1, 759]],columns = ["type",...
pandas|dataframe|pandas-groupby
2
5,618
58,741,434
Filter one data frame based on other data frame in pandas
<p>I have two DataFrames in pandas:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'Name': ["A", "B", "C", "C","D","D","E"], 'start': [50, 124, 1, 159, 12, 26,110], 'stop': [60, 200, 19, 200, 24, 30,160]}) df2 = pd.DataFrame({'Name': ["B", "C","D","E"], ...
<p>To solve your problem, I applied an SQL-like way that mimics the following query:</p> <pre class="lang-sql prettyprint-override"><code>SELECT df.Name, df.start_x AS start, df.stop_x AS stop FROM ( SELECT df1.Name, df1.start AS start_x, df1.stop AS stop_x, df2.start AS start_y, df2.stop AS stop...
python|pandas|dataframe
1
5,619
58,705,732
How to fill empty cell value in pandas with condition
<p>My sample dataset is as below. Actuall data till 2020 is available.</p> <pre><code> Item Year Amount final_sales A1 2016 123 400 A2 2016 23 40 A3 2016 6 A4 2016 10 100 A5 2016 5 200 A1 2017 123 400 A2 2017 2...
<p>It looks like you want to fill forward where there is missing data.</p> <p>You can do this with 'fillna', which is available on pd.DataFrame objects.</p> <p>In your case, you only want to fill forward for each item, so first group by item, and then use fillna. The method 'pad' just carries forward in order (hence ...
python-3.x|pandas|dataframe|row
2
5,620
70,277,650
Is there any other way (to combine values of one column into different groups), instead of using 'df.replace( )' several times in the below problem?
<p>In : char_df['Loan_Title'].unique()</p> <p>Out: array(['debt consolidation', 'credit card refinancing', 'home improvement', 'credit consolidation', 'green loan', 'other', 'moving and relocation', 'credit cards', 'medical expenses', 'refinance', 'credit card consolidation', 'lending club', 'debt consolidation loan', ...
<p>IIUC (it is hard to read) you could try the following:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd # will use regex pattern as keys and replace string as value patterns = { r'dept consolidation.*': 'dept_consolidation', r'personal.*': 'personal_loan', r'credit card.*': 'credi...
python|pandas|machine-learning|data-science|feature-engineering
2
5,621
70,123,729
Add hours to year-month-day data in pandas data frame
<p>I have the following data frame with hourly resolution</p> <pre><code>day_ahead_DK1 Out[27]: DateStamp DK1 0 2017-01-01 20.96 1 2017-01-01 20.90 2 2017-01-01 18.13 3 2017-01-01 16.03 4 2017-01-01 16.43 ... ... 8756 2017-12-31 25.56 8757 2017-12-31 11.02 8758 2017-12-31 7....
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> for counter with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_timedelta.html" rel="nofollow noreferrer"><code>t...
python|pandas|dataframe
1
5,622
70,058,518
InvalidArgumentError: Incompatible shapes: [29] vs. [29,7,7,2]
<p>so I'm new right here and in Python also. I'm trying to make my own network. I found some pictures of docs and cats 15x15 and unfortunatly couldn't make this basic network...</p> <p>So, these are libraries which I'm using</p> <pre><code> from tensorflow.keras.models import Sequential from tensorflow.keras imp...
<p>You need to <strong>flatten</strong> your prediction somewhere, otherwise you are outputing an image (29 samples of size 7x7 with 2 channels), while you simply want a flat 2 dimensional logits (so shape 29x2). The architecture you are using is somewhat odd, did you mean to have flattening operation <strong>before</s...
tensorflow|keras|neural-network|google-colaboratory
0
5,623
56,318,354
TensorFlow: Why should my image tensor shape equal my label tensor shape?
<p>I wish to do semantic segmentation using TensorFlow 1.12. I create a dataset using <code>from_generator()</code>, where my generator is as follows:</p> <pre><code>def train_sample_fetcher(): return sample_fetcher() def val_sample_fetcher(): return sample_fetcher(is_validations=True) def sample_fetcher(is_...
<p><code>tf.stack</code> operation tries to merge N rank K tensors into one rank (K+1) tensors. In other words, it tries to join a sequence of tensors along new axis and therefore, other axis of tensors should be the same. </p> <p>Can simply return a pair <code>yield rgb, onehots</code> out of your generator.</p>
python|tensorflow|dataset|tensor
1
5,624
56,246,970
How to apply a binomial low pass filter to data in a NumPy array?
<p>I'm supposed to apply a "binomial low pass filter" to data given in a NumPy <code>numpy.ndarray</code>.</p> <p>However, I wasn't able to find anything of the sort at <a href="https://docs.scipy.org/doc/scipy/reference/signal.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/scipy/reference/signal.html</a> ...
<p>A binomial filter is a <a href="https://en.wikipedia.org/wiki/Finite_impulse_response" rel="nofollow noreferrer">FIR filter</a> whose coefficients can be generated by taking a row from <a href="https://en.wikipedia.org/wiki/Pascal%27s_triangle" rel="nofollow noreferrer">Pascal's triangle</a>. A quick way ("quick" a...
python|numpy|filter|scipy|binomial-coefficients
4
5,625
55,683,523
separating a .txt file into two columns using pandas
<p>I have a text file of a script and is ordered like this:</p> <pre><code>0 "character one" "dialogue for character one." 1 "character two" "dialogue for character two." 2 "character one" "dialogue for character one again" ... etc </code></pre> <p>My problem is that I want to analyze this text and need it to be in ...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> with parameters <code>sep</code> and <code>names</code> for new columns names, because in <code>pandas 0.24.2</code> get:</p> <blockquote> <p>FutureWarnin...
pandas|csv|export-to-csv|data-cleaning
2
5,626
55,878,165
create 2 lines plot by dates of Trump's tweets
<p>I have series of Trump's tweets sources by date:</p> <pre><code>trump_tweets_sources.groupby([' created_at ', ' source '])[' source '].count() </code></pre> <p><a href="https://i.stack.imgur.com/y12Cf.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I want to create 2 lines plot descri...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>Series.unstack</code></a> for <code>DataFrame</code> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html" rel="nofollow noreferrer"...
python|pandas|dataframe|matplotlib
0
5,627
55,990,477
Creating a DataFrame by passing a NumPy array, with a datetime index and labeled columns:
<p>On running a code, getting a following error:-</p> <p><strong>'list' object is not callable</strong></p> <pre><code>dates = pd.date_range('20190101', periods=6) dates df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD')) </code></pre> <p>Expected output:-</p> <pre><code>In [8]: df Out[8]: ...
<p>Your code is perfectly correct. If you execute it right after restarting your kernel it is bound to run. The error you are getting refers to the <code>list</code> function you have used to convert <code>string</code> 'ABCD' to list. Most likely, you have used list as an <code>object</code> name somewhere else, and t...
python|pandas
0
5,628
64,744,068
Remove row from arbitrary dimension in numpy
<p>I have a function, <code>remrow</code> which takes as input an arbitrary numpy nd array, <code>arr</code>, and an integer, <code>n</code>. My function should remove the last row from <code>arr</code> in the <code>n</code>th dimension. For example, if call my function like so:</p> <p><code>remrow(arr,2)</code></p> <p...
<p>Construct an indexing tuple, consisting of the desired combination of slice(None) and slice(None,-1) objects.</p> <pre><code>In [75]: arr = np.arange(24).reshape(2,3,4) In [76]: idx = [slice(None) for _ in arr.shape] In [77]: idx Out[77]: [slice(None, None, None), slice(None, None, None), slice(None, None, None)] In...
python|numpy|indexing|numpy-ndarray
2
5,629
64,940,267
How to access specific rows in a pandas multiindex dataframe
<p>I'm working with what I think is a pandas multi-index data frame. Is there any way to make sure? My data looks like this.</p> <pre><code> cinc Outcome Side 1 2 1 2 WarNum 1 0.146344 0.029989 1 2 4 0.152565 0.056853 ...
<p>To check if your df has <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html" rel="nofollow noreferrer"><code>Multiindex</code></a>, you can do this:</p> <pre><code>isinstance(war_cinc.index, pd.MultiIndex) </code></pre> <p>This will return <code>True</code>.</p> <p>To check for <code>hiera...
python|python-3.x|pandas|dataframe
1
5,630
64,952,877
How can I add comma into existing value in DataFrame?
<p>I scraped a DataFrame from one website but during scraping I lost comma in values, so it looks like below:</p> <pre><code>name price x 100 y 89 z 123584 </code></pre> <p>Now I have to modify values in column &quot;price&quot; by adding comma in each value on the second place counting by right. T...
<p>We can slice your string and add the commas:</p> <pre><code>df['price'].str[:-2] + ',' + df['price'].str[-2:] </code></pre> <pre><code>0 1,00 1 ,89 2 1235,84 Name: price, dtype: object </code></pre> <hr /> <p>Or we can use <code>str.cat</code> with the <code>sep</code> argument:</p> <pre><code>df['pr...
python|python-3.x|pandas|dataframe|number-formatting
1
5,631
64,984,092
Pandas Dataframe calculate Time difference for each group and Time difference between two different groups
<p>I have created a dataframe like that:</p> <pre><code>import pandas as pd d = {'Time': ['01.07.2019, 06:21:33', '01.07.2019, 06:32:01', '01.07.2019, 06:57:33', '01.07.2019, 07:24:33','01.07.2019, 08:26:25', '01.07.2019, 09:12:44'] ,'Action': ['Opened', 'Closed', 'Opened', 'Closed', 'Opened', 'Closed'] ,'Nam...
<p>Start by making datetime from string, then some groupbys and diffs:</p> <pre><code>df[&quot;Time&quot;] = pd.to_datetime(df[&quot;Time&quot;]) df[&quot;d1&quot;] = df.groupby(&quot;Name&quot;)[&quot;Time&quot;].diff().shift(-1).fillna(&quot;&quot;) df[&quot;d2&quot;] = ( df.groupby((df[&quot;Action&quot;] == &qu...
python|pandas|dataframe
3
5,632
64,827,154
Python/Pandas time series correlation on values vs differences
<p>I am familiar with Pandas Series corr function to compute the correlation between two Series, so example:</p> <pre><code>import pandas as pd import numpy as np A = pd.Series(np.random.randint(1,101,50)) B = pd.Series(np.random.randint(1,101,50)) A.corr(B) </code></pre> <p>This willl compute the correlation in the ...
<p>I guess the more pythonic way, through pandas, would be to use <code>df.pct_change()</code>:</p> <p>Suppose A and B are time series:</p> <pre><code>A.pct_change().corr(B.pct_change()) </code></pre>
python|pandas|numpy|statistics|correlation
1
5,633
64,667,734
Pretty print a dictionary matrix in Python
<p>Giving a dictionary of dictionary:</p> <pre><code>dict_2d = collections.defaultdict(dict) dict_2d['A']['A'] = 1 dict_2d['A']['B'] = 0.19 ... dict_2d['Z']['A'] = 0.76 ... dict_2d['Z']['Z'] = 1 </code></pre> <p>Could you advise an elegant way to print such a square matrix?</p> <p>For instance:</p> <ol> <li>is there a...
<p>Not sure exactly how your print should look like however I tried writing some code. I would recommend using <code>tabulate</code> or <code>pandas</code> as it makes it way easier.</p> <pre><code>df = pd.DataFrame(dict_2d) print(df) # A Z # A 1.00 0.76 # B 0.19 NaN # Z NaN 1.00 </code></pre> <p>I w...
python|pandas|dictionary
1
5,634
64,847,271
Use two columns as inputs - Pandas
<p>I'm trying to create a new column that comes from the calculation of two columns. Usually when I need to do this but with only one column I use <code>.apply()</code> but now with two parameters I don't know how to do it.</p> <p>With one I do the following code:</p> <pre><code>from pandas import read_csv, DataFrame ...
<p>Disclaimer: avoid <code>apply</code> if possible. With that in mind, you are looking for <code>axis=1</code>, but you need to rewrite the function like:</p> <pre><code>df['new'] = df.apply(lambda x: myFunc(x['colA'], x['colB']), axis=1) </code></pre> <p>which is essentially equivalent to:</p> <...
python|pandas
2
5,635
40,033,190
Pandas Grouping - Values as Percent of Grouped Totals Not Working
<p>Using a data frame and pandas, I am trying to figure out what each value is as a percentage of the grand total for the "group by" category</p> <p>So, using the tips database, I want to see, for each sex/smoker, what the proportion of the total bill is for female smoker / all female and for female non smoker / all f...
<p>You can add another grouped by process after you get the <code>sum</code> table to calculate the percentage:</p> <pre><code>(df.groupby(['sex', 'smoker'])['total_bill'].sum() .groupby(level = 0).transform(lambda x: x/x.sum())) # group by sex and calculate percentage #sex smoker #Female No 0.622350...
python|pandas|dataframe|aggregate|aggregation
10
5,636
39,998,594
Many small data table I/O for pandas?
<p>I have many table (about 200K of them) each small (typically less than 1K rows and 10 columns) that I need to read as fast as possible in pandas. The use case is fairly typical: a function loads these table one at a time, computes something on them and stores the final result (not keeping the content of the table in...
<p>IMO there are a few options in this case:</p> <ol> <li><p>use HDF Store (AKA PyTable, H5) as <a href="https://stackoverflow.com/questions/39998594/many-small-data-table-i-o-for-pandas#comment67274829_39998594">@jezrael has already suggested</a>. You can decide whether you want to group some/all of your tables and s...
pandas|io
1
5,637
44,339,072
Difference between initializing a Tensorflow Variable using np.zeros and using tf.zeros
<p>Are there some differences between initializing a tensorflow Variable using np.zeros and using tf.zeros?</p> <p>For example, if we take a look at the MNIST softmax tutorial ( <a href="https://github.com/tensorflow/tensorflow/blob/r1.1/tensorflow/examples/tutorials/mnist/mnist_softmax.py" rel="nofollow noreferrer">h...
<p>For most experiments it almost does not matter. You can also provide python list of lists <code>[[0, 0, ...], ...]</code>. The difference you see in your <code>eval</code> is because <a href="https://www.tensorflow.org/api_docs/python/tf/zeros" rel="nofollow noreferrer">tf.zeros</a> by default uses <code>float32</co...
variables|tensorflow|initialization
2
5,638
69,616,471
Hugginface Bert Tokenizer build from source due to proxy issues
<p>I encountered something similar to this: <a href="https://stackoverflow.com/questions/59701981/bert-tokenizer-model-download">BERT tokenizer &amp; model download</a></p> <p>The link above is about downloading the Bert model itself, but I would only like to use the Bert Tokenizer.</p> <p>Normally I could do it like t...
<p>You would need to 1) download vocabulary and configuration files (<code>vocab.txt</code>, <code>config.json</code>), 2) put them into a folder and 3) pass folder's path to <code>BertTokenizer.from_pretrained(&lt;path&gt;)</code> function.</p> <p>Here is the download location of <code>vocab.txt</code> for different t...
python|tokenize|huggingface-transformers
2
5,639
69,660,556
pd.DataFrame cuts the decimals' mantissa
<p>Need to convert list of values with long mantissa into pd.DataFrame without precision lost:</p> <p><a href="https://i.stack.imgur.com/Nl05Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nl05Q.png" alt="enter image description here" /></a></p> <p>My list of decimals:</p> <p><a href="https://i.sta...
<p>The values are stored with the correct precision, they are just truncated when you display them.</p> <p>You can change the precision used by pandas when displaying datarames by using <code>pd.set_option('display.precision', num_decimal_digits)</code>.</p> <p>For example</p> <pre><code>df = pd.DataFrame([0.123456789]...
pandas|dataframe|decimal|mantissa
0
5,640
69,561,023
Combine value strings of two dataframes in corresponding locations within each dataframe
<p>I am looking for python code to paste value strings of two dataframes with identical column names, dimensions and datatype (Strings).</p> <p>I want to create a new dataframe by pasting each element of DF1 &amp; DF2 together which is in the corresponding location within each dataframe and have a &quot;,&quot; delimit...
<p>Use <code>pd.concat</code>:</p> <pre><code>out = pd.concat([df1.stack(), df2.stack()], axis=1) \ .apply(lambda x: ','.join(x), axis=1) \ .unstack() </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; out A B C 0 z,f x,h c,j 1 v,t b,y n,u 2 a,u s,i d,o </code></pre>
python|pandas|dataframe
2
5,641
41,067,917
Tensorflow: InvalidArgumentError for placeholder
<p>I tried to run the following code in Jupyter Notebook, however I got the <code>InvalidArgumentError</code> for the <code>placeholder</code>.</p> <p>But when I wrote a Python script and ran it in command window, it worked. I want to know how can I ran my code in the Notebook successfully, thanks.</p> <ul> <li>OS: U...
<p>Your <code>raw_data</code> is float64 (default numpy float type) whereas your placeholder is float32 (default tensorflow float type). You should explicitly cast your data to float32</p>
tensorflow
1
5,642
54,125,497
Expected 2D array, got scalar array instead error in pandas regression
<p>I'm taking an error when i try to calculate regression in pandas. Here is the code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df=pd.DataFrame({"haftalar":[1,2,3,4,5,6,7], "degerler":[6.11,5.66,5.30,5.32,5.25,5.37,5.28]}) haftalar=df[['haftalar']] degerler=df[['degerler']] ...
<p>Try:</p> <pre><code>tahmin=lr.predict([[8]]) </code></pre> <p>More often, you may have data in <code>numpy</code> arrays like so:</p> <pre><code>import numpy as np x_test = np.array([8]) </code></pre> <p>Now the error message tells you what to do:</p> <pre><code>tahmin=lr.predict(x_test.reshape(-1, 1)) </code><...
python|python-3.x|pandas|scikit-learn|sklearn-pandas
0
5,643
53,869,191
When converting to CSV UTF-8 with python, my date columns are being turned into date-time
<p>When I run the following code </p> <pre><code>import glob,os import pandas as pd dirpath = os.getcwd() inputdirectory = dirpath for xls_file in glob.glob(os.path.join(inputdirectory,"*.xls*")): data_xls = pd.read_excel(xls_file, sheet_name=0, index_col=None) csv_file = os.path.splitext(xls_file)[0]+"...
<p>Nothing is "going wrong" per se. You simply need to provide a custom <code>date_format</code> to <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer"><code>df.to_csv</code></a>:</p> <blockquote> <p>date_format : string, default None ...
python|excel|pandas
5
5,644
53,932,989
Output file for every input file in a folder
<pre><code>import pandas as pd import glob import csv files=glob.glob('*.csv') for file in files: df=pd.read_csv(file) a=sum(df.iloc[: , 0]) with open ('output.txt','w') as f: f.write("sum of the first column is "+ str(a)) f.close() </code></pre> <p>I would like to write output files for ev...
<p>You can create a separate output file for each input file and prefix/suffix it with the name of the input file - </p> <pre><code>import pandas as pd import glob import csv files=glob.glob('*.csv') for file in files: df=pd.read_csv(file) a=sum(df.iloc[: , 0]) output_file_name = "output_" + file with ...
python|python-3.x|pandas
0
5,645
66,269,739
De-Duplicate in Pandas based off of multiple rules
<p>I want to de-dupe rows in pandas based off of multiple criteria.</p> <p>I have 3 columns: name, id and nick_name.</p> <p>First rule is look for duplicate id's. When id's match, only keep rows where name and nick_name are different as long as I am keeping at least one row.</p> <p>In other words, if name and nick_name...
<p>We can split this into 3 boolean condtions to filter your initial dataframe by.</p> <pre><code>#where name and nick_name match, keep the first value. con1 = df.duplicated(subset=['name','nick_name'],keep='first') # where ids are duplicated and name is not equal to nick_name con2 = df.duplicated(subset=['id'],keep...
python|pandas
1
5,646
66,198,363
Extract first column and last column of a Numpy array and populate on one dimension array
<p>I am a novice on Numpy.</p> <p>I have extracted a CSV file and with the condition to populate the array below</p> <pre class="lang-py prettyprint-override"><code>data = [(2006, 'Total Live-Births', 38317) (2007, 'Total Live-Births', 39490) (2008, 'Total Live-Births', 39826) (2009, 'Total Live-Births', 39570) (2010...
<p>Given your data as follows: Just sticking to <code>numpy</code> you could do something like:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np data = np.genfromtxt('live-births.csv', delimiter=',', skip_header=1, dtype=str) # keep only the 'Total Live-Births' values live_births = data[data[:, 1...
numpy
2
5,647
65,954,374
pandas mapping list to dict items for new column
<p>i have df like:</p> <pre><code>col_A [1,2,3] [2,3] [1,3] </code></pre> <p>and dict like:</p> <pre><code>dd = {1: &quot;Soccer&quot;, 2: &quot;Cricket&quot;, 3: &quot;Hockey&quot;} </code></pre> <p>how can i create a new column col_B like:</p> <pre><code>col_A col_B [1,2,3] [&quot;Soccer&quot;, &quot;Cricket&...
<p>You can use list comprehension with <code>if</code> for filter out not matched values:</p> <pre><code>df['sports'] = df['col_A'].map(lambda x: [dd[y] for y in x if y in dd]) </code></pre> <p>Or replace to <code>None</code> if no match:</p> <pre><code>df['sports'] = df['col_A'].map(lambda x: [dd.get(y, None) for y in...
python|pandas|list|dictionary
3
5,648
52,871,044
Count duplicates in rows per column in pandas DataFrame
<p>I have a very long table like below:</p> <pre><code> A B C D ....... 0 au br gt uy 1 cd gq gt uy 2 fg br gt ml 3 kl br gt wx </code></pre> <p>..............</p> <p>I would like to count and to print duplicates per column like:</p> <pre><code>A 0 B 2 C ...
<p>Subtract length of DataFrame with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.nunique.html" rel="noreferrer"><code>nunique</code></a>:</p> <pre><code>df = len(df) - df.nunique() print (df) A 0 B 2 C 3 D 1 dtype: int64 </code></pre> <p>Or use<a href="http://pandas.pyd...
python|pandas|dataframe|duplicates
5
5,649
52,484,199
Series' object has no attribute 'decode in pandas
<p>I am trying to decode utf-8 encoded text in python. The data is loaded to a pandas data frame and then I decode. This produces an error: <strong>AttributeError: 'Series' object has no attribute 'decode'</strong>. How can I properly decode the text that is in pandas column? </p> <pre><code>&gt;&gt; preparedData.head...
<p>I could be wrong but I would guess that what you have are byte strings rather than strings of bytes strings <code>b"XXXXX"</code> instead of <code>"b'XXXXX'"</code> as you've posted in your answer in which case you could do the following (you need to use the string accessor):</p> <pre><code>preparedData['text'] = p...
python|pandas
7
5,650
52,736,221
Pandas NaN value causing trouble when change values depending on other columns
<p>why do pandas NaN values sometime typed as numpy.float64, and sometimes float? This is so confusing when I want to use function and change values in a dataframe depending on other columns</p> <p>example:</p> <pre><code> A B C 0 1 NaN d 1 2 a s 2 2 b s 3 3 c NaN </code></pre> <p>I h...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a>, for check missing values is used spec...
python|pandas|numpy
2
5,651
46,330,595
Build a dictionary from two DataFrame columns
<p>How to build up a dictionary with a Dataframe.</p> <p><code>df</code></p> <pre><code> Vendor Project 0 John Cordoba 1 Saul Pampa 2 Peter La Plata 3 John Federal District 4 Lukas Salta 5 Thomas Rio Grande 6 Peter Rio Salado 7 Pe...
<p>Use</p> <pre><code>In [1893]: df.groupby('Vendor')['Project'].apply(list).to_dict() Out[1893]: {'John': ['Cordoba', 'Federal District'], 'Lukas': ['Salta'], 'Peter': ['La Plata', 'Rio Salado', 'Bahia Blanca'], 'Saul': ['Pampa'], 'Thomas': ['Rio Grande']} </code></pre> <p>Or,</p> <pre><code>In [1900]: {k: g['P...
python|pandas|dictionary|dataframe
5
5,652
58,311,504
filter DataFrame leaving rows where Needle is part of the list present in columnB
<p>I am looking for a filter function on my DataFrame to find rows where my searchTerm is in the list that is in the dataframe row.</p> <p>I've been digging trough list related filters, they all seem to have a 'list' as needles and a single value in the dataFrame column.</p> <pre class="lang-python prettyprint-overri...
<p><a href="https://stackoverflow.com/questions/32280556/how-to-filter-a-dataframe-column-of-lists-for-those-that-contain-a-certain-item">How to filter a DataFrame column of lists for those that contain a certain item</a></p> <p>contains the solution:</p> <pre><code>df[df['members'].apply(lambda x: 'b' in x)] </code>...
python|pandas
0
5,653
58,460,285
Why is df.cumsum() giving ValueError: Wrong number of items passed, placement implies 1
<p>I would like to create a new column called total_amount based on the sum of each amount in each group. I would like the final data set to look like the set below. </p> <p>company | amount | total_amount</p> <p>company 1 | 10000 | 10000</p> <p>company 1 | 20000 | 30000</p> <p>company 1 | ...
<p>It indicates <code>cumsum</code> returns more than 1 columns. In other words, <code>df.groupby('company').cumsum()</code> is calling <code>cumsum</code> on <code>DataFrameGroupby</code> object, so it returns a dataframe. If the returned dataframe is only 1 column, the assignment still works. However, if the returned...
python|pandas|cumsum
0
5,654
69,223,955
Building a Neural Network for Binary Classification on Top of Pre-Trained Embeddings Not Working?
<p>I am trying to build a Neural Network on top of the embeddings that a pre-trained model outputs. In specific: I have the logits of a base model saved to disk where each example is an array of shape 512 (which originally corresponds to an image) with an associated label (0 or 1). This is what I am doing right now:</p...
<p>You are only printing from the second iteration. The above will effectively print for every <code>200k+1</code> steps, but <code>i</code> starts at <code>0</code></p> <pre><code>if i % 2000 == 1: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) ...
python|machine-learning|deep-learning|neural-network|pytorch
0
5,655
69,102,683
Python - Join two dataframes based on closest date match and additional column
<p>I have two dataframes that I need to join on two columns, one of which is a date column. However, the dates do not match as shown in below example. I have seen people on other posts using merge_of for similar examples however that will not work here I believe as I also need to join on another non-date column(pty).I ...
<p>My output is a bit different in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a> method:</p> <pre><code>df1['alert_dt'] = pd.to_datetime(df1['alert_dt'], dayfirst=True) df2['inv_dt'] = pd.to_datetime(df2['inv_dt'], dayfir...
python|pandas
2
5,656
69,170,906
Convert a string column to period in pandas preserving the string
<p>I would like to understand if I can convert a <em>string</em> column to a <strong>PeriodIndex</strong> (for instance year), preserving the string (suffix).</p> <p>I have the following DataFrame:</p> <pre><code>company date ... revenue taxes Facebook 2017-01...
<p>Let's say there is a dummy dataframe, similiar with yours:</p> <pre><code>dictionary = {'company' : ['Facebook', 'Facebook', 'Facebook_Total','Google','Google_Total'], 'date' : ['2019-09-14 09:00:08.279000+09:00 Total', '2020-09-14 09:00:08.279000+09:00 Total', ...
python|pandas|dataframe|datetime|period
2
5,657
68,883,614
Keras Captcha OCR - How to pass single jpeg image to loaded (trained) model and receive prediction in string?
<p>for the past several hours I was looking all over the internet for an answer to how I can pass a single jpeg image into my pre-trained model (saved and loaded) and receive prediction in string format.</p> <p>I am using Captcha OCR from this source - <a href="https://keras.io/examples/vision/captcha_ocr/" rel="nofoll...
<p>From the last code snippet and &quot;Since the model is expecting two values (while training we were passing dict with image and image name (answer to captcha)). But now, I would like this model to actually predict the image so I am not able to pass answer/label.&quot; statement you have made.</p> <p>you are trying ...
python|tensorflow|keras|ocr|captcha
0
5,658
61,150,879
Mapping a Dataframe into another using conditionals
<p>I would like to map one dataframe into another, though it is not so simple because I am using 2 conditions to execute the mapping - I will explain them below. Basically, what I am trying to do is given two dataframes, df1 and df2, such that:</p> <p>df1:</p> <pre><code>A B Type Heart Spades Boo Hea...
<p>Try <code>melt</code> and <code>drop_duplicates</code> on <code>df2</code>. Finally, left <code>merge</code> df1 to the result of <code>melt</code> and <code>drop_duplicates</code></p> <pre><code>df_final = (df1.merge(df2.melt(['A','B'], var_name='Type', value_name='Verification') .drop_dup...
python|pandas|dataframe
2
5,659
61,072,251
How can I find Feature importance from sklearn api, after I have converted my categorical variables into dummy variables?
<p>After we have converted our categorical variables to dummy variables for training the model. We tend to find feature importance. But sklearn's model.feature_importance_ object returns feature impotance for every dummy variable, rather than the original categorical variable. How to fix this?</p>
<p>Because the dummy variables are used to train the model, you cannot find the importance of the original categorical variable. It is mathematically impossible thing.</p>
python|pandas|machine-learning|scikit-learn|data-science
0
5,660
71,517,905
Merge with replacement of smaller dataframe to larger dataframe
<p>I have two DataFrames that look like this:</p> <p>DF1:</p> <pre><code>index colA colB id1 0 0 id2 0 0 id3 0 0 id4 0 0 id5 0 0 </code></pre> <p>DF2:</p> <pre><code>index colA colB id3 A3 B3 id4 A4 B4 id6 A6 B6 </code></pre> <p>I want to infuse val...
<p>Here's one way using <code>concat</code> + <code>drop_duplicates</code>:</p> <pre><code>out = pd.concat((df1, df2)).reset_index().drop_duplicates(subset=['index'], keep='last').set_index('index').sort_index() </code></pre> <p>or use <code>reindex</code> + <code>update</code>:</p> <pre><code>df1 = df1.reindex(df1.ind...
python|pandas|dataframe|merge
2
5,661
71,645,121
Pandas replace change so values to NaN
<p>I have the the following dataframe:</p> <pre><code># dictionary with list object in values details = { 'Name' : ['D', 'C', 'F', 'G','A','N'], 'values' : ['21%','45%','10%',12,14,15], } df = pd.DataFrame(details) </code></pre> <p>The column value has values in %, however, some were originally saves as string...
<p>There are numeric values, so if use <code>str</code> function get missing values for numeric, possible solution is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.replace.html" rel="nofollow noreferrer"><code>Series.replace</code></a> with <code>regex=True</code> for replace by s...
python|pandas|replace|nan
1
5,662
71,688,065
Generic requirements.txt for TensorFlow on both Apple M1 and other devices
<p>I have a new MacBook with the Apple M1 chipset. To install tensorflow, I follow the instructions <a href="https://developer.apple.com/metal/tensorflow-plugin/" rel="noreferrer">here</a>, i.e., installing <code>tensorflow-metal</code> and <code>tensorflow-macos</code> instead of the normal <code>tensorflow</code> pac...
<p>According to this post <a href="https://stackoverflow.com/questions/29222269/is-there-a-way-to-have-a-conditional-requirements-txt-file-for-my-python-applica">Is there a way to have a conditional requirements.txt file for my Python application based on platform?</a></p> <p>You can use conditionals on your requiremen...
python|macos|tensorflow|apple-m1|requirements.txt
2
5,663
71,669,501
Having trouble calculating mean squared error in sklearn python
<p>I am trying to fit a decision tree regressor to a dataset, and it is working but when I test it out by calculating mean squared error. I get an error that looks like this:</p> <pre><code>msee = mse(x_test, y_test) ValueError Traceback (most recent call last) ~\AppData\Local\Temp/ipyke...
<p>from the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>Parameters y_true array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values.</p> <p>y_pred array-like of ...
python|numpy|scikit-learn|decision-tree
0
5,664
71,727,478
Trying to plot a graph with Pandas but only wish to display data from 1 row of a csv between two dates
<p>I have a CSV file of weather data.</p> <p>I have the file indexed by date (e.g., the date of the reading).</p> <p>One of my columns is 'Humidity' and contains humidity data.</p> <p>I wish to use the .plot function but I wish to limit the data set to between two dates.</p> <p>To discriminate by time I used this to vi...
<p>What about</p> <pre><code>london[london.loc[start_date : end_date]]['Mean Humidity'].plot(grid=True, figsize=(10,5)) </code></pre>
python|pandas|csv
0
5,665
71,629,686
Python - how to add another "column" to numpy ndarray
<p>I have a 34000,18 dimension numpy array and I have a 34000,1 array that needs to be appended to the first one at the end.</p> <p><code>X_train.shape</code> =(34189, 18)</p> <p><code>type(X_train)</code> = numpy.ndarray</p> <p><code>y_train.shape</code> = (34189,)</p> <p>my attempt:</p> <p>Data = np.append(X_train,y_...
<p>An array with <code>ndim == 1</code> is implicitly a row, not a column. The simplest way would be to turn it into a column and use <code>np.concatenate</code>:</p> <pre><code>np.concatenate((X_train, Y_train[:, None]), axis=1) </code></pre> <p>You could do the same with <code>np.append</code>:</p> <pre><code>np.appe...
python|dataframe|numpy
0
5,666
42,449,339
General way to test restored tensorflow model
<p>I am very, very brand new to Tensorflow, and need to write a script that tests a single example on a model restored from a checkpoint file. </p> <p>I was wondering if there was a general way to build a test function for a restored model without knowing all the minute details of the model. </p> <p>Further, in the l...
<p>The <a href="https://www.tensorflow.org/extend/estimators" rel="nofollow noreferrer">Estimator</a> class has a convenient set of utilities such that, if your model is wrapped around an estimator, loading and predicting from it is easy.</p> <p>Overall, without some kind of coordination, this will be hard.</p>
python-2.7|tensorflow
0
5,667
42,392,260
Return equivalent of `:` from function for indexing array
<p>I have a large array and a function that returns index lists into the array, i.e.,</p> <pre><code>import numpy n = 500 a = numpy.random.rand(n) def get_idx(k): # More complicated in reality return range(n) if k &gt; 6 else range(k) data = a[get_idx(29)] data = a[get_idx(30)] # ... </code></pre> <p>A ...
<p>Have a look at <a href="https://docs.python.org/3/library/functions.html#slice" rel="nofollow noreferrer"><code>slice</code></a></p> <pre><code>def get_x(): return slice(2) a=list(range(100)) a[get_x()] </code></pre> <p>will return <code>[0, 1]</code></p> <h2>UPDATE</h2> <p>And for your need <code>get_x</co...
python|arrays|numpy
9
5,668
42,191,656
Tensorflow learning XOR with linear function even though it shouldn't
<p>I am implementing a simple network in tensorflow and for pedagogical purposes, I am trying to show that the linear transformation:</p> <pre><code>yhat = w(Wx + c) + b </code></pre> <p>cannot learn XOR. But the problem right now is that with my current implementation, it does! This suggests a bug in the code. Pleas...
<p>tf.argmax(Y,1) will return [0,0,0,0]. This is not what you want.</p>
tensorflow|neural-network
1
5,669
69,873,341
need help assigning custom timeslots to datetime data
<p>I have a datetime data to a minute (sample below)</p> <pre><code>2021-11-08 00:10:00 2021-11-08 01:10:00 2021-11-08 02:25:00 2021-11-08 03:55:00 2021-11-08 06:55:00 2021-11-08 12:35:00 2021-11-08 16:05:00 2021-11-08 17:10:00 2021-11-08 18:45:00 2021-11-08 19:10:00 2021-11-08 20:25:00 2021-11-08 20:55:00 2021-11-08 2...
<p>Given that the initial time data is in a string format, this is how I would proceed: Given a dataframe of form:</p> <pre><code> Time 0 2021-11-08 00:10:00 1 2021-11-08 01:10:00 2 2021-11-08 02:25:00 3 2021-11-08 03:55:00 4 2021-11-08 06:55:00 5 2021-11-08 12:35:00 </code></pre> <p>Step 1. Add a timest...
python|pandas|datetime|compare
0
5,670
43,165,025
dropping columns from dataframes
<p>I have 5 dataframes and I want to drop certain columns from them. I tried for loop, something like this -</p> <pre><code>dataframes =[af,bf,cf,df,ef,ff,gf] for col in dataframes: print col.head(1) col = col.drop(col.columns[[0,2]],axis=1) print col.head(1) </code></pre> <p>I know the approach is wrong. How t...
<p>consider the list of dataframes <code>dataframes</code></p> <pre><code>dataframes = [pd.DataFrame(dict(A=[1], B=[2], C=[3])) for _ in range(4)] </code></pre> <p>Use <code>drop</code> and <code>inplace=True</code></p> <pre><code>for d in dataframes: d.drop(['B'], 1, inplace=True) for d in dataframes: prin...
python|pandas
1
5,671
43,394,148
Replace strings in entire dataframe if they are present in a list
<p>Thank you for your time visiting my post. I have the following dataframe below:</p> <pre><code>df1 col1 col2 1 virginia is cold, canada is cold too virginia is cold, canada is cold too 2 florida, virginia, washington are good florida, virginia, washington a...
<pre><code>df1.replace(lst, 'x' * 5, regex=True) col1 col2 1 xxxxx is cold, canada is cold xxxxx xxxxx is cold, canada is cold xxxxx 2 florida, xxxxx, washington are good florida, xxxxx, washington are good 3 georgia, alabama, xxxxx are xxxxx xx...
python|list|pandas|dataframe|replace
3
5,672
50,661,449
Trying to set a subset of a vector to equal another vector, but everything gets set to 0
<p>I'm trying to get into Python for statistics, coming from an R background. I've set up a script for cross validation on a dataset I've been working with:</p> <pre><code>cvIndex = np.remainder(np.arange(dat.shape[0]), 10) pred = np.arange(dat.shape[0]) for i in range(10): #get training and test set trFeatur...
<p>Looks like integer coercion to me. <code>np.arange</code> returns an integer array which you then update in-place. As an in-place operation cannot change an array's dtype the r.h.s. will be converted to int. With your input being probabilities this will be all zeros.</p> <p>Since you are overwriting all of <code>pr...
python|python-3.x|validation|numpy|numpy-ndarray
2
5,673
50,581,526
Two dataframe columns to row and column index with third column as values
<p>I have a dataframe that looks as follows:</p> <pre><code> x y error (1, 1) 1.0 1.0 0.062532 (1.0, 2.0) 1.0 2.0 0.050991 (1.0, 3.0) 1.0 3.0 0.028133 (1.0, 4.0) 1.0 4.0 0.023807 ... (99.0, 20.0) 99.0 20.0 0.019846 (99.0, 21.0) 99.0 21.0 0.135257 (99.0, 22.0)...
<p>This should work: </p> <pre><code>df.pivot(index='y', columns='X', values='error') </code></pre> <p>You can get more examples on pivot table in pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reshaping.html" rel="nofollow noreferrer">here</a></p>
python|pandas
0
5,674
50,595,173
pandas merge and groupby
<p>I have 2 pandas dataframes which look like below. </p> <p>Data Frame 1: </p> <pre><code>Section chainage_from chainage_to Frame R125R002 10.133 10.138 1 R125R002 10.138 10.143 2 R125R002 10.143 10.148 3 R125R002 10.148 ...
<p>merge the dataframes by <code>Section</code> and filter so that <code>Chainage</code> is in [from &amp; to). </p> <pre><code>merged = pd.merge_asof(df2, df1, by='Section', left_on='Chainage', right_on='chainage_from') </code></pre> <p>groupby &amp; aggregate, passing a dictionary that maps column name &amp; aggreg...
python|pandas
1
5,675
50,263,985
tf.datasets input_fn getting error after 1 epoch
<p>So I am trying to switch to an input_fn() using tf.datasets as described in this <a href="https://stackoverflow.com/questions/48779293/upgrade-to-tf-dataset-not-working-properly-when-parsing-csv">question</a>. While I have been able to get superior steps/sec using tf.datasets with the input_fn() below, I appear to r...
<p>As Robbie suggests in the <a href="https://stackoverflow.com/a/50266170/3574081">other answer</a>, it looks like your old implementation used fixed batch sizes throughout (presumably using an API like <a href="https://www.tensorflow.org/api_docs/python/tf/train/batch" rel="nofollow noreferrer"><code>tf.train.batch()...
tensorflow|google-cloud-ml|tensorflow-datasets
1
5,676
62,766,042
Inputs to eager execution function cannot be Keras symbolic tensors with Variational Autoencoder
<p>I'm trying to implement a custom Variational Autoencoder. The code is shown below</p> <pre><code>image = Input(shape = (X_train.shape[1])) label = Input(shape = (Y_train.shape[1])) inputs = Concatenate()([image, label]) x = Dense(625, activation = 'relu')(inputs) x = Reshape((25,25,1))(x) x = LocallyConnected2D(8...
<p>I've been having the same problem for a long time, but managed to figure it out. The problem is that TF only accepts loss functions which accept <code>(input, output)</code> parameters which are then compared. However, you are computing your (kl_)loss using also <code>mu</code> and <code>sigma</code>, which are basi...
tensorflow|keras
0
5,677
62,848,487
Inserting new fields(columns) to mongoDB with pandas
<p>I have an existing data in MongoDB where Primary Key is set on 'date' with a few fields in it.</p> <p>And I want to insert a new pandas dataframe with new fields(columns) to the existing data in MongoDB, joining on the 'date' field which exists on the both dataframe.</p> <p>For example, lets say the this is datafram...
<p>The method you need is <code>update_one()</code> with <code>upsert=True</code> in a loop; you can't use <code>insert_many()</code> for two reasons; firstly your not always inserting; sometime you are updating; secondly <code>update_many()</code> (and <code>insert_many()</code>) only work on a single filter; in your ...
pandas|mongodb|dataframe|pymongo
1
5,678
62,688,771
merge cells in dataframe while converting to html using style object
<p><a href="https://i.stack.imgur.com/iSlvn.png" rel="nofollow noreferrer"> </a></p> <p>I am trying to merge cells in dataframe while converting to HTML. But however, ending with row lines. Is it possible to merge only specific cells in a dataframe while converting to HTML or can we give header option to multiple colum...
<p>I was unable to do this. But I tried to add caption to table as an option and its very feasible than this.</p> <pre><code>styles = [dict(selector=&quot;th&quot;, props=th_props), dict(selector=&quot;td&quot;, props=th_props), dict(selector=&quot;caption&quot;, props=[(&quot;text-align&quot;, &quot;center&quot;), ...
html|pandas|dataframe|styles|cell
0
5,679
54,566,209
LSTM's expected hidden state dimensions doesn't take batch size into account
<p>I have this decoder model, which is supposed to take batches of sentence embeddings (batchsize = 50, hidden size=300) as input and output a batch of one hot representation of predicted sentences:</p> <pre><code>class DecoderLSTMwithBatchSupport(nn.Module): # Your code goes here def __init__(self, em...
<p>When you create the <code>LSTM</code>, the flag <code>batch_first</code> is not necessary, because it assumes a different shape of your input. From the docs:</p> <blockquote> <p>If True, then the input and output tensors are provided as (batch, seq, feature). Default: False</p> </blockquote> <p>change the LSTM...
python-3.x|lstm|pytorch|batchsize
1
5,680
71,128,122
Pandas - How to convert timedelta64[ns] to HH:MM:SS
<p>I have a doubt how can I convert all column from Pandas (Python) from timedelta64[ns] like: <code>2 days 03:29:05</code> to: <code>51:29:05</code>.</p> <pre><code>**PLEASE, CONSIDER time COLUMN AS A timedelta64[ns]** d = {'id': [1123, 2342], 'time': ['2 days 03:29:05', '1 days 01:57:53']} df = pd.DataFrame(data=d)...
<p>I don't think that there is a direct way. But you could use a custom function on top of <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.total_seconds.html" rel="nofollow noreferrer"><code>total_seconds</code></a>:</p> <pre><code>def sec_to_format(s): h,s = divmod(int(s),3600) m,s = div...
python|pandas
1
5,681
60,758,957
Using generator in Python to feed into Keras model.fit_generator
<p>I am learning how to use generator in Python and feed it into Keras model.fit_generator.</p> <pre><code>from keras.utils import to_categorical from keras.models import Sequential from keras.layers import Dense, Conv2D, Flatten import pandas as pd import os import cv2 class Generator: def __init__(self,path): ...
<p>I think answers to your questions can be found in Keras documentation. </p> <p>In terms of the input shape, <code>Conv2D</code> layers expects 4-dimensional input, but you explicitly reshape to <code>(28,28,1)</code> in your generator, so 3 dimensions. On the Conv2D info and the input format, see <a href="https://k...
python|tensorflow|machine-learning|keras|deep-learning
1
5,682
60,683,901
Tensorboard smoothing
<p>I downloaded the CSV files from tesnorboard in order to plot the losses myself as I want them Smoothed.</p> <p>This is currently my code:</p> <pre><code>import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt df = pd.read_csv('C:\\Users\\ali97\\Desktop\\Project\\Database\\C...
<p>If you are working with <code>pandas</code> library you can use the function <code>ewm</code> (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ewm.html" rel="noreferrer">Pandas EWM</a>) and ajust the <code>alpha</code> factor to get a good approximation of the smooth function fro...
python|tensorflow|tensorboard
8
5,683
72,728,922
ERROR: Input to reshape is a tensor with 2381440 values, but the requested shape requires a multiple of 200704
<p>I am trying to learn the CNN model in deep learning and I am using a <code>Cats-vs_Dogs</code> dataset to begin with. I am following a video tutorial and the steps are the same, although the dataset is different and all the other solutions have vastly varied code that I am not able to understand. Can someone tell me...
<p>The error is because the target size is (244, 244) and the input shape given in the model is (224, 224, 3). You can either change the target size to (224, 224) or change the input shape to (244, 244, 3).</p> <p>Change the <code>input_shape</code> to <code>(244, 244, 3)</code></p> <pre><code>Conv2D(filters=32,kernel_...
python|tensorflow|machine-learning|keras|deep-learning
0
5,684
72,550,969
Interpolating a time series with interp1d using only numpy
<p>I want to plot a time series with numpy and matplotlib, using markers for the exact points, and interpolation. Basically this (data is dummy, but functionality is the same, note that distance between time-points may vary):</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from scipy.interpolate ...
<p>The data type of any element in <code>T</code> is <code>np.datetime64</code> and not <code>np.timedelta64</code>.</p> <p>Thus, convert the dtype of all elements of T to <code>np.timedelta64</code> by creating a numpy array with datatype <a href="https://numpy.org/doc/stable/reference/generated/numpy.dtype.kind.html...
python|numpy|matplotlib|scipy|interpolation
1
5,685
72,538,834
How to do a nested loop with 2 columns for pandas dataframe with counter?
<p>I am using python and pandas. I have a bunch of unstructured survey data.</p> <p>I have a dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Type</th> <th>Activity</th> </tr> </thead> <tbody> <tr> <td>Sport</td> <td>rowing</td> </tr> <tr> <td>Sport</td> <td>Surfing</td> </tr> <t...
<p>It's best to avoid loops as much as possible, here we replaced the 2 loops with a dictionary <code>activity_type</code> that maps every activity to its type.</p> <p>NOTE: the <code>df1</code> is the Type, Activity <code>DataFrame</code></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd from col...
python|pandas|loops
0
5,686
59,755,671
How to use a trained TensorFlow model in a plain Javascript webapp
<p>I've been following this tutorial: <a href="https://docs.annotations.ai/workshops/object-detection/6.html" rel="nofollow noreferrer">https://docs.annotations.ai/workshops/object-detection/6.html</a></p> <p>And got to step 6, once I get to the webapp example it's done in ReactJS and I can't figure out how to convert...
<p>You can use the script for TensorFlow js &amp; coco SSD</p> <pre><code>&lt;!-- Load TensorFlow.js. This is required to use coco-ssd model. --&gt; &lt;script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"&gt; &lt;/script&gt; &lt;!-- Load the coco-ssd model. --&gt; &lt;script src="https://cdn.jsdelivr.net/npm/@t...
javascript|tensorflow
0
5,687
59,671,362
Downloading blocks of data from census, how to wrtie to multiple csvs to not exceed memory
<p>Suppose I have a list of api keys I am downloading from the census data</p> <p>Example:</p> <pre><code>variable_list = [ 'B08006_017E', 'B08016_002E', 'B08016_003E', 'B08016_004E', ... ] </code></pre> <p>Now given memory constraints for putting this data onto one csv file. I want to create a way in which I place ...
<p>It looks like you're already chunking the variable_lists here:</p> <pre class="lang-py prettyprint-override"><code>for var_list in all_variable_lists: list_of_dfs.append(download_all_data(var_list, 2012)) </code></pre> <p>Just make sure each <code>var_list</code> has only 100 items. Then chunk the csv writing ...
python|pandas|census
1
5,688
59,616,436
How to reset initialization in TensorFlow 2
<p>If I try to change parallelism in TensorFlow 2 after initializing a <code>tf.Variable</code>,</p> <pre><code>import tensorflow as tf _ = tf.Variable([1]) tf.config.threading.set_inter_op_parallelism_threads(1) </code></pre> <p>I get an error</p> <blockquote> <p>RuntimeError: Inter op parallelism cannot be modif...
<p>This is achievable in a "hacky" way. But I'd recommend doing this the right way (i.e. by setting up config at the beginning).</p> <pre><code>import tensorflow as tf from tensorflow.python.eager import context _ = tf.Variable([1]) context._context = None context._create_context() tf.config.threading.set_inter_op_...
python|tensorflow|pytest|tensorflow2.0
3
5,689
59,818,185
memory error reading big size csv in pandas
<p>My laptops memory is 8 gig and I was trying to read and process a big csv file, and got memory issues, I found a solution which is using <strong>chunksize</strong> to process the file chunk by chunk, but apperntly when uisng chunsize the file format vecoe <strong>textreaderfile</strong> and the code I was using to p...
<p>You have to iterate over the chunks:</p> <pre><code>csv_length = 0 for chunk in pd.read_csv(fileinput, names=['sentences'], skiprows=skip, chunksize=10000): csv_length += chunk.count() print(csv_length ) </code></pre>
python|pandas|csv|chunking
1
5,690
59,551,405
rolling function does not print all values
<p>I am trying to understand rolling function on pandas on python here is my example code </p> <pre><code># importing pandas as pd import pandas as pd # By default the "date" column was in string format, # we need to convert it into date-time format # parse_dates =["date"], converts the "date" column to date-time...
<p><code>...</code> just means that <code>pandas</code> isn't showing you all the rows, that's where the 'missing' ones are.</p> <p>To display all rows:</p> <pre><code>with pd.option_context("display.max_rows", None): print (df.close.rolling(3, win_type ='triang').sum()) </code></pre>
python|pandas
1
5,691
61,858,321
Plot specific months from whole data set?
<p>From a whole data set, I need to plot the maximum &amp; minimum temperatures for just the months of January and July. Column 2 is the date, and columns 8 and 9 are the 'TMAX' and 'TMIN.' This is what I have so far:</p> <pre><code>napa3=pd.read_csv('MET 51 Lab #10 data (Pandas, NAPA).csv',usecols=[2,8,9]) time2=pd.t...
<p>The problem can raise because the dates are saved as an "object" or a string. However, I can't see that you have created dataframe?! you do read_csv but you do not make dataframe out of that:</p> <pre><code>dnapa3 = pd.DataFrame(napa3) </code></pre> <p>then repeat converting your time data and check:</p> <pre><co...
python|pandas|datetime
0
5,692
61,885,775
Rolling mean over the last n-days with if statement
<p>I have the following dataframe:</p> <pre><code>entry_time_flat route_id time_slot duration n_of_trips 2019-09-02 00:00:00 1_2 0-6 10 29 2019-09-04 00:00:00 3_4 6-12 15 10 2019-09-06 00:00:00 1_2 ...
<p>I am not complete sure if I understood your goal here but I'll try:</p> <pre><code>import pandas as pd data = {'entry_time_flat': ['2019-09-02 00:00:00', '2019-09-04 00:00:00', '2019-09-06 00:00:00', '2019-09-06 00:00:00'], 'route_id': ['1_2', '3_4', '1_2', '1_2'], 'time_slot': ['0-6', '6-12', '0-6', '18-20'], 'du...
python|pandas|pandas-groupby|rolling-computation
0
5,693
61,831,227
How to solve Import object_detection/protos/image_resizer.proto but not used protobuf compilation
<p>I have an issue when I try to compile Protobuf to use TensorFlow Object Detection API</p> <p>In jupyter I tried to lauch object_detection_tutorial</p> <p>I got this error:</p> <p>jupyter protobuf error:<br /> <a href="https://i.stack.imgur.com/YLtAl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/...
<p>Haven't tried to build the latest version of the api, but perhaps that's a bug? Try removing line 5 from input_reader.proto:</p> <pre><code>//import &quot;object_detection/protos/image_resizer.proto&quot;; </code></pre> <p>It looks as though it isn't used, perhaps they forgot to remove it.</p>
python|tensorflow
4
5,694
57,736,228
Errors when load selected raw data into dataframe
<p>I want to select three groups of json data and load them into a dataframe but i got the errors "string indices must be integers". Can anyone kindly tell me what is the reason for it?</p> <p>The code is as following and i have also attached the screenshot:</p> <pre><code>for currency in data: if '/BTC' in currency...
<p>Looks like <code>currency</code> is a key in <code>data</code> dictionary here:</p> <pre><code>for currency in data: if '/BTC' in data[currency]['symbol']: change_daily=data[currency]['percentage'] name=data[currency]["symbol"] price = data[currency]['last'] df_binance.append({"N...
python|pandas|data-analysis|cryptocurrency
0
5,695
57,990,852
catplot(kind="count") is significantly slower than countplot()
<p>I am working on a fairly large dataset (~40m rows). I have found that if I call <strong>sns.countplot()</strong> directly then my visualisation plots really quickly:</p> <pre><code>%%time ax = sns.countplot(x="age_band",data=acme) </code></pre> <p><a href="https://i.stack.imgur.com/k4qwV.png" rel="nofollow norefe...
<p>There is a lot of overhead in <code>catplot</code>, or for that matter in <code>FacetGrid</code>, that will ensure that the categories are synchronized along the grid. Consider e.g. that you have a variable you plot along the columns of the grid for which not every age group occurs. You would still need to show that...
python|pandas|matplotlib|seaborn
1
5,696
54,956,068
Rename a column values in pandas
<p>I have a dataset with column named region. Sample values are Eg. <code>region_1, region_2, region_3</code> etc.</p> <p>I need to replace these values to Eg. <code>1,2,3</code>, etc.</p> <p>Any specific function to deal with this easy transformation?</p> <p>Thanks</p>
<p>I believe you need split with select second value and if necessary convert to integers:</p> <pre><code>df.region = df.region.str.split('_').str[1].astype(int) </code></pre> <p>Or use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>extra...
python|pandas
0
5,697
54,809,462
xarray and netCDF file with empty variables and 0-dimensional object dataframe
<p>I'm trying to convert some .nc files into <code>pandas</code> dataframes using <code>xarray</code>.</p> <p>Here's one of the netCDF files:</p> <p><a href="ftp://l5ftl01.larc.nasa.gov/MISR/MIL2ASAE.003/2017.08.31/MISR_AM1_AS_AEROSOL_P006_O094165_F13_0023.nc" rel="nofollow noreferrer">ftp://l5ftl01.larc.nasa.gov/MIS...
<p>Your dataset seems to be setup with a hierarchy of <a href="http://docs.h5py.org/en/stable/high/group.html" rel="nofollow noreferrer">groups</a>. Xarray's <a href="http://xarray.pydata.org/en/stable/generated/xarray.open_dataset.html#xarray.open_dataset" rel="nofollow noreferrer"><code>open_dataset</code></a> functi...
python|pandas|netcdf|python-xarray
3
5,698
54,911,436
How to implement CRelu in Keras?
<p>I'm trying to implement CRelu layer in Keras</p> <p>One option that seems work is to use Lambda layer:</p> <pre><code>def _crelu(x): x = tf.nn.crelu(x, axis=-1) return x def _conv_bn_crelu(x, n_filters, kernel_size): x = Conv2D(filters=n_filters, kernel_size=kernel_size, strides=(1, 1), padding='same'...
<p>I don't think there is a significant difference between the two implementations speed-wise. </p> <p>The Lambda implementation is the simplest actually but writing a custom Layer as you have done usually is better, especially for what regards model saving and loading (<strong>get_config</strong> method). </p> <p>Bu...
python|tensorflow|keras|deep-learning
1
5,699
49,759,626
Is it possible to Skip Blank Lines in a Dataframe? If Yes then how I can do this
<p>I am trying to run this code</p> <pre><code>num = df_out.drop_duplicates(subset=['Name', 'No.']).groupby.(['Name']).size() </code></pre> <p>But when I do I get this error:</p> <pre><code>ValueError: not enough values to unpack (expected 2, got 0) </code></pre> <p>If we think about my dataframe(df_out) as an exce...
<p>Consider using <code>df.dropna()</code>. It is uses to remove rows that contains NA. See <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html</a> for more information...
python|pandas|dataframe
3