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
11,400
69,314,471
Creating rank based on index value in pandas dataframe
<p>I have a data-frame like this</p> <pre><code>name qty1 qty2 set_id 0 name0 2 5 1000 1 name1 1 7 1000 2 name2 0 4 1000 3 name3 6 6 1000 4 name4 8 8 1000 5 name5 0 3 1000 </code></pre> <p>I want to update the set_id column like this. (for every...
<p>IIUC, you can use a <code>list comprehension</code> and assign it's return to your set_id column:</p> <pre><code>df['set_id'] = pd.Series([(i+1) for i in range(len(df)) for n in range(2)]) </code></pre> <p>prints:</p> <pre><code> name qty1 qty2 set_id 0 0 name0 2 5 1 1 1 name1 1 ...
python|python-3.x|pandas
0
11,401
69,496,275
tensorflow:You must feed a value for placeholder tensor 'Placeholder_1' with dtype float
<p>my code with the fail:</p> <p>tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_1' with dtype float [[{{node Placeholder_1}}]]</p> <p>Here is my code.</p> <pre><code>import tensorflow as tf import numpy as np import os os.environ[&quot;TF_CPP_MIN_...
<p>When you run the code multiple times, nested computation graph will be created. You can view the behavior in tensorboard, graph become bigger and bigger after multiple runs. You need to reset the graph</p> <p>Use <code>tf.reset_default_graph()</code> and put it before the place where you create the graph</p>
tensorflow
0
11,402
69,333,441
Output of f_classif (sklearn) is a array that contain nan only
<p>I used train_test_split to split training set call X_train and y_train. For X_train, I got 799 rows and 9 features. For y_train, it got 799 rows that is the 'changes'. When I try to use <code>F,PV = f_classif(X, y)</code> to get F-value. It is correct to have 9 values for 9 features, but it is 'nan'. I just don't un...
<p>Number of observations of classes in features may not be sufficiant to make calculations. Assume 'M' is a class in feature1. Since you split your dataset, 'M' might be left in the other part of the dataset. So X_train does not have sufficiant number of 'M' class. Each class should be appear with other classes in oth...
python|pandas|scikit-learn|sklearn-pandas
0
11,403
69,611,466
How to join two tables with same column names but with different data using pandas?
<p>Supposing</p> <p>df1,</p> <pre><code>col1 | col2 | col3 | col4 | A | 131 | 666 | 777 | B | 123 | 345 | 435 | C | 1424 | 3214 | 2314 | </code></pre> <p>df2,</p> <pre><code>col1 | col2 | col3 | col4 | A | 10 | 1 | 0 | B | 20 | 14 | 68 | C | 23 | 43 | 4 | </code></pre> <p>fi...
<p>You can convert DataFrames to strings, replace <code>0</code> to missing values, add <code>( %)</code>, so not added for missing values and last is added first <code>DataFrame</code>:</p> <pre><code>df = ((df1.set_index('col1').astype(str) + (' (' + df2.set_index('col1').astype(str).replace('0', np.nan) + '%)...
python|pandas|dataframe|join
3
11,404
41,154,398
What do I need to return from __repr__ to have multiple lines when printing custom object wrapped in a pandas object
<p>consider my custom class <code>Cube</code></p> <pre><code>class Cube(object): def __init__(self): pass def __repr__(self): return "⧉ ⟦x⨯y⟧\nCUBE" cube = Cube() cube ⧉ ⟦x⨯y⟧ CUBE </code></pre> <p>The string representation was printed on multiple lines.<br> However, when I wrap it in a pa...
<p>I don't have a good answer for your actual question, but in the past when I've wanted to change some of the visuals of a DataFrame's HTML table, I've used a combination of <code>IPython.display.display_html()</code> and <code>pd.DataFrame.to_html()</code>. Not ideal, but at least one potential workaround for you.</p...
python|pandas|jupyter-notebook
1
11,405
40,857,128
Calculate the difference in two wind directions in python
<p>How can I calculate the difference (WD_Bias) in two wind directions (in degrees) in python so that the results range from -180 to 180? Here is the code I have so far? Does this seem to do what I want or am I missing something else?</p> <pre><code>WD_Bias = WD_model - WD_obs WD_Bias[WD_Bias&gt;180.]=360.-WD_Bias[WD...
<p>If the wind directions that you are subtracting are the same magnitude, take the difference and use modulo arithmetic to get your answer between -180 and +180.</p> <p>If they are different magnitudes, represent those as vectors (real+image works) then use inverse tangent to find the vector difference angle. Or use ...
python|numpy|math
3
11,406
54,112,903
Search multiple strings for multiple words
<p>I have a dataframe containing a sentence per row. I need to search through these sentences for the occurence of certain words. This is how I currently do it:</p> <pre><code>import pandas as pd p = pd.DataFrame({"sentence" : ["this is a test", "yet another test", "now two tests", "test a", "no test"]}) test_words ...
<p>IIUC, use a simple list comprehension and call <code>str.find</code> for each word:</p> <pre><code>u = pd.DataFrame({ # 'word_{}'.format(w) f'word_{w}': df.sentence.str.find(w) for w in test_words}, index=df.index) u word_yet word_test 0 -1 10 1 0 12 2 -1 8...
python|pandas|dataframe
5
11,407
54,039,062
Pandas check time series continuity
<p>I have a DataFrame with monthly index. I want to examine whether the time index is continuous on the monthly frequency, and, if possible, spots where it becomes discontinuous e.g. has certain "gap months" between two months that are adjacent in its index.</p> <p>Example: the following time series data</p> <pre><co...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.asfreq.html" rel="nofollow noreferrer"><code>asfreq</code></a> by month for add missing datetimes, filter it to new <code>Series</code> and if necessary grouping by years with create list of months:</p> <pre><code>s = s.asfreq('m') s1 ...
python|pandas|datetime
6
11,408
66,305,759
Issues with .JSON file conversion and CSV manipulation in Python
<p>sorry for the long post! I'm a bit Python-illiterate, so please bear with me:</p> <p>I am working on a project that uses extracted Fitbit resting heart-rate data to compare heart-rate values between a series of years. The fitbit data exports as a .json file that I am attempting to convert to .csv for further analysi...
<p>The problem is that this is a nested json file. The solution is to load the json file with <code>json</code> and then load it into pandas with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html" rel="nofollow noreferrer"><code>json_normalize</code></a></p> <pre><code>impor...
python|json|pandas|csv
1
11,409
66,015,279
MATLAB .mat in Pandas DataFrame to be used in Tensorflow
<p>I have gone days trying to figure this out, hopefully someone can help.</p> <p>I am uploading a .mat file into python using scipy.io, placing the struct into a dataframe, which will then be used in Tensorflow.</p> <pre><code>from scipy.io import loadmat import pandas as pd import numpy as p import matplotlib.pyplot ...
<p>What type of data is your .mat file of ? Is your application very time critical? If you can collect all your data in a struct you could give jsonencode a try, make the struct a json file and load it back into python via json (see json documentation on loading data).</p> <p>Then you can create a pandas dataframe via<...
pandas|matlab|tensorflow
0
11,410
66,151,277
Recode multiple values in several columns in Python [similar to R]
<p>I am trying to translate my R script to python. I have a survey data with several date of birth and education level columns for each family member(from family member 1 to member 10): here a sample:</p> <pre><code>id_name dob_1 dob_2 dob_3 education_1 education_2 education_3 12 1958 2001 ...
<p>You can write a function that combines <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjtoPfRveHuAhXKF4gKHcg5BfUQFjAAegQIAxAC&amp;url=https%3A%2F%2Fpandas.pydata.org%2Fpandas-docs%2Fstable%2Freference%2Fapi%2Fpandas.DataFrame.pipe.html...
python|r|pandas|dataframe|numpy
1
11,411
58,303,621
Populating new data frame column from parameterised SQL call
<p>I have a data frame whose single column <code>tbl_name</code> contains a list of tables from my SQLite database:</p> <pre class="lang-python prettyprint-override"><code>tables = pd.read_sql_query("SELECT tbl_name FROM sqlite_master WHERE type = 'table'", db) </code></pre> <p>I would like to add a column containing...
<p>Try this:</p> <pre><code>tables['count'] = tables.tbl_name.apply(lambda row : pd.read_sql_query(f"SELECT COUNT(*) FROM {row}", db).iloc[0,0]) </code></pre> <p>In your version, there is <code>axis=1</code> is missing, it should be like below:</p> <pre><code>tables['count'] = tables.apply(lambda row : pd.read_sql_q...
python|pandas
1
11,412
58,203,973
pandas unable to write to Postgres db throws "KeyError: ("SELECT name FROM sqlite_master ..."
<p>I have created a package allowing a user to write data to either a sqlite or Postgres db. I created a module for connecting to the db and a separate module that provides the writing functionality. In the latter module the write is a straightforward pandas internal function call:</p> <pre><code>indata.to_sql('pay_...
<p>Per <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.to_sql.html" rel="nofollow noreferrer"><code>pandas.DataFrame.to_sql</code></a> documentation:</p> <blockquote> <p><strong>con</strong> : sqlalchemy.engine.Engine or sqlite3.Connection</p> <p>Using SQLAlchemy makes i...
pandas|sqlite|pycharm|anaconda|pg8000
3
11,413
58,294,484
How to batch CsvDataset correctly in Tensorflow 2.0?
<p>I'm using <code>tf.data.experimental.make_csv_dataset</code> to create a dataset from a .csv file. I'm also using <code>tf.keras.layers.DenseFeatures</code> as an input layer of my model.</p> <p>I'm struggling to create a <code>DenseFeatures</code> layer properly so that it is compatible with my dataset in the case...
<p>From the <code>tf.feature_column.numeric_column</code> documentation:</p> <blockquote> <p><strong><code>shape</code></strong>: An iterable of integers specifies the shape of the <strong><code>Tensor</code></strong>. An integer can be given which means a single dimension <strong><code>Tensor</code></strong> with g...
tensorflow2.0|tf.keras
1
11,414
58,548,267
How to remove and return a row from a pandas dataframe?
<p>I have a dataframe with n records indexed (0 - n). I want to remove a row at the 'x' index from the dataframe and store it elsewhere. I essentially am trying to do the equivalent to performing a pop() from a list in Python. Is there any function or easy way to do this using pandas dataframes? </p> <p>I've tried usi...
<p>You could simply define your own function which performs the drop inplace but only after storing the desired result:</p> <pre class="lang-py prettyprint-override"><code>def drop_return(df, index): row = df.loc[index] df.drop(index, inplace=True) return row </code></pre> <p>With your given example:</p> ...
python|pandas|dataframe|numpy-ndarray
4
11,415
69,167,398
Filtering a datatime set from the starting and ending year with Pandas Numpy Python
<p>How would I be able to write a code that will enable the starting and the ending year in <code>dates</code>. I want to use either pandas or numpy to show the starting and the ending year.</p> <pre><code>import numpy as np import pandas as pd dates = ['2017-09-01 00:00:00', '2017-10-01 00:00:00', '2017-11-01 00:00...
<p>In your case let us do</p> <pre><code>pd.Series(pd.to_datetime(dates)).dt.year.agg(StartYear = 'min', EndYear = 'max') Out[245]: StartYear 2017 EndYear 2019 dtype: int64 </code></pre>
python|arrays|pandas|numpy|datetime
3
11,416
69,213,060
How do I cut up a dataframe using dates as the start and end points?
<p>Currently, I am using DataFrame.iloc to cut my dataframe into small dataframes based on integer position.</p> <pre><code>#df_all is my full dataframe that includes a column for date and time df_some = df_all.iloc[100:4000] </code></pre> <p>However, when I use this method, I have to guess the integer values until I ...
<pre><code>df_some = df_all.loc['2021-08-04 19:05:00':'2021-08-05 19:10:00'] </code></pre> <p>Thank you Kyle Parsons!</p>
python|pandas|dataframe
0
11,417
69,262,802
Pandas - Interpolate based on previous behavior
<p>I have a datetime index pandas with hourly data that needs to be interpolated when <code>nans</code> exist. Sometimes 1 hour is missing and a linear interpolation would be enough, but sometimes it can be days, in which case I'd need it to consider the behavior it has had on the last week on average to fill the value...
<p>Here's a solution on how to fill different NaN blocks, depending on their length:</p> <pre><code># count up by one every time NaN-state flips d31_nan_group_keys = df.D31.isnull().diff().ne(0).cumsum() def long_nan_series(series): # select this series when all values are NaNs all_nans = series.isnull().all()...
python|pandas|time-series|interpolation
1
11,418
69,169,194
Pivoting a pandas dataframe using the first column as colNames
<p>I know how the pivot_table works in python. However I have a different problem. My sample dataframe ( or csv file say) looks this below:</p> <pre><code> df PRD A1 A2 A3 A4 A5 A6 A7 DN 12 67-1 34 98 07 45 29 AV uy-9 iu-9 uyt ...
<p>There are two ways to change rows and columns in pandas:</p> <ul> <li>Use pandas.DataFrame.T</li> </ul> <pre><code>df_transposed = df.T </code></pre> <ul> <li>Use pandas.DataFrame.transpose</li> </ul> <pre><code>df_transposed = df.transpose() </code></pre> <p><strong>Note</strong></p> <p>depending on the data type d...
python|pandas|pivot-table|transpose
0
11,419
44,491,123
How to select DataFrame index's values based on value of another numpy array?
<p>I have </p> <pre><code>a = pd.DataFrame({'user_id': [101,102,103,104,105], 'date1': [0,1,2,3,4], 'date2': [0,1,2,3,4]}) a.set_index('user_id') </code></pre> <p>And I would like to select the values in a that has the same indices as the values of b (below)</p> <pre><code>b = np....
<p>Note that you did not persist the setting of the index of <code>a</code>. You could either reassign back to <code>a</code> with <code>a = a.set_index('user_id')</code> or use the <code>inplace=True</code> parameter with <code>a.set_index('user_id', inplace=True)</code> or neither of those because we'll be chaining ...
pandas|numpy|select|dataframe|indexing
1
11,420
61,102,268
Can't run Tensorflow-federated on GPU
<p>I am trying to run my python code which uses <code>tensorflow-federated</code> on a GPU. To set up my environment, I use <code>venv</code>. First, I install <code>tensorflow-gpu</code>, and my python code then can recognize the GPU, I use <code>tf.test.gpu_device_name()</code>. However, as soon as I install <code>te...
<p>It's hard to say exactly what the problem is here, but I do have a suspicion.</p> <p>TFF <a href="https://github.com/tensorflow/federated/blob/master/tensorflow_federated/tools/development/setup.py#L84" rel="nofollow noreferrer">declares TensorFlow 2.1 as a required package</a>; this may mean that your TF-gpu insta...
tensorflow-federated
2
11,421
60,948,836
Get RGB channels from a list of arrays
<p>I have list of RGB images I would like to take each channel from a image in the list and reshape it. However, I am having an issue extracting the channels from the list of arrays.</p> <p>Please refer the below code;</p> <p><code>difference[0].shape</code></p> <p>Output;</p> <p><code>(1280,720,3)</code></p> <p>T...
<p>Assuming <code>difference[0]</code> is a numpy array of shape <code>(1280,720,3)</code>, you can use <code>difference[0][:,:,0]</code> to access all the data for the first dimension.</p> <p><code>difference[0][:,:,0].shape</code> will give you <code>(1280, 720)</code>.</p> <p><code>difference[0][:,:,0].shape</code...
python|arrays|python-3.x|list|numpy
2
11,422
71,672,074
TFF: evaluating the federated learning model and got a large increase of loss value
<p>I am trying to evaluate the Federated Learning model following this <a href="https://www.tensorflow.org/federated/tutorials/building_your_own_federated_learning_algorithm" rel="nofollow noreferrer">tutorial</a>. As in the code below</p> <pre><code>test_data = test.create_tf_dataset_from_all_clients().map(reshape_dat...
<p>This can happen if the model is predicting the correct classes but with lower confidence. E.g for label0 if the ground truth is 1 and you predict 0.45 the accuracy measure would count this as FN. but if your model predicts it as 0.51 this will be counted as TP but the loss value won’t change much. Similarly if label...
python|tensorflow|tensorflow-federated
2
11,423
71,658,556
Pandas 0.19.0 explode() workaround
<p>Good Day everyone!</p> <p>I need help with alternatives or a workaround for explode() in pandas 0.19.0 I have this csv files</p> <pre><code> item CODE 0 apple REDGRNYLW 1 strawberry REDWHT 2 corn YLWREDPRLWHTPNK </code></pre> <p>I need to get this result</p> <pre><code> item CODE 1 appl...
<p>Convert ouput of function to <code>Series</code> and use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a>:</p> <pre><code>df_splitted = (df2.set_index(df2.columns.drop('CODE', 1).tolist()) .CODE.apply(lambda...
python|pandas|explode
2
11,424
42,507,589
MFCC Sampling frequency
<p>I want to obtain MFCC values of my wav file. Here is my code: </p> <pre><code>&gt; import numpy as np &gt; import scipy.io.wavfile &gt; from scikits.talkbox.features import mfcc &gt; sr1,x1=scipy.io.wavfile.read("filename.wav") &gt; ceps1,mspec1,spec1=mfcc(x1) </code></pre> <p>The value of sr1=22050. But in the ...
<p>Take a look at <a href="https://github.com/cournape/talkbox/blob/master/scikits/talkbox/features/mfcc.py#L47" rel="nofollow noreferrer">the docstring for <code>mfcc</code></a>. The signature of the function is</p> <pre><code>def mfcc(input, nwin=256, nfft=512, fs=16000, nceps=13): </code></pre> <p>As you noted in...
python|numpy|audio|scipy|scikit-learn
0
11,425
42,353,600
How do I create a multilevel index from column names?
<p>I want to create an index as part of a multilevel index from data that is embedded in a column name. This question is much easier to show than describe. This is what my original data looks like:</p> <pre><code>d = {'time':[0,1,2], 'part_0_hits': [100,200,300], 'part_1_hits': [25,50,75]} df = pd.DataFrame(d) </code>...
<p>You can use pd.melt for this</p> <pre><code>df = pd.melt(df, id_vars=["time"],var_name="part", value_name="hits") df['part'] = df['part'].str.extract('(\d+)').astype(int) </code></pre> <p>You get</p> <pre><code> time part hits 0 0 0 100 1 1 0 200 2 2 0 300 3 0...
python|pandas|multi-index
2
11,426
69,683,380
Efficiently counting records with date in between two columns
<p>Say I have this DataFrame:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;"></th> <th style="text-align: left;">user</th> <th style="text-align: left;">sub_date</th> <th style="text-align: left;">unsub_date</th> <th style="text-align: left;">group</th> </tr> </t...
<p>Using a smaller date range for convenience</p> <p>Note: my users df is different from OPs. I've changed around a few dates to make the outputs smaller</p> <pre class="lang-py prettyprint-override"><code>In [26]: import pandas as pd ...: import datetime as dt ...: ...: users = pd.DataFrame( ...: [...
python|pandas
2
11,427
45,721,037
Idiomatic clip on quantile for DataFrame
<p>I am trying to clip outliers in the DataFrame based on quantiles for each column. Let's say </p> <p><code>df = pd.DataFrame(pd.np.random.randn(10,2))</code></p> <pre><code>0 1 0 0.734355 0.594992 1 -0.745949 0.597601 2 0.295606 0.972196 3 0.474539 1.462364 4 0.238838 0.684790 5 -0.65909...
<p>You can use clip and align on the first axis:</p> <pre><code>df.clip(df.quantile(0.05), df.quantile(0.95), axis=1) Out: 0 1 0 0.734355 0.594992 1 -0.706864 0.597601 2 0.295606 0.972196 3 0.474539 1.241788 4 0.238838 0.684790 5 -0.659094 0.451718 6 0.675360 -0.884488 7 0.713914 0.1351...
python|pandas|numpy
8
11,428
45,642,621
How can i save tensors object to an numpy array?
<p>I have implemented autoencoder on my custom images data for sign language recognition.Now i want to save tensors object of the output layer to an numpy array. I tried Session.run(tensor) and tensor.eval(). Here is my code.</p> <pre><code>#define model x= tf.placeholder(tf.float32,[None,784]) y_=tf.placeholder(tf.fl...
<p>That's because <code>y</code> is a tensor in the graph and not a variable. When you run <code>.eval()</code> on a variable, it gives you the current value held by that variable in that session but if you run <code>.eval()</code> on a tensor instead like <code>tf.argmax(y, 1).eval()</code> in your case then tensor fl...
python|tensorflow|tensor
3
11,429
62,683,489
How to subset a pandas timeindexed data based on a list of bespoke times?
<p>I have a dataframe that is time indexed as below:</p> <pre><code>date 2020-06-17 23:00:00 558 2020-06-17 23:01:00 184 2020-06-17 23:02:00 113 2020-06-17 23:03:00 85 2020-06-17 23:04:00 47 ... 2020-07-01 18:48:00 203 2020-07-01 18:49:00 118 2020-07-01 18:50:00 236 2020...
<p>This is my approach, first you would need to split the datetime objects into date and hh:mm:ss format. Afterwards, we'll transform the <code>hh:mm:ss</code> into strings, and use <code>.isin(tss)</code> as the mask for the filtering. All in all:</p> <pre><code>df = df.reset_index() df = df[df['date'].map(lambda x: ...
pandas|subset
1
11,430
62,727,183
Numpy select over second axis
<p>I know this is supposed to be simple but I can't figure it out.</p> <p>The problem:</p> <pre><code>gt_prices = np.random.uniform(0, 100, size = (121147, 28)) pred_idxs = np.random.randint(0, 28 , size = (121147,)) print(gt_prices.shape, pred_idxs.shape) (121147, 28) (121147,) </code></pre> <p>I want to get an array...
<p>You can do the following (used a smaller dimension of 3 for checking the correctness easier)</p> <pre><code>gt_prices = np.random.uniform(0, 100, size = (3, 28)) pred_idxs = np.random.randint(0, 28 , size = (3,)) indices = np.expand_dims(pred_idxs, axis=1) gt_prices[np.arange(gt_prices.shape[0])[:,None], indices] <...
python|numpy|indexing
1
11,431
62,873,293
Count how many initial elements in Pandas Series equal to a certain value?
<p>As in question. I know how to compute it, but is there better/faster/more elegant way to do this? Cnt is the result.</p> <pre><code>s = pd.Series( np.random.randint(2, size=10) ) cnt = 0 for n in s: if n != 0: break else: cnt += 1 continue </code></pre>
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>Series.eq</code></a> to create a <code>boolean mask</code> then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cummin.html" rel="nofollow noreferrer"><...
python|pandas|series
3
11,432
54,530,941
Cleaning up and concatenation of a 2D masked array of strings containing peculiar characters with numpy
<p>Reading a netCDF file, one of the variables is a 2D string array looking like this:</p> <pre><code>[[' ' ' ' ' ' 'B' 'l' 'i' ' ' ' '] ['+' -- '\xaa' -- 'F' 'o' 'o' ' '] [' ' '1' ']' -- 'B' 'l' 'a' ' '] [' ' '\x1a' -- '\x98' -- 'B' 'l' 'o']] </code></pre> <p><strong>My desired output:</strong></p> <pre><code>['...
<p>Can you use this?</p> <pre><code> import numpy as np a = np.ma.masked_array([(' ', ' ', ' ', 'B', 'l', 'i', ' ', ' ' ), ('+', ' ', '\xaa', ' ', 'F', 'o', 'o', ' '), (' ', '1', ']', ' ', 'B', 'l', 'a', ' '), (' ', '\x1a', ' '...
python|numpy
1
11,433
54,378,808
Sort dataframe row while preserving columns
<p>I have a pandas dataframe something like shown below:</p> <pre><code> U1 U2 U3 U1 1.0 0.0 0.2 U2 0.4 1.0 0.0 U3 0.0 0.45 1.0 </code></pre> <p>Here, U1, U2 and U3 are indexes and column headers. I want...
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow noreferrer"><code>numpy.argsort</code></a> for positions and then reorder values of columns and by values of DataFrame:</p> <pre><code>pos = df.values.argsort(axis=1) df1 = pd.DataFrame(df.columns[pos], index...
python|pandas|numpy|dataframe
2
11,434
54,442,060
Pandas : Problem with aggregation by periods of two months
<p>I want to aggregate data by periods of two months by using the groupby method of pandas. And I cannot achieve the exepected results. Indeed I have data that spans 4 months. Therefore I want two periods : the first one between 2018-06-01 and 2018-07-31 and the seconde one between 2018-08-01 and 2018-09-30. Below in t...
<p>I don't think it possible with your approach, because of how time frequencies are defined in pandas. The closest I could get was:</p> <pre><code>In [22]: test.groupby(pd.Grouper(key='A', freq='2M', closed='left', base="2018-06-01")).sum() ...
python|pandas-groupby
0
11,435
54,540,018
What does tensorflow's tables_initializer do?
<p>The documentation is not very clear <a href="https://www.tensorflow.org/api_docs/python/tf/initializers/tables_initializer" rel="nofollow noreferrer">link</a> The vague description says that it initializes tables. What tables are those?</p>
<p>Tables in TensorFlow generally refer to data structures supporting lookup operations, i.e. map-like collections. So far, these operations have lived under <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/lookup" rel="nofollow noreferrer"><code>tf.contrib.lookup</code></a>, but it seems the TensorFlow t...
python|tensorflow|machine-learning
4
11,436
54,585,729
CNN implementation using Keras and Tensorflow
<p>I have created a CNN model using <strong>Keras</strong> and I am training it on a <strong>MNIST</strong> dataset. I got a reasonable accuracy around 98%, which is what I expected:</p> <pre><code>model = Sequential() model.add(Conv2D(64, 5, activation="relu", input_shape=(28, 28, 1))) model.add(MaxPool2D()) model.ad...
<p>I don't see any mistakes in your code. Note that your current model is heavily parameterized for such a simple problem because of the <code>Dense</code> layers, which introduce over 260k trainable parameters:</p> <pre><code>_________________________________________________________________ Layer (type) ...
tensorflow|keras|conv-neural-network
3
11,437
73,554,531
Pandas allocation / delegation of unique values in a dataframe column to a user from a list
<p>I have a Dataframe of email addresses with their domains. I have a list of users 1-5</p> <pre><code>users = [1, 2, 3, 4, 5] </code></pre> <p>I need to allocate each unique domain to a user id, I need to ensure that multiples of the same domain are always allocated to the same user id, however the individual domains ...
<p>Firstly, to get the unique domains as a dataframe:</p> <pre><code>unique = pd.DataFrame(df['domain'].drop_duplicates().reset_index(drop=True)) domain 0 gmail.com 1 hotmail.com 2 email.com 3 moestavern.com 4 simpson.net 5 sax.com 6 work.net 7 teacher.net </code></pr...
pandas|dataframe
1
11,438
73,820,008
Merged Excel Column Headers in Pandas
<p>I'm trying to read an excel file that has some merged column headers using pandas. The file looks as below:</p> <p><a href="https://i.stack.imgur.com/burYY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/burYY.png" alt="enter image description here" /></a></p> <p>I want the output to be as below:<...
<p>This is usually called multiple headers, - and <code>pd.read_excel</code> also <code>pd.read_csv</code> has options to represent it. simply use, <code>header</code> parameter. Later flatten the header as per example below:</p> <pre><code>df = pd.read_excel('test.xlsx', header=[0,1]) # using first and second row as h...
python|pandas|jupyter-notebook
0
11,439
73,664,429
Selecting from large array based on broadcasted smaller array - numba?
<p>I have a data matrix of dimensions (<code>a</code>, <code>b</code>, <code>c</code>), and a selecting matrix of that is broadcaste-able (let's say, dimensions (<code>a</code>, <code>c</code>)).</p> <pre><code>import numpy as np dim1, dim2, dim3 = 4, 5, 6 d1 = np.ones((dim1,)) d2 = np.ones((dim2,)) d3 = np.arange(dim3...
<p>The usual solution to speed up this kind of problem is to find the size of the output array first and then fill it (possibly in parallel when it is possible and this worth it). Here is an example (untested):</p> <pre class="lang-py prettyprint-override"><code>@numba.jit(nopython=True) def select_large_array_using_sm...
python|numpy|numba|array-broadcasting
2
11,440
71,120,895
How to exclude the point itself in Sklearn NearestNeighbors?
<p>I have 400,000 customers data, each of them has 40 attributes. The DataFame looks like:</p> <pre><code> A1 A2 ... A40 0 xx xx ... xx 1 xx xx ... xx 2 xx xx ... xx ... ... 399,999 xx xx ... xx </code></pre> <p>I first standardize these data by sklearn's StandardScaler. Now we ...
<p>As I see from the second list of the tuple, examples are sorted in the order the same as the original order from the DataFrame. So, for the second list, it needs to remove from each example the <strong>element</strong> equals the index of the example in the list. For the first list, needs to delete element with the ...
python|pandas|numpy|scikit-learn|nearest-neighbor
0
11,441
71,303,408
What is equivalent to MATLAB griddedInterpolant function in python?
<p>I tried <code>scipy.interpolate.RegularGridInterpolator</code> but MATLAB and python give me results with tiny different (For example: python: -151736.1266937256 MATLAB: -151736.1266989708). And I do care about those different decimals.</p>
<p>Those two functions are equivalent. However, <code>MATLAB</code>'s <code>griddedInterpolant</code> has multiple interpolation methods, whilst <code>RegularGridInterpolator</code> only seems to support <code>linear</code> and <code>nearest</code>. With <code>MATLAB</code>, this gives you more possibilities to choose ...
python|numpy|matlab|scipy
0
11,442
52,258,002
How to use groupby and grouper properly for accumulating column 'A' and averaging column 'B', month by month
<p>I have a pandas data with <strong>3</strong> columns: </p> <p><strong>date</strong>: from 1/1/2018 up until 8/23/2019, column <strong>A</strong> and column <strong>B</strong>.</p> <pre><code>import pandas as pd df = pd.DataFrame(np.random.randint(0,10,size=(600, 2)), columns=list('AB')) df['date'] = pd.DataFrame(p...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.agg</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.month.html" rel="nofollow noreferrer"><code>Dateti...
python|pandas|pandas-groupby
1
11,443
52,340,970
Internal compiler error: killed (program cc1plus) on MAC OS Sierra
<p>doing a compilation on MAC... (ps: for mxnet...)</p> <p>got an error msg...</p> <p>CMakeFiles/mxnet_static.dir/src/operator/tensor/indexing_op.cc.o -c /work/mxnet/src/operator/tensor/indexing_op.cc armv7-unknown-linux-gnueabi-g++: internal compiler error: Killed (program cc1plus) Please submit a full bug report......
<p>problem solved...</p> <p>i reboot my build machine and close most applications. this clean up my memory. I then redo the build and the build went through just fine.</p> <p>Just a reference for others..</p>
macos|tensorflow|gcc|compiler-errors
6
11,444
52,183,433
Tensorflow Loss is always 0.0
<p>i've done the Tutorial from sentdex. But when I excecute the programm, loss is always 0.0.</p> <pre><code>Epoch 0 completed out of 10 loss: 0.0 Epoch 1 completed out of 10 loss: 0.0 Epoch 2 completed out of 10 loss: 0.0 Epoch 3 completed out of 10 loss: 0.0 Epoch 4 completed out of 10 loss: 0.0 Epoch 5 completed ou...
<p>Your algorithm seems to work : Here is a screenshot : (i have just copy paste your code) </p> <p><a href="https://i.stack.imgur.com/7ZHbh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7ZHbh.png" alt="enter image description here"></a></p> <p>My configuration :</p> <p>tensorflow ...
python|tensorflow
1
11,445
60,478,562
Fabricate a datset to test PCA in Sklearn?
<p>I would like to test my workflow for PCA, to do so I want to create a dataset with lets say 3 features with a set relationship between those features. then apply the PCA and check if the those relationships were captures, what is the most straightforward way to do it in Python ?</p> <p>Thank you!</p>
<p>You can create samples where two features are independent of each other and a third feature is a linear combination of the other two. </p> <p>For example: </p> <pre><code>import numpy as np from numpy.random import random N_SAMPLES = 1000 samples = random((N_SAMPLES, 3)) # Let us suppose that the column `1` wil...
python|numpy|dataframe|pca
0
11,446
60,493,991
Best way of joining many time series in pandas to a single datetime index?
<p>I am reading many CSV files. Each one contains time series data. For example:</p> <pre><code>import pandas as pd csv_a = [['2019-05-25 10:00', 25, 60], ['2019-05-25 10:05', 26, 25], ['2019-05-25 10:10', 27, 63], ['2019-05-25 10:20', 28, 62]] df_a = pd.DataFrame(csv_a, columns=["Timestamp...
<p>As I understand you already had a custom datetimeindex <code>index</code> and want to join each time series by this <code>index</code>. Try <code>combine_first</code> and <code>reindex</code>. If you have multiple time series to join, you need to use loop or use python <code>reduce</code></p> <pre><code>df_out = df...
python|pandas|dataframe
3
11,447
60,721,910
How to create a pandas dataframe vector that has values based on a groupby
<p>given the following data:</p> <pre class="lang-py prettyprint-override"><code>x1 = 'one' x2 = 'two' x3 = 'three' y1 = 'yes' y2 = 'no' n = 3 df = pd.DataFrame(dict( a = [x1]*n + [x2]*n + [x3]*n, b = [ y1, y1, y2, y2, y2, y2, y2, y2, y1...
<p>IIUC, you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.transform.html" rel="nofollow noreferrer"><code>Groupby+transform</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.any.html" rel="nofollow noreferrer"><code>any</cod...
python|pandas|conditional-statements|grouping
2
11,448
60,727,762
Iterating a tf.data.Dataset.from_generator for a keras image generator.flow_from_dir throw errors
<p>This is the case of using Keras ImageDataGenerator with .flow_from_directory, wrapping it with tf.data.Dataset.from_generator(...). The dataset failed in any attempt to iterate through it.</p> <p>Error summary:</p> <p>InvalidArgumentError: TypeError: endswith first arg must be bytes or a tuple of bytes, not str</p...
<p>As per this <a href="https://stackoverflow.com/a/49280127/11253331">Stack Overflow Answer</a>, you can make your code to work properly by replacing </p> <pre><code>gen = img_gen.flow_from_directory(flowers_root_path) </code></pre> <p>with </p> <pre><code>def Gen(): gen = img_gen.flow_from_directory(flowers_root...
python-3.x|tensorflow|tensorflow-datasets|tf.keras
0
11,449
72,558,113
How to subtract one column from another in a dynamic set of columns followed by multiplication of another column in a pandas dataframe?
<p>I have a dataframe that has multiple columns. Out of which I need to pick up few columns, subtract one from the other, and then multiply the result with another column.</p> <p>For demonstration, I have simulated a simple dataframe, but with a similar structure to my actual dataframe.</p> <p><strong>Below is what I t...
<p>Idea is multiple all columns without first by <code>-1</code>, then sum and last multiple by <code>col4</code>:</p> <pre><code>d = dict.fromkeys(columnlist[1:], -1) d[columnlist[0]] = 1 print (d) {'col2': -1, 'col3': -1, 'col1': 1} df['out'] = df[columnlist].mul(pd.Series(d), axis=1).sum(axis=1).mul(df['col4']) pri...
pandas|dataframe
1
11,450
72,817,807
Python get percentage increase based on datetime columns on previous days
<p>I'm trying to calculate the percentage of increase in a price, based on the price of the previous day and the price of two days before. The problem I'm fancing is that I don't know how to access to the element of two days before properly.</p> <p>The dataset is the following:</p> <div class="s-table-container"> <tabl...
<h3><code>groupby</code> + <code>pct_change</code></h3> <pre><code>g = df.groupby('slug') df['%increase_24'] = g['price_usd'].pct_change(1) df['%increase_48'] = g['price_usd'].pct_change(2) </code></pre> <hr /> <pre><code> slug datetime price_usd %increase_24 %increase_48 0 bitcoin 2022...
python|pandas|date|datetime|percentage
2
11,451
72,618,075
How to get nearest neighbor for every element of array A from array B
<p>I need to create function <code>nearest_neighbor(src, dst)</code>, which accepts two arrays of 2D points, and for every point of array A calculates distance and index to closest neighbor from array B.</p> <p>Example input:</p> <pre><code>src = np.array([[1,1], [2,2],[3,3],[4,4],[9,9]]) dst = np.array([[6,7],[10,10],...
<p>You can use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow noreferrer"><code>scipy.spatial.distance.cdist</code></a>:</p> <pre><code>from scipy.spatial.distance import cdist # compute matrix of distances dist = cdist(src, dst) # get min distance close...
python|arrays|numpy|scikit-learn|computer-vision
2
11,452
72,586,041
Pandas apply function to each row by calculating multiple columns
<p>I have been stacked by an easy question, and my question title might be inappropriate.</p> <pre><code>df = pd.DataFrame(list(zip(['a', 'a', 'b', 'b', 'c', 'c', 'c'], ['a1', 'a2', 'b1', 'b2', 'c1', 'c2', 'c3'], [110, 80, 100, 180, 12], ...
<p>IIUC, you can use:</p> <pre><code>out = (df .groupby('name') .apply(lambda g: g['amount'].mul(g['con']).sum()/g['amount'].sum()) ) </code></pre> <p>output:</p> <pre><code>name a 5.842105 b 4.571429 c 10.000000 dtype: float64 </code></pre>
python|pandas|dataframe|apply
2
11,453
59,534,825
Multi-dimension input to a neural network
<p>I have a neural network with many layers. I have the input to the neural network of dimension <code>[batch_size, 7, 4]</code>. When this input is passed through the network, I observed that only the third dimension of the input keeps changing, that is if my first layer has 20 outputs, then the output of the second l...
<p><strong>Answer to Question 1</strong>: The data values in 2nd dimension (<code>axis=1</code>) are not being used because if you look at the output of code snippet below (assuming <code>batch_size=2</code>):</p> <pre><code>&gt;&gt;&gt; input1 = tf.placeholder(float, shape=[2,7,4]) &gt;&gt;&gt; tf.layers.dense(inputs...
python|tensorflow|machine-learning|deep-learning|neural-network
0
11,454
61,667,037
batch size on multiple GPUs tensorflow
<p>With tensorflow keras, if I use batch_size=8, and has tf.distribute.MirroredStrategy() with 4 GPUs, for each step in the training, does it has (1) 8 batch, in which each GPU has 2 batch or (2) 4x8 batch, in which each GPU has 8 batch</p> <p>I thought it is the second case. Please correct me if I am wrong. If it is...
<p>The first interpretation is correct. So if you set batch_size=8. Each GPU has batch size 2 and performs forward and backward passes based on batch size 2. Finally, gradients from 4 GPUs are merged by averaging which is equivalent that batch_size=8 would be processed on single GPU.</p> <p>Here one can find good exapl...
tensorflow|tensorflow2.0
1
11,455
61,666,069
How do you predict future values with this LSTM-RNN model I've built below?
<p>I have successfully created the model, and it works good on the test data. I don't know how to make it predict future values, can someone help me? I have tried changing the timestep to a negative value, so that the model predicts future values, but I wasn't able to carry it out because I got errors that led me in a...
<p>If your model works good on test data, so you trained it successfully. If it doesn't work on real world data, it seems your dataset is biased or your model is underfitted. That's it. There is no need to review code.</p>
python|tensorflow|machine-learning|keras|lstm
1
11,456
58,046,661
Get each unique word in a csv file tokenized
<p><a href="https://i.stack.imgur.com/53rEL.png" rel="nofollow noreferrer">Here is the CSV table</a>There are two columns in a CSV table. One is summaries and the other one is texts. Both columns were typeOfList before I combined them together, converted to data frame and saved as a CSV file. BTW, the texts in the tabl...
<p>You can use built-in csv pacakge to read csv file. And nltk to tokenize words:</p> <pre class="lang-py prettyprint-override"><code>from nltk.tokenize import word_tokenize import csv words = [] def get_data(): with open("sample_csv.csv", "r") as records: for record in csv.reader(records): y...
python|pandas|nlp|tokenize
1
11,457
54,838,962
How to add values under the diagonal of a dataframe array into a larger one based on row/column names?
<p>I want to build a correlation matrix of all authors of a series of articles.</p> <p>First I will build a correlation matrix of all authors to all authors initialized to zeros and represent them with a pandas dataframe.</p> <p>I will then get the author list of the first article and build a smaller dataframe initil...
<p>I have found a good way of solving the above problem using itertools.combinations. Here is a sample code:</p> <pre><code>for coauthors in author_lists: # build all pairwise combinations of article's authors with no repetitions new_coauthorship = list(itertools.combinations(coauthors, 2)) # increment cel...
python|pandas|numpy|dataframe|data-science
0
11,458
55,123,896
What does executorRunTime consist of in Spark?
<p>Currently working on Spark, I collected some performance metrics through the custom Spark listener API for analysis purposes. I tried to make a stacked bar plot that shows the percentage of the time the executor passes executing the task, shuffling or in garbage collection pauses for three different machine learning...
<p>According to <a href="https://github.com/apache/spark/blob/master/core/src/main/scala/org/apache/spark/executor/TaskMetrics.scala#L71" rel="nofollow noreferrer">TaskMetrics.scala</a>:</p> <pre><code> * Time the executor spends actually running the task (including fetching shuffle data). */ def executorRunTime: L...
pandas|apache-spark|pyspark|apache-spark-mllib|metrics
0
11,459
49,733,658
Tensorflow evaluation
<p>I am running a tensor flow model and trying to understand its performance. However, I am not sure about some of the metrics in the results. I have used the Linear classifier using tf.estimator.LinearClassifier. The code and results are attached below:</p> <p>The model is:</p> <pre class="lang-py prettyprint-overri...
<p><code>auc_precision_recall</code> is "area under precision recall curve". AUC stands for "area under curve". There are plenty of references online for these concepts. Here is one: <a href="http://scikit-learn.org/stable/auto_examples/model_selection/plot_precision_recall.html" rel="nofollow noreferrer">http://scikit...
tensorflow
1
11,460
49,765,144
Weights in logistic regression in Keras layers
<p>Following is the logistic regression code that I am using to establish association between dose value (shape 672,1) and disease outcome (shape 672,1; binary outcome 0,1) using Keras. My objective is to calculate odds ratio, which I figured out to be exp(weights) and compare it with the odds ratio that I calculated u...
<p>I guess I have found the answer to my own question. The first number/array is for the weight term and the second array is for the bias term. Because if I add two columns in my feature table then I get two values in the weight array with a single value in the bias array, which makes sense.</p>
python|tensorflow|keras|logistic-regression
3
11,461
67,300,906
Creating and simplifying of bool formula in Python
<p>There is a problem of finding maximal internally stable graph sets by the Magu method (discrete mathematics in higher education). Given a graph with an adjacency matrix(already implemented), then you need to make Boolean formulas where there will be a conjunction of all disjunctions of negations of adjacent vertices...
<p>Problem solved</p> <pre><code>i = 0 j = 0 counter = 0 while i &lt; amount: while j &lt; amount: if matrix[i, j] == 1: x = symbols(str(i + 1)) y = symbols(str(j + 1)) if counter == 0: formula = (~x | ~y) counter += 1 else: ...
python|numpy|sympy|discrete-mathematics
0
11,462
67,598,004
RuntimeError: CUDA out of memory. When training with Yolact
<p>I have been trying to train with PyTorch for Yolact following the guide: <a href="https://github.com/dbolya/yolact" rel="nofollow noreferrer">https://github.com/dbolya/yolact</a></p> <p>Current GPU is RTX2070 and cudatoolkit of 11.1.1 is used.</p> <p>When I run the following:</p> <blockquote> <p>python train.py --co...
<p>there are several reason for this error some of them are</p> <ol> <li>your model is too dense with layers so you GPU is unable to train it</li> <li>the image input could be too large for the GPU to process</li> </ol> <p>and may be some other reasons what you can try is, look at your configs and make the batch size s...
python|pytorch
0
11,463
60,091,496
Can I retrain OpenCV DNN face detector using my own face dataset and .pb .pbtxt files provided by OpenCV?
<p>I want to fine tune existing OpenCV DNN face detector to a face images database that I own. I have opencv_face_detector.pbtxt and opencv_face_detector_uint8.pb tensorflow files provided by OpenCV. I wonder if based on this files is there any way to fit the model to my data? So far, I haven't also managed to find any...
<p>I don't see a way to do this in opencv, but I think you'd be able to load the model into tensorflow and use <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit" rel="nofollow noreferrer">model.fit()</a> to retrain.</p> <p>The usual advice about transfer learning applies. You'd probably want to fre...
python|opencv|tensorflow|caffe|face-detection
0
11,464
65,156,049
Concatenating matching column values between 2 dataframes
<p>I have 2 dataframes.</p> <p>df1 has 5 columns and 3 rows. Column 'B' has same value for row1 and 2.</p> <pre><code> A B C D E a b c d data1 o b g h data2 i j k l data3 </code></pre> <p>df2 has 4 columns and 2 rows</p> <pre><code> ...
<p>You can:</p> <ol> <li><code>merge</code> the required columns of the other dataframein</li> <li><code>groupby</code> the columns and join the strings together as desired</li> </ol> <hr /> <pre><code>(df2.merge(df1[['B','E']]) .groupby([*df1.columns[:-1]])['E'] .agg(':'.join).reset_index()) A B C D...
pandas|dataframe
0
11,465
65,437,493
convert string to float array in csv using tf.data
<p>I have a csv like this :</p> <pre><code>kw_text,kw_text_weight amazon google,0.5 0.5 google facebook microsoft,0.5 0.3 0.2 </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>kw_text</th> <th>kw_text_weight</th> </tr> </thead> <tbody> <tr> <td>amazon google</td> <td>0.5 0.5</td> </...
<p>I believe this is what you want:</p> <pre><code>import pandas as pd import tensorflow as tf d = {&quot;kw_text&quot;: [['amazon', 'google'], ['google', 'facebook', 'microsoft']], &quot;kw_text_weight&quot;: [['0.5', '0.5'], ['0.5', '0.3', '0.2']]} df = pd.DataFrame(d) # Convert string to float for i in rang...
tensorflow|tensorflow2.0
0
11,466
65,251,436
The minimum element in a numpy array remaining zero even after adding one to every element pointwise
<p>I am trying to get the log of an image for some further processing, the minimum pixel value in the image is zero and hence i am trying to take log(1+image), but even after adding 1 to every element the minimum value of the array is still showing as 0 and hence <em>np.log</em> is throwing a <em>divide by zero encount...
<p>Most likely due to <code>image.dtype</code> being unsigned (e.g. <code>uint8</code>), which makes sense since the pixel values are always positive. Due to the data type, pixels with value 255 will overflow when you add one and change to zero.</p> <pre><code>image = io.imread('./PET_image.tif').astype(np.uint64) </co...
python|numpy
1
11,467
49,945,058
what's the pipeline to train tensorflow attention-ocr on customized dataset?
<p>I've read some questions on stackoverflow about attention-ocr, and most of them are about the implementation detail of a specific step. What I wanted to know is the pipeline for us to fine-tune this model on our own dataset. </p> <p>As far as I know, the steps should be:</p> <p>0) Should we first download FSNS dat...
<p>The error was caused by incorrect version of Python. They should be run with Python 2, and you can just change the 'import' sentence to solve this error. Try to change the 'import fsns' to 'from datasets import fsns'. </p>
tensorflow|ocr|attention-model
0
11,468
49,976,644
count of one specific item of panda dataframe
<p>i have used following line to get the count of number of</p> <p>&quot;Read&quot; s from the specific column (containing READ,WRITE,NOP)of a file . which is not csv file but a .out file with \t as delimiter.<br/></p> <pre><code> data = pd.read_csv('xaa',usecols=[1], header=None,delimiter='\t') df2=df1.iloc[...
<p>I believe need select column <code>1</code> for <code>Series</code>, else get one column <code>DataFrame</code>:</p> <pre><code>count=df2[1].str.count("R").sum() </code></pre> <p>Or compare by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.eq.html" rel="nofollow noreferrer"><code>eq</...
python|pandas
1
11,469
63,756,915
How get Timeindex, where Two Dataframes both have only NaNs in Row?
<p>I have two dataframes X and Y (both have a timeindex). both have an intersection,but also indices which the other doesnt necessarily includes.</p> <p>How to get the timeindex, where both <strong>intersect</strong> and boths <strong>row is only-NaNs</strong>?</p> <p>reproducable:</p> <pre><code>import numpy as np, pa...
<p>Try this</p> <pre><code>i_X = X.index[X.join(Y).isna().all(1)] Out[20]: DatetimeIndex(['2019-07-18 08:52:00', '2019-07-18 09:00:00', '2019-07-18 09:01:00'], dtype='datetime64[ns]', freq=None) </code></pre>
python|pandas|numpy|dataframe|indexing
1
11,470
63,892,688
How to map images to a Pandas Dataframe from a Dictionary
<p><a href="https://stackoverflow.com/questions/53468558/adding-image-to-pandas-dataframe">This question</a> helped a lot with what I am trying to do. I now know how to insert images to a pandas dataframe, but now I want to figure out how to do it with a dictionary. For example, I have the following df</p> <pre><code> ...
<ul> <li>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>pandas.Series.map</code></a> to map the <code>images</code> to the <code>'team'</code></li> </ul> <pre class="lang-py prettyprint-override"><code>import pandas as pd from IPython.disp...
python|pandas|dataframe
4
11,471
46,933,176
check if at least one value exists in pandas dataframe index
<p>How can I check if at least one of the index of df2 is in df1?</p> <pre><code>df1 Val StartDate 2015-03-31 NaN 2015-04-03 NaN 2015-04-05 8.08 2015-04-06 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.isin.html" rel="nofollow noreferrer"><code>Index.isin</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.any.html" rel="nofollow noreferrer"><code>Index.any</code></a> for check at least one <code...
pandas|dataframe|indexing
1
11,472
46,733,814
Pandas: Condition based on list in a cell
<p>Dataframe looks like this (blank cells are '', field, extra_dimensions are columns)</p> <pre><code>field | extra_dimensions ------------------------ a | b | [abc, def] c | [ghi] </code></pre> <p>I have a list of required dimensions and extra dimensions:</p> <pre><code>required_dimensions = [123, 456]...
<p>By using <code>get_dummies</code> again .....</p> <pre><code>required_dimensions = ['123', '456'] df=pd.DataFrame({'field':list('abc'),'extra_dimensions':[[],['abc','def'],['ghi']]}) df=pd.get_dummies(df.set_index('field')['extra_dimensions'].apply(pd.Series).stack()).sum(level=0).reindex(df.field).fillna(0) d = di...
python|pandas
0
11,473
47,018,472
How to use custom Theano layers in Keras?
<p>I have custom layers defined in Theano. I'd like to use them in my Keras model. How can I do this? Do these layers (defined as classes) in Theano have to follow a certain format? </p> <p>I couldn't find any resource for this. It'd be very helpful if someone can guide me.</p>
<p><strong>Pure operations:</strong></p> <p>If these layers are pure operations, you can use keras <a href="https://keras.io/layers/core/#lambda" rel="nofollow noreferrer">Lambda</a> layers.</p> <p>The idea is to create a function taking one tensor (or list of tensors) and do all the operations inside this function:<...
tensorflow|keras|theano
1
11,474
63,074,751
Summing up two columns of pandas dataframe ignoring NaN
<p>I have a pandas dataframe as below:</p> <pre><code>import pandas as pd df = pd.DataFrame({'ORDER':[&quot;A&quot;, &quot;A&quot;], 'col1':[np.nan, np.nan], 'col2':[np.nan, 5]}) df ORDER col1 col2 0 A NaN NaN 1 A NaN 5.0 </code></pre> <p>I want to create a column 'new' as sum(col1, co...
<p>Use the <code>add</code> function on the two columns, which takes a <code>fill_value</code> argument that lets you replace <code>NaN</code>:</p> <pre><code>df['col1'].add(df['col2'], fill_value=0) 0 NaN 1 5.0 dtype: float64 </code></pre>
python-3.x|pandas
3
11,475
63,047,678
Offline Automatic Speech Recognition(ASR) In Android with maximum accuracy
<p>I am looking for ASR in android with maximum accuracy and went through some implementations as follows</p> <ol> <li>Android Recognizer(Native Android)</li> <li>Sphinx</li> <li>Tensor flow lite</li> <li>KeenASR</li> <li>kitt.ai</li> </ol> <p>Need some inputs about which one to use because for Android Recognizer when ...
<p>I found keen ASR with good offline support</p>
android|speech-recognition|speech-to-text|tensorflow-lite|cmusphinx
0
11,476
67,749,871
pandas data frame index issues
<p>I have downloaded the following data from yfinance api as follow:</p> <pre><code>import yfinance as yf symbols=['BTC-USD', 'SPY', 'TSLA', 'AAPL', 'CAKE', 'JBLU', 'MSFT'] data = yf.download(symbols, start=&quot;2015-01-01&quot;, end=&quot;2021-04-20&quot;) </code></pre> <p>I tried to choose appl from the data frame a...
<p>You can use cross-section <code>xs</code>:</p> <pre><code>data.xs('AAPL', axis=1, level=1) </code></pre> <p>Output:</p> <pre><code> Adj Close Close High Low Open Volume Date 2015-01-02 24.82 27.33 27.86 26.84 27.85 2...
pandas|dataframe|numpy
0
11,477
61,432,291
How to get the weights of layer in a keras model for each input
<p>I know that you can you Model.layer[layer_number].getWeights() to get weight of layer from a keras model at a certain point. I am only to get those weights for an epoch or a batch using callbacks during training. </p> <p>But I want to get the weights of the layer for each input in the training part. Or if possible ...
<p>This is a small example. You can use <code>custom callbacks</code> inside which you can access model's weights by layers (including activations (<code>layers.Activation</code>)). Just change based on your needs.</p> <p>This will print the weights after each epoch, you can plot them/ save them too or run any operati...
python|keras|tensorflow2.0|keras-layer
0
11,478
61,291,925
Copy Dataframe to column only if value exist in other columns
<p>I have a DataFrame like this.</p> <pre><code> SMS Email 1 - or " " or nan 2 3 - or " " or nan 100 - or " " or nan - or " " or nan </code></pre> <p>Here - or " " or nan means that position can be a dash or nan or a blank value. Now i want a...
<p>IIUC</p> <pre><code>df['Status']=df[['SMS','Email']].apply(pd.to_numeric,errors='coerce', axis=1).bfill(1).iloc[:,0] </code></pre>
python-3.x|pandas
1
11,479
68,751,520
how to specify start for a pandas time series with timedelta index?
<p>It seems that I can't specify a start for resampling a series with timedelta index.</p> <pre class="lang-py prettyprint-override"><code>s = pd.Series([1, 1, 1], index=[pd.Timedelta(&quot;1min&quot;), pd.Timedelta(&quot;4min&quot;), pd.Timedelta(&quot;8min&quot;)]) s </code></pre> <pre><code>0 days 00:01:00 1 0 d...
<p>The easiest method is to <code>reindex</code> your Series and use <code>pd.timedelta_range</code> to create the new index from <code>0</code> to <code>s.index.max()</code>:</p> <pre><code>&gt;&gt;&gt; s.resample(&quot;30S&quot;).count() \ .reindex(pd.timedelta_range(0, s.index.max(), freq='30S'), fill_value=0) ...
pandas
0
11,480
68,681,507
Can Tensorflow Lite models be used for inference on Windows 10?
<p>I converted an existing SavedModel to TFLite:</p> <pre><code>model = tf.keras.models.load_model(&quot;/path/to/original_model&quot;) converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert() with open(&quot;/path/to/optimized_model.tflite&quot;, 'wb') as f: f.write(tflite_model...
<p>In the TensorFlow version 2.5, only the models, converted from the <code>from_saved_model</code> API, will have a signature.</p>
tensorflow-lite
1
11,481
68,458,356
Accessing Excel files directly from RAM using Excel Writer
<p>In the documentation for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.ExcelWriter.html" rel="nofollow noreferrer">pd.ExcelWriter</a> we see the following code snippet:</p> <p>You can store Excel file in RAM:</p> <pre><code>import io df = pd.DataFrame([[&quot;ABC&quot;, &quot;XYZ&quot;]]...
<p>In the snippet you provided, the Excel file has been written to the <code>buffer</code> the same way as if it would have been stored on disk.</p> <p>Therefore you can read it back in a similar way as if you were reading from file:</p> <pre><code>pd.read_excel(buffer.getvalue()) </code></pre> <p>More on how <code>Byt...
python|python-3.x|pandas|pandas.excelwriter
1
11,482
53,051,989
How to use tf.contrib.rnn.convLSTMCell class in tensorflow
<p>I would like to use a convolution LSTM in my research but I'm having a difficult time figuring out the exact way to implement this class in tensorflow. Here is what I have so far. I get no errors, but I am seriously doubting my implementation. Can anyone confirm if I am doing this correctly?</p> <pre><code>n_input ...
<p>Yes, you are correct! The output dimension will match the input dimension. If you actually want the <code>(?,5,436,1024,2)</code> output, you will have to look at the history, <code>state.h</code>. the last four <code>[-4]</code> of it will still correspond to the output.</p>
python-2.7|tensorflow|deep-learning
1
11,483
53,335,338
How can I predict the next elements in a dataset with LSTM in Keras, python?
<p>This is my first time with Keras and LSTMs and I am working in a project in which I have many time series data to train with.</p> <p>I have around 13000 rows of data (1 column) with numerical values regarding to a degradation level of a component ending in a failure; and on the other side I have multiple datasets o...
<p>Try this: model.predict(newX)</p>
python|tensorflow|keras|lstm|predict
0
11,484
53,043,859
Transpose Fields csv, Python (Numpy or Pandas)
<p>I need to do somthing like this:</p> <p><a href="https://i.stack.imgur.com/0lpCC.png" rel="nofollow noreferrer">Image</a></p> <pre><code>ID 20170101 20170106 20170111 A 0.31 0.1 0.2 B 0.3 0.2 0.1 C 0.11 0.12 0.13 D 0.3 0.3 0.4 ID ...
<p>You can use the <code>melt</code> function:</p> <pre><code>In [1611]: df Out[1617]: ID 20170101 20170106 20170111 0 A 0.31 0.10 0.20 1 B 0.30 0.20 0.10 2 C 0.11 0.12 0.13 3 D 0.30 0.30 0.40 In [1613]: pd.melt(df, id_vars='ID', var_name='Date', v...
python|pandas|csv|numpy
0
11,485
53,011,321
Pandas list of dict in multiple excel sheets
<p>I have multiple lists of dict that converge to one list of dict to an excel file. The idea is to make an excel sheet for each dict, key(web1, web2), name and have the correct info in each sheet. The problem of the code below is that it make a excel file of one sheet. Any idea on how should I do it?</p> <pre><code>i...
<p><code>pandas</code> has an <code>ExcelWriter</code> helper, it's right in the docs.</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html</a></p> <pre><co...
python|excel|pandas
2
11,486
53,063,557
Deleting/dropping rows in pandas DataFrame with particular string in ANY column
<p>May be a simply answer so apologies in advance (minimal coding experience).</p> <p>I am trying to drop any rows with particular string (Economy 7) from ANY column and have been trying to go off this thread:</p> <p><a href="https://stackoverflow.com/questions/28679930/how-to-drop-rows-from-pandas-data-frame-that-co...
<p>You can select only object columns, obviously strings by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer"><code>select_dtypes</code></a>:</p> <pre><code>df = energy.select_dtypes(object) #added regex=False for improve performance like ment...
python|pandas
1
11,487
65,675,445
"for tokens_tensor, segments_tensors, att_mask, pos_id, trg in data_loader: NameError: name 'data_loader' is not defined"
<p>I am trying to implement question answering model with a BERT transformer implemented by jugapuff. Link to the code: <a href="https://github.com/jugapuff/BERT-for-bAbi-task" rel="nofollow noreferrer">https://github.com/jugapuff/BERT-for-bAbi-task</a></p> <p>After executing the main.py file which is written below as ...
<p>I will just give you some pointers:</p> <ul> <li><p><code>collate_fn</code> is not meant to be called with a dataset as argument. It is a special callback function given to a dataloader and used to collate batch elements into a batch.</p> </li> <li><p>Since <code>bAbi_Dataset</code> in <code>/dataloader.py</code> is...
pytorch|bert-language-model
0
11,488
65,649,660
Combine arbitrary shaped tensors
<p>I'd like to combine two variable length tensors.</p> <p>Since they don't match in shape I can't use tf.concat or tf.stack.</p> <p>So I thought I'd flatten one and then append it to each element of the other - but I don't see how to do that.</p> <p>For example,</p> <pre><code>a = [ [1,2], [3,4] ] flat_b = [5, 6] com...
<p>Using <code>tf.map_fn</code> with <code>tf.concat</code>, Example code:</p> <pre><code>import tensorflow as tf a = tf.constant([ [1,2], [3,4] ]) flat_b = [5, 6] flat_a = tf.reshape(a, (tf.reduce_prod(a.shape).numpy(), ))[:, tf.newaxis] print(flat_a) c = tf.map_fn(fn=lambda t: tf.concat([t, flat_b], axis=0), elems=f...
python|tensorflow
2
11,489
65,657,086
How can I express this custom loss function in tensorflow?
<p>I've got a loss function that fulfills my needs, but is only in PyTorch. I need to implement it into my TensorFlow code, but while most of it can trivially be &quot;translated&quot; I am stuck with a particular line:</p> <pre><code>y_hat[:, torch.arange(N), torch.arange(N)] = torch.finfo(y_hat.dtype).max # to be &q...
<h3>1. What does torch.finfo() do and how to express it in TensorFlow?</h3> <p><code>.finfo()</code> provides a neat way to get machine limits for floating-point types. This function is available in <a href="https://numpy.org/doc/stable/reference/generated/numpy.finfo.html" rel="nofollow noreferrer">Numpy</a>, <a href=...
python|tensorflow|machine-learning|keras|pytorch
1
11,490
65,810,229
How to find the highest median value in pandas data frame grouped by month?
<p>Problem Statement: Which month has the highest median of maximum_gust_speed (thats name of the column) of all available records? Also print its value.</p> <pre><code>Day 3280 non-null object Average temperature (°F) 3280 non-null float64 Average gustspeed (mph) 3280 non-null float64...
<p>I have applied the below for the answer. Test this out and let me know. I believe this the climate dataset in your case as well.</p> <p>First, create a Month column, in my case the months extracted were like eg - for January it came as '01'.</p> <p>Post that a group by of Maximum gust speed (mph) and Month. And then...
python|pandas
1
11,491
63,334,299
What is the correct way to define the loss function in tensorflow 2.+ in the following code?
<p>I am making a simple GAN neural network. My architecture is defined by two principal models a <code>Discriminator</code> and a <code>Generator</code>:</p> <pre><code>class Discriminator(tf.keras.Model): def __init__(self): super(Discriminator, self).__init__(name='') self.h0 = Linear(num_outputs=hidden_si...
<p>I solve the problem using <code>tf.GradientTape()</code> for update the weights. In the following way:</p> <pre><code>def run_opt_discriminator(real_sample, z_noise): with tf.GradientTape() as tape: D1x = discriminator(real_sample) gen_sample = generator(z_noise) D2x = discriminator(gen_sample) los...
python|tensorflow2.0
0
11,492
63,614,243
Assigning numbers to given string's letters
<p>I am currently trying to finish a project which wants encode given paragraph using given matrix. I wanted to start make a letter list:</p> <pre><code>letterlist = np.array([&quot; &quot;,&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;,&quot;F&quot;,&quot;G&quot;,&quot;H&quot;,&quot;I&quot;,&quo...
<p>The conversion to a number is done by converting the char to a ordinary number and then subtracting 64 because that is the starting ASCII-Index for 'A'</p> <p>Code looks like this:</p> <pre><code>from math import ceil samplestr = &quot;MEET ME MONDAY&quot; # Pad string to be dividable by 3 samplestr = samplestr.l...
python|string|numpy|encoding|integer
1
11,493
53,376,556
Pandas JSON_Normalize only specific columns
<p>I have a nested JSON structure which I need to flatten. On using JSON normalize it flattens all the keys. But, I want to flatten specific keys while preserving the other keys nested. How to achieve this with JSON normalize. The detail description of what I am trying to do is as follows.</p> <p>The JSON data that lo...
<p>How about you just separate <code>data</code> in to two separate dictionaries. Perform 2 different transform operations and then join the respective dataframes:</p> <pre><code>data1 = {k:v for k,v in data.iteritems() if k!='Image'} data2 = {k:v for k,v in data.iteritems() if k=='Image'} df = pd.io.json.json_normali...
python|pandas|scikit-learn|pandas-groupby|sklearn-pandas
0
11,494
53,545,551
Modeling a Poisson RV with an unknown number of structural changes
<p>I have some count data for user-interaction over the past 365 days. I have reason to believe that several events have occurred which change the rate at which users are interacting. The model is as follow:</p> <h2>Assumptions</h2> <ul> <li>Daily count data is (locally) drawn from a Poisson distribution with paramet...
<p>You're exactly right that models with an random number of latent variables are tricky to write in most existing tools, including TFP, because they require the shape of the inference computation to change dynamically during inference: the set of things to infer is itself one of the quantities you're doing inference o...
tensorflow-probability|probabilistic-programming
1
11,495
72,056,023
Extracting rows from list in data frame where at max numbers
<p>So i've been given a pandas data frame and created a definition for the maximum variable in one column.</p> <p>max_energy = D202['USAGE'].max() max_energy</p> <p>I need to extract the rows with maximum values</p>
<p>Use:</p> <pre><code> df = D202[D202['USAGE'].eq(D202['USAGE'].max())] </code></pre>
python|pandas
0
11,496
55,547,049
ValueError: np.nan is an invalid document, expected byte or unicode string
<p>I am trying to perform sentiment analysis on Uber-Review. I have used Naive bays sklearn to perform sentiment analyis,I used trianing data from kaggle on reviwes, But The test data is in xlsx sheet, I used pandas to create data frame, </p> <pre><code>import pandas as pd test=pd.read_excel("uber.xlsx",sep="\t",enco...
<p>the Data that i have found in Kaggle for Uber is <a href="https://www.kaggle.com/purvank/uber-rider-reviews-dataset/downloads/Uber_Ride_Reviews.csv/2" rel="nofollow noreferrer">https://www.kaggle.com/purvank/uber-rider-reviews-dataset/downloads/Uber_Ride_Reviews.csv/2</a></p> <p>now coming to your problem</p> <pre...
pandas|python-3.6|naivebayes|sklearn-pandas
1
11,497
56,842,889
Compute a convolution with weights that where computed by another function
<p>I would like to perform a conv2d but a special one because I compute the weights of a conv2d layer in a function for each sample. Can I simply assign the weights of a given layer for each sample?</p> <p>I am implementing the Spatially variant convolution of this paper : <a href="https://arxiv.org/abs/1804.00389" re...
<p>It is actually very simple : torch.nn.functional.conv2d !</p>
pytorch
1
11,498
66,942,596
TF2 Object Detection - Custom training failed (OOM) after successful training in the past
<p>I train an object object detection model, based on pre-trained model from TF2 Object Detection efficientdet _d2_coco17_tpu-32. <a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/training.html" rel="nofollow noreferrer">https://tensorflow-object-detection-api-tutorial.readthedocs.io/en...
<p>I don't know what you did while your training. I give the reason. If you increase the batch size the oom error will occur. you need to check if any other unwanted processes are running with your GPU.Use the below command and end the unwanted process.</p> <pre><code>nvidia-smi </code></pre> <p>In a few cases image si...
python-3.x|tensorflow|ubuntu|tensorflow2.0|object-detection-api
0
11,499
66,885,720
How to change text format 12- to -12 and to convert to numeric?
<p>I have a dataframe where I have a column with the following structure:</p> <pre><code>Column1 12- 0 87 9708 987 607- </code></pre> <p>This is how the system output negative values, which is not in the right format. How can I take the - from the end in order to put in the beginning of the number and be able to conver...
<p>We could <code>str.replace</code> here along with <code>to_numeric</code>:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;Column1&quot;] = pd.to_numeric(df[&quot;Column1&quot;].str.replace(r'^(\d+)-$', r'-\1'), errors='coerce') </code></pre> <p>Note that the regex replacement used above would only fire...
python|pandas|string|dataframe|replace
1