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
357,800
50,157,416
BGR8 raw image conversion to numpy python
<p>So far i have tested acquiring images from a camera in the raw BGR8 format into a numpy array, I am at the point in which i can get access to the data however the image seems to have visible image artifacts (vertical lines etc) and only displays in greyscale.</p> <p>The following code is used to acquire the image i...
<p>Working example is:</p> <pre><code>image=ctrl.GetImageWindow(0,0, w,h) data = numpy.array(image, dtype=numpy.uint8).reshape(768,-1,3) </code></pre>
python|numpy|opencv|python-imaging-library
0
357,801
50,070,789
Keyerror when trying to testsuite pytest with pandas
<p>Hi there all machine learning and python experts. I seek your help.</p> <p>I have recently seen into google ml crash course. They recommended to get familiar with pandas before starting the crash course.</p> <p>So, I have installed pip v8.1.1 using python v3.5.2 and pandas from pip. And also installed pytest 3.5.1...
<p>To run tests in pandas you need to install a lot of <a href="https://github.com/pandas-dev/pandas/blob/master/ci/requirements_dev.txt" rel="nofollow noreferrer">development requirements</a>:</p> <pre><code>pip install -U [--user] ci/requirements_dev.txt </code></pre>
python|python-3.x|pandas|machine-learning|pytest
1
357,802
49,809,354
Searching sub string through 3Million Records in python
<p>I have a huge Data frame which has 3M records which has column called description. Also I have possible sub string set of around 5k.</p> <p>I want to get the rows in which the description contains any of the sub string.</p> <p>i used the following looping</p> <pre><code>for i in range(0,len(searchstring)): ss=s...
<p>Should be faster if you use pandas <code>isin()</code> function</p> <p>Example:</p> <pre><code>import pandas as pd a ='Hello world' ss = a.split(" ") df = pd.DataFrame({'col1': ['Hello', 'asd', 'asdasd', 'world']}) df.loc[df['col1'].isin(ss)].index </code></pre> <p>Returns a list of indexes:</p> <pre><code>Int6...
python|pandas
0
357,803
50,216,844
Convert XML to DataFrames
<p>I'm trying to read the tables from a [web page][1] into pandas DataFrames. <code>pandas.read_html</code> returns a list of empty tables because the tables from the HTML are indeed empty. They're probably populated dynamically.</p> <p>Someone <a href="https://stackoverflow.com/questions/50216844/python-convert-xml-t...
<p>Anytime one works with complex XML and needs simpler structures like flattened dataframes with two-dimensional row by column, one should consider <a href="https://stackoverflow.com/tags/xslt/info">XSLT</a>, the special purpose language designed to transform XML files into other XML, HTML, and as shown below even tex...
python|xml|pandas|xslt
2
357,804
63,891,902
How to do update rows in SQLite table using SQLite3 and Python
<p>I am new to python and I don't really understand the sql thing that well. Currently on the 6th week of team treehouse so please bare with me here if these are noob questions.</p> <p><strong>Goal</strong></p> <ol> <li>Import CSV with stock_tickers and 5 other columns of data</li> <li>Convert CSV into pandas dataframe...
<p>This is the <code>ON CONFLICT</code> clause of your query:</p> <pre><code>ON CONFLICT (stock_ticker) DO UPDATE SET (stock_status) </code></pre> <p>This is not valid SQLite syntax. If you want to update <code>stock_status</code> when another row already exists with the same <code>stock_ticker</code>, you can use ...
python|pandas|sqlite|sql-update|sql-insert
2
357,805
63,938,847
Python Django: Merge Dataframe performing Sum on overlapping columns
<p>I want to merge two DataFrames with exact the same column names. The overlapping columns can be added togheter. I'm having a bit of troubles because the grouping should be happening on the &quot;index&quot; called &quot;Date&quot; but I can't this index through using the 'Date' name.</p> <p>Actually, I just need the...
<p>Let say you have 2 df like this:</p> <pre><code>df1 = pd.DataFrame({'Adj Close':[1, 2]}, index=['2019-09-19','2019-09-20']) df2 = pd.DataFrame({'Adj Close':[3, 4, 5]}, index=['2019-09-19','2019-09-20','2019-09-21']) </code></pre> <p>df1</p> <pre><code> Adj Close 2019-09-19 1 2019-09-20 2...
python|django|pandas|dataframe|merge
1
357,806
63,821,407
Pandas selecting dataframe columns using a specific string and array/list
<p>I have a dataframe with hundreds of columns (stocks). My issue is that I need to always pull a specific column (date) followed by an array/list of others (dynamic).</p> <p>Previously I was doing something like this:</p> <pre><code>df = stocks[['date', 'AAPL', 'AMZN']] </code></pre> <p>but now if I need to dynamicall...
<p>Let us try</p> <pre><code>df = stocks[['date'] + rowData['symbol'].iloc[0]] </code></pre>
pandas
0
357,807
63,885,376
How to aggregate some of the levels in a deep nested `groupby` in pandas?
<p>I am doing the exercise on <a href="https://repl.it/@freeCodeCamp/fcc-medical-data-visualizer" rel="nofollow noreferrer">https://repl.it/@freeCodeCamp/fcc-medical-data-visualizer</a>, and the groupby problem stuck me:</p> <p>Now I get a tree like nested-level <code>groupby</code>, I want to get the total count of so...
<p>Check <code>sum</code> and know your <code>level</code></p> <pre><code>df = df.sum(level = [0, 6]) </code></pre>
pandas
1
357,808
63,831,839
What is the most efficient way to populate one pandas dataframe using another dataframe?
<p>I am wondering how I can most efficiently do the following operation so that I can also upscale it to dataframes with million rows+. I have 2 panda dataframes:</p> <p>Data1:</p> <pre><code>Position Letter 1 a 2 b 3 c 4 b 5 a </code></pre> <p>Data2:</p> <pre><code>...
<p>Best way is to use merge:</p> <pre><code>df = df1.merge(df2, on=['Letter']) print(df) Position Letter Weight 0 1 a 1 1 5 a 1 2 2 b 2 3 4 b 2 4 3 c 3 </code></pre>
python|pandas|dataframe|apply
1
357,809
64,144,121
Pandas reshaping and stacking dataframe
<p>I have an excel sheet in this format:</p> <pre><code>Source Hour Min1 Min2 Min3 online 0 0 0 0 online 1 1 2 0 online 2 3 4 5 </code></pre> <p>How do I use pandas to transform it to this format?</p> <pre><code>Hour 0 1 2 Min1 Min2 Min3 ...
<p>Just do <code>T</code>, notice I will recommend keep the <code>Source</code> as first level in the column</p> <pre><code>out = stacked.to_frame(0).T </code></pre>
python|pandas
2
357,810
63,990,833
Error when I try to calculate the normalization on Jupyter notebook (with '-' and df)
<p>I'm just discovering pandas, I tried to google the error but I found nothing. When I try to calculate this: <code>X = (X - X.min()) / (X.max() - X.min()) </code>knowing that (<code>X = titanic[['sex','age','fare','class','embark_town','alone']].copy())</code> I get this : <a href="https://i.stack.imgur.com/QQ2FY.png...
<p>You should normalize numerical features only (like fare in the Titanic dataset).</p>
python|pandas|machine-learning
0
357,811
63,995,370
Doing a for loop on bunch of tuples?
<p>I have 1002 tuples in which there are an index and an 11 columns data. I would like to write a for loop to make each of those columns one numpy array based on changing the column &quot;T&quot;. In the sense that each of theses data frames becomes stored in a separated data frame.</p> <pre><code>index &quot;T&q...
<p>Possibly it's because you calling &quot;T&quot;, that is a float number, you should try:</p> <pre><code>for index in df_train_list: df_train_array = np.array(df_train_list[&quot;T&quot;][1]) </code></pre>
python|numpy
0
357,812
63,866,156
tf__norm() takes 1 positional argument but 2 were given
<p>I a trying to pass a function to my tf dataset to normalize the non numerical data in my data frame, however I keep getting this error:</p> <p>TypeError: in user code: TypeError: tf__norm() takes 1 positional argument but 2 were given</p> <pre><code>def norm(dataframe): for header in dataframe._get_numeric_data(...
<p>Follow your code, the type of <em>ds</em> is BatchDataSet , Its element_spec is tuple which size is 2, but your norm function only needs one parameter, That's why it raise</p> <p><code>takes 1 positional argument but 2 were given</code></p> <p>More detail, the type of first elements is dict, the other is TensorSpec....
tensorflow|keras
0
357,813
63,822,730
Why do we need the custom dataset class and use of _getitem_ method in NLP, BERT fine tuning etc
<p>I am a newbie in NLP and has been studying the usage of BERT for NLP tasks. In many notebooks, I See that a custom dataset class is defined and <em>getitem</em> method is defined (along with len).</p> <p>Tweetdataset class in this notebook - <a href="https://www.kaggle.com/abhishek/roberta-inference-5-folds" rel="no...
<p>It is a recommended abstraction in pytorch to define <code>datasets</code> by inheriting <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.Dataset" rel="nofollow noreferrer"><code>torch.utils.data.Dataset</code></a>. Those objects define how many elements are there (<code>__len__</code> method) and...
nlp|pytorch|bert-language-model
1
357,814
63,859,568
get rows by time regardless of date in pandas
<p>I have data as follows:</p> <pre><code>Col1,ColDate a,2020-09-11 08:43:00 b,2020-09-12 09:43:00 c,13-09-2020 09:43:00 d,09/16/2020 10:43:00 e,09/19/2020 12:43:00 f,09/12/2020 15:43:00 </code></pre> <p>Intention is to get all rows between 0000 and 0900 hours, regardless of the date and its format. In pandas</p> <p>I ...
<p>Use <code>pandas.DataFrame.between_time</code>:</p> <pre><code>df[&quot;ColDate&quot;] = pd.to_datetime(df[&quot;ColDate&quot;]) # If not in datetime already new_df = df.set_index(&quot;ColDate&quot;).between_time(&quot;00:00:00&quot;, &quot;09:00:00&quot;) print(new_df.reset_index()) </code></pre> <p>Or other way a...
python|python-3.x|pandas
2
357,815
63,767,829
What am I doing wrong in calculating quartiles?
<pre><code>x = np.array([1, 3, 7, 11]) print(np.quantile(x, 0.75)) print(np.quantile(x, 0.25)) </code></pre> <pre><code>8.0 2.5 </code></pre> <p>How am I getting these as answers? What am I doing wrong? Am I being really dumb or is q1 and q3 9 and 2?</p>
<p>What you're doing wrong is not reading the <a href="https://numpy.org/doc/stable/reference/generated/numpy.quantile.html" rel="nofollow noreferrer">documentation</a>. The default interpolation is <code>linear</code>; you seem to expect <code>midpoint</code>.</p> <pre><code>x = np.array([1, 3, 7, 11]) print(np.quant...
python|numpy
3
357,816
64,131,836
Is there anyway to get efficientnet pre-trained weight in hdf5 format?
<p>I have some problems with getting pre-trained weights in efficientnet. So I googled for efficientnet.hdf5 but cannot find it. So is there anyway to get pre-trained weight in hdf5 format. Thank u.</p>
<pre><code>from tensorflow.keras.applications.efficientnet import EfficientNetB0, EfficientNetB5 model = EfficientNetB0(include_top=True, weights=&quot;imagenet&quot;, input_tensor=None, input_shape=None, pooling=None, classes=1000, classifier_activation=&quot;softmax&quot;) model.summary() # Keras H5 format(older me...
tensorflow|keras|conv-neural-network|efficientnet
1
357,817
64,055,945
Calculation new column in pandas dataframe from row by row calculation
<p>I am learning python and have come up with a way to calculate values row by row, but I am sure there is a more elegant (and quicker) solution. Here is simple example:</p> <pre><code>df = pd.DataFrame(np.random.rand(10,3), columns=list('abc')) df.head() a b c 0 0.207455 0.257266 0.453369 1 0.518193...
<p>Yes we have <code>shift</code> with <code>diff</code> and no for loop</p> <pre><code>df['d'] = ((df['a'] - df['b']) ** 2 + (df['a'].shift() - df['b'].shift()) ** 2)**0.5 df['e'] = (df['c'].diff()) * 1609 df a b c d e 0 0.207455 0.257266 0.453369 NaN NaN ...
python|pandas|dataframe
0
357,818
64,145,932
Filtering Pandas DataFrame by value in a column's lists
<p>I have a DataFrame that has a column of lists. I would like to return a subset of the Dataframe of those rows whose list contains a specified value.</p> <pre><code>test = pd.DataFrame({'detail_id': [10000, 10001, 10002], 'tokens': [['A', 'B', 'C'], ['A', 'D'], ['C', 'E', 'F', 'H']]}) </code></p...
<p>A good night's sleep and a re-reading of the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html" rel="nofollow noreferrer">selection documentation</a> has helped me figure it out. The documentation says that selection can accept a &quot;boolean array&quot;. So that's what I've done.</p> <...
pandas
0
357,819
63,923,672
Integrate sum of functions vs sum of integrated functions with scipy solve_ivp
<p>So I was wondering: Shouldn’t the sum of the integrals of some functions be equivalent to the integral of the sum of the functions?</p> <p>Here I integrate three arbitrary functions with the help of <code>scipy</code>’s <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html" rel...
<ol> <li>The initial values are inconsistent. You have to sum initial values too.</li> <li>If you sum solutions of</li> </ol> <pre><code>dy/dt = -y dy/dt = y y(0)=1 </code></pre> <p>you do not get the solution of</p> <pre><code>dy/dt = 0 </code></pre> <p>you get</p> <pre><code>cos(t) + y^t </code></pre> <p>But</p> <...
python|numpy|math|scipy|integral
0
357,820
63,875,039
Tensorflow Probability Sampling Take Long Time
<p>I am trying to use tfp for sampling process. draw samples from beta distribution and feed the result as probability input to draw sample from Binominal distribution. It took forever to run.</p> <p>Am I supposed to run it this way or is there an optimal way?</p> <p>'''</p> <pre><code>import tensorflow_probability as ...
<p>TFP Distributions support a concept we call &quot;batch shape&quot;. Here, by giving <code>probs=phi</code> with <code>phi.shape = [100000]</code>, you are effectively creating a &quot;batch&quot; of 100k Binomials. Then you're sampling 100k times from those, which is trying to create 1e10 samples, which is gonna ta...
tensorflow|sampling|montecarlo|tensorflow-probability
0
357,821
63,801,646
Drop rows if specific word is not present in a column where column have links and word need to be compare require splitting python
<p>here I am trying to analyze and practicing pandas.dataframe functions. Now I am trying to drop all rows which have not a specific word in the given column of links. <a href="https://i.stack.imgur.com/hGxwg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hGxwg.png" alt="enter image description here...
<p>This is a much nicer solution - will only leave rows contain 'Microsoft':</p> <pre><code>df = df[df['post_link'].str.contains('Microsoft')] </code></pre> <p>Following your request for multiple search terms, here you go:</p> <pre><code>searchfor = ['MicrosoftLife', 'MicrosoftTeam'] df = df[df['post_link'].str.contain...
python|pandas|dataframe
0
357,822
64,011,749
Tensorflow: 'Error: No gradients provided for any variable' with custom loss
<p>I'm getting an error when I try to run my code</p> <pre><code>ValueError: No gradients provided for any variable </code></pre> <p>Here's what my code looks like</p> <pre><code>optimizer = tf.keras.optimizers.Adam(learning_rate=1e-2) while True: #...other stuff if(isTimeToBackprop()): vStates = mod...
<p>Supposing you are working with Tensorflow 2.x, If you are trying to create a custom training step, to track the model gradients, you have to invoke the model under the <code>tf.GradientTape</code> context manager.</p> <p>Here you have your code updated to correctly work with the <code>GradientTape</code>:</p> <pre c...
python|tensorflow|gradient-descent|backpropagation
1
357,823
63,785,159
Pandas columns of lists, check if lists are intersecting
<p>I have a data frame, called <code>a</code>, that has the following structure:</p> <pre><code>df = pd.DataFrame({ 'id': [1, 2, 3], 'numbers_a': [[2, 3, 5], [1, 2, 4], [4, 6, 9]], 'numbers_b': [[2, 1, 3], [10, 11], [4, 5, 7]] }) df | id | numbers_a | numbers_b | |----|-----------|-----------| | 1 | [2, 3...
<p>Try set intersection:</p> <pre><code>df['numbers_a'].map(set) &amp; df['numbers_b'].map(set) 0 True 1 False 2 True dtype: bool </code></pre> <p>This works well with the overloaded pandas boolean operators, although it isn't particularly performant.</p> <hr /> <p>Another method involves list comprehension...
python|pandas|dataframe
3
357,824
64,133,919
Plot multiple line graph from Pandas into Seaborn
<p>I'm trying to plot a multi line-graph plot from a pandas dataframe using seaborn. Below is a .csv of the of the data and the desired plot. In excel I simply selected the whole dataset and swapped the axis. Technically there are 110 lines (rows) on this, but many aren't visible because they only contain 0's.</p> <p><...
<p>The seaborn <code>lineplot()</code> <a href="https://seaborn.pydata.org/generated/seaborn.lineplot.html" rel="nofollow noreferrer">documentation</a> says:</p> <blockquote> <p>Passing the entire wide-form dataset to <code>data</code> plots a separate line for each column</p> </blockquote> <p>Since you want a line for...
python|pandas|plot|seaborn
1
357,825
64,153,348
add element to a nested array in a dictionary converting series to readable dictionary with nested arrays python
<p>I need to add an element to an array that is inside a dictionary, This is my code:</p> <pre class="lang-py prettyprint-override"><code>indexes9 = [] dataInfected9 = {} for index, value in data9.items(): if index[0] not in indexes9: indexes9.append(index[0]) dataInfected9[index[1]].append(value) </cod...
<p>Using <code>dict.setdefault</code></p> <p><strong>Ex:</strong></p> <pre><code>dataInfected9 = {} indexes = set() #Using set to prevent dups. for (k, v), n in data9.items(): indexes.add(k) dataInfected9.setdefault(v, []).append(n) </code></pre>
python|arrays|python-3.x|pandas|dictionary
1
357,826
64,102,481
Is there an easy way to find the 'coordinates' of an element in a pandas dataframe?
<p>I have a dataframe 'ptable' which looks like this:</p> <p><img src="https://i.stack.imgur.com/b8ODY.png" alt="A 188 x 32 dataframe of the periodic table containing varying types of data." /></p> <p>We were given a very easy task of finding one value in the dataframe, the boiling point of argon. Their sample solution...
<p>Here is my solution:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd def locate(data, query, value, output): df = pd.DataFrame(data = data) # create a list of values in the query (column) values = df[query].tolist() row = 0 if value in values: row = values.index(v...
python|pandas|dataframe
1
357,827
63,958,039
How do I interpret tf.keras.Model.predict() output?
<p>I am having trouble finding the documentation I need on this. To summarize the issue, I have trained a tf.keras model using two classes of images, labeled as '0' or '1'. I now want to use this model to predict whether new images are a '0' or '1'. My question is as follows: <code>model.predict()</code> returns a numb...
<blockquote> <p>is <code>pred</code> the probability the image is a 1, and <code>1 - pred</code> the probability the image is a 0?</p> </blockquote> <p>Yes, that is correct. If you want to get hard class (i.e., 0 or 1), then you can threshold the output. 0.5 is a common threshold, but I have also seen 0.3. This is some...
python-3.x|tensorflow|keras|computer-vision
1
357,828
64,047,518
How to specify a columns dtype by its index rather than its name in pandas pd.read_excel
<p>I need to read data from Excel but while doing it I should not specify the columns by their names. How can I set data types using indexing?</p> <p>For instance:</p> <pre><code>df = pd.read_excel('file.xlsx', sheet_name='sheet1', index_col=None, dtype={'column_x':s...
<p>use <code>header=None</code> then access the columns by their index position.</p> <pre><code>df = pd.DataFrame({'A' : [0,1,2,3], 'B' : ['A','B','C','A']}) print(df.dtypes) A int64 B object dtype: object df.to_excel('file.xlsx'index=False) df = pd.read_excel('file.xlsx',index_col=None) print(df.dtypes) A ...
python|excel|pandas
0
357,829
63,781,059
Sorting a list of ordered dictionaries in Pandas for csv output
<p>I have added a dbf file into a Pandas series dataframe. The original data is in a listed dictionary like so.</p> <pre><code>0 {'a': 'av1','b': 'bv1', 'c' : 'cv1',... 1 {'a': 'av2', b': 'bv2', 'c' : 'cv2',... 2 {'a': 'av3', b': 'bv3', 'c' : 'cv3',... 3 {'a': 'av4', b': 'bv4', 'c' : 'cv4',... 4...
<p>We need to do <code>ast</code> then pass to <code>DataFrame</code></p> <pre><code>import ast yourdf = pd.DataFrame(df['col_name'].apply(ast.literal_eval).tolist()) Out[191]: a b c 0 av1 bv1 cv1 1 av1 bv1 cv1 </code></pre>
python|pandas|csv|dictionary|ordereddictionary
0
357,830
64,145,423
Improving Performance of Inflating data by generating missing sequential data
<p>I have a dataset which has missing data - around 10,000 to 500,000 rows.</p> <pre><code>1 2 3 13 14 15 18 26 ... </code></pre> <p>I need to fill the data in between so that it is continuous for subsequent processing.</p> <pre><code>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... </code></pre...
<p>Possibly I was looking at something like this - this runs 23 times faster. Not tested on the entire dataset though!</p> <pre><code># Optimization 2: Try out using Numpy array : start_time = time.time_ns() start_time_s = time.time() delta = 100 times = numpy.arange(start = start_time_s, stop =start_time_s + delta, s...
python|pandas|performance
0
357,831
64,032,945
Cast decimal number to datetime in Pandas
<p>I am attempting to convert a decimal number to a datatime. An example dateframe is:</p> <pre><code> timestep_time vehicle_angle vehicle_id vehicle_pos vehicle_speed vehicle_x vehicle_y Cluster 0 0.00 113.79 0 5.10 0.00 295.36 438.47 1 1 ...
<p>I received a <code>Decimal</code> Epoch time in milliseconds from an AWS response. I didn't see a simple way to convert that to a <code>datetime</code> with Panda unless you first cast it to an int or string.</p> <p>I used this:</p> <pre><code># cast from Decimal to int df[&quot;creationDate&quot;] = df[&quot;creat...
python|pandas|time
0
357,832
63,867,452
Normalization of dictionary values
<p>For normalization of elements in numpy arrary, we can use the sklearn normalize function:</p> <pre><code>import numpy as np from sklearn.preprocessing import normalize b=np.array([[0, 0.2, 0.2, 0.2, .30, .24, 0]]) print(type(b)) normalized = normalize(b) print(&quot;Normalized Data = &quot;, normalized) </code></pr...
<p>By default, the <code>Normalizer</code> function considers the <code>L-2</code> norm normalization, but in the following example we will additionally consider <code>L-1</code> norm normalization. Taking as example, the array you provided this will be</p> <pre><code>X = np.array([val for val in xy.values()]) # If yo...
python|numpy|dictionary|scikit-learn|normalization
1
357,833
63,769,671
How to subtract two columns of lists from each other in pandas?
<p>I have data in a tab-separated value text file that look like this:</p> <pre><code>FileName Onsets Offsets FileName1 [9, 270, 763] [188, 727, 1252] FileName2 [52, 634, 1166, 1775, 2104] [472, 1034, 1575, 1970, 2457] FileName3 [180, 560, 1332, 1532] [356, 1286, 1488, 2018] </code></pre> <p>These ...
<ul> <li>The first issue is, you have columns of strings that must be converted to lists, using <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow noreferrer"><code>ast.literal_eval</code></a></li> <li>In order to perform array subtracting, convert the values in <code>'Onsets'</code> an...
python|arrays|pandas|numpy|text
2
357,834
63,746,426
Tensorflow eigenvalue decomposition is extremely slow
<p>I am using eigendecomposition in Tensorflow and find that it is extremely slow. Here's the code to show Tensorflow's speed vs numpy and scipy:</p> <pre><code>import numpy as np import scipy as sp import tensorflow as tf from time import time A = np.random.randn(400, 400) A_tf = tf.constant(A) cur = time() d, v = s...
<p>Try wrapping <code>tf.linalg.eig</code> in a <code>@tf.function</code> and you can observe improvement in speed. This is because it converted to graph mode and there will be some optimizations can be done.</p> <p>Incase of eager mode these may not preformed and it is default behavior in TF 2.x.</p> <p>You can wrap y...
python|tensorflow|eigenvalue|eigenvector
0
357,835
63,775,235
str.contains search in a pandas column for multiple strings separated by a comma
<p>I have a dataframe that looks like the following:</p> <pre><code>Company keywords A SOFTWARE, IOT, PLATFORM, ENERGY, OPEN SOURCE B ENERGY, PUBLIC UTILITIES, HARDWARE, SOFTWARE C ENERGY, SOFTWARE, ELECTROMOBILITY, EMISSIONS D ...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np # Boolean indices of rows including word SOFTWARE ind_df_software=df[&quot;keywords&quot;].str.contains(&quot;SOFTWARE&quot;) # Boolean indices of rows including word HARDWARE ind_df_hardware=df[&quot;keywords&quot;].str.contains(&quot;HAR...
pandas|dataframe
1
357,836
63,760,836
pandas dataframe update based on date values in 2 dataframes
<p>I have two dataframes, a snippet looks like this:</p> <pre><code>year1 = {'DAY':['MON', 'MON', 'MON', 'TUE', 'TUE', 'TUE'], 'TEMP':[12, 13, 14, 15, 15, 18], 'DATE':['01/01/20', '02/01/20', '03/01/20', '06/01/20', '07/01/20', '08/01/20']} df1 = pd.DataFrame(year1) year2 = {'DAY':['MON', 'MON', 'MON', 'TUE', ...
<p>You can use <code>pd.merge</code> on the <code>DATE</code> and <code>DAY</code> columns since the same dates will have the same day. Take the average of the <code>TEMP_x</code> and <code>TEMP_y</code> columns created from the merge and call it <code>AVG_TEMP</code>, then drop the <code>TEMP_x</code> and <code>TEMP_y...
python|pandas|dataframe|merge
2
357,837
64,128,947
how to access tf.data.Dataset within a keras custom callback?
<p>I have written a custom keras callback to check the augmented data from a generator. (See <a href="https://stackoverflow.com/a/63910397/1295595">this answer</a> for the full code.) However, when I tried to use the same callback for a <code>tf.data.Dataset</code>, it gave me an error:</p> <pre><code> File &quot;/pat...
<p>What ended up working for me was the following, using <a href="https://www.tensorflow.org/datasets/api_docs/python/tfds" rel="nofollow noreferrer"><code>tfds</code></a>:</p> <p>the <code>__init__</code> function:</p> <pre><code>def __init__(self, logdir, train, validation=None): super(TensorBoardImage, self).__i...
python|tensorflow|keras|callback|tf.data.dataset
1
357,838
63,920,897
Conversion between "pandas.Series" to numpy array
<p>I have a <code>pandas.Series</code> that every element is a <code>numpy.array</code>, For example:</p> <pre class="lang-py prettyprint-override"><code>p = pandas.Series([numpy.array([1,2]), numpy.array([2,4])]) </code></pre> <p>I try to convert the whole <code>Series</code> into a multi-dimensional (2,2) <code>numpy...
<p>I would suggest following conversion:</p> <pre><code>import numpy as np import pandas as pd p = pd.Series([np.array([1,2]), np.array([2,4])]) np.array(p.values.tolist()).shape </code></pre>
python|pandas|numpy
0
357,839
64,031,601
Dataframe: adding a column with mean by other column group
<p>Say I have the following DataFrame:</p> <pre><code>data = pd.DataFrame({'id' : ['1','2','3','4','5'], 'group' : ['1','1','2','1','2'], 'state' : ['True','False','False','True','True'], 'value' : [11,12,5,8,3]}) </code></pre> <p>I would like to add to the previous dataframe, a new column with the average <code...
<p>IIUC change <code>state</code> column back to boolean so you can <code>sum</code>, then <code>groupby</code> and <code>transform</code>:</p> <pre><code>df[&quot;avg_state&quot;] = (df.assign(state=df[&quot;state&quot;].map({&quot;True&quot;:True, &quot;False&quot;:False})) .groupby(&quot;group&q...
python|pandas|dataframe|pandas-groupby|mean
2
357,840
63,863,773
Speeding Up DataFrame .mask() Iteration
<p>Is there a faster way to perform conditional calculations to certain DataFrame columns than using .mask()? My code shown below seems to work, but it can be slow when I use a large dataset.</p> <pre><code>def inversing(column): DF = pd.read_csv('DataFrame.csv') DF[column] = DF[column].mask(DF[column] !=0, 1/D...
<p>There are multiple ways to go about this, but a straight forward one would be using a lambda: <code>df[column].apply(lambda x: 1/x if x != 0 else x)</code></p> <p>Full code in jupyter notebook with timings:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(-50, 50, 100)) %tim...
python|pandas|iteration|conditional-statements
0
357,841
64,146,136
Differentiate between Circles and Radio buttons Opencv python
<p>I have a task to detect Circles and Radio buttons in an Image. For this I tried Hough circles by having different parameters.</p> <p><strong>Issues</strong>: If the circles in the Image are of same radius of Radio buttons both are detected, but in our case it should only detect only one.</p> <p>Is there a way to di...
<ol> <li>Find and draw all the contours in the answer-sheet.</li> </ol> <hr /> <ol start="2"> <li>Apply <code>HoughCircles</code></li> </ol> <hr /> <p><strong>Step #1:</strong> We could start with finding all contours in the given <a href="https://content.zipgrade.com/static/pdfs/ZipGrade20QuestionV2.pdf" rel="nofollow...
python|numpy|opencv
1
357,842
64,036,162
Store dataframe in variable python
<p>I'm still learning python and I have a simple problem and i made a reasearch already with no success.</p> <p>I have this simple code:</p> <pre><code>import pandas as pd def readDF(): df = **reads a df from excel** return df DF = readDF() </code></pre> <p>The problem is that everytime i try to access the DF v...
<p>You could load the data into a data-storage class which calls the function once, or doesn't use a function at all:</p> <pre><code>import pandas as pd # Option 1: call function class DataStorage: def __init__(self): self.df = self.readDF() def readDF(self): df = pd.read_excel('test.xls...
python|pandas
0
357,843
63,820,894
Calculate the average between the same month in a time series
<p>I have a dataset between 2002 - 2018 which contains 1 value per month, 198 rows in total.</p> <p>I want to know how I can average all the values from the same month (e.g. January/2003 + ... + January/2018)</p> <pre><code>dateparse = lambda dates: pd.datetime.strptime(dates, '%Y-%m-%d') df = pd.read_csv('turbidez.cs...
<p>Use <code>pandas.to_datetime</code> and <code>pandas.Series.dt.month</code>:</p> <pre><code># Sample data date x 0 2002-07-31 8.466111 1 2003-07-31 6.234259 2 2002-09-30 8.160763 3 2003-09-30 4.927685 4 2002-11-30 8.125012 df[&quot;date&quot;] = pd.to_datetime(df[&quot;date&quot;] ) new_df = df...
python|pandas
1
357,844
64,144,956
What is wrong with this Binomial Tree Backwards Induction European Call Option Pricing Function?
<p>The function below works perfectly and only needs one thing: Removal of the for loop that creates the 1000 element array arr.</p> <p>Can you help me get rid of that for loop? Code is below</p> <pre><code>#Test with european call import numpy as np T = 1 N = 1000 sigma = 0.5 r = 0.02 S = 1 K = 0.7 u = np.exp(sigma*np...
<p>I am note sure if you can omit that loop in an efficient way, but when we do not use <code>np.delete()</code> but just use the indices to shrink <code>payoff</code> in every iteration I already got a big speed increase on my machine:</p> <pre class="lang-py prettyprint-override"><code># ... arr = np.full(N+1, d/u) a...
python|numpy
0
357,845
63,910,662
Best way to save extracted features for future training deep learning
<p>I am using the VGG19 architecture to extract features from my images. Here is my code to do so:</p> <pre><code>model = VGG19(include_top=False) image_paths = glob.glob('train/*/*') def extract_features(model, path): img_path = path img = image.load_img(img_path, target_size=(224,224)) x = image.img_to_array(i...
<p>I have two suggestions:</p> <p>Save the features per file, e.g. for cat.png save it as cat.npy; and as you go over your list of files (cat.png, dog.png, snake.png), first check if the feature was already created and directly load the .npy file.</p> <p>The second approach is using a dictionary data structure, where y...
python|tensorflow|keras|deep-learning
0
357,846
64,051,278
pandas filter if string in row A contains row b element
<p>Let's say we have this df</p> <pre><code>d = pd.DataFrame({'year': [2010, 2020, 2010], 'colors': ['red', 'white', 'blue'], &quot;shirt&quot; : [&quot;red shirt&quot;, &quot;green and red shirt&quot;, &quot;yellow shirt&quot;] }) </code></pre> <p>like this:</p> <pre><code> year colors shirt 0 2010 red ...
<p>I believe you need <code>df.apply</code></p> <p><strong>Ex:</strong></p> <pre><code>df = pd.DataFrame({'year': [2010, 2020, 2010], 'colors': ['red', 'white', 'blue'], &quot;shirt&quot; : [&quot;red shirt&quot;, &quot;green and red shirt&quot;, &quot;yellow shirt&quot;] }) print(df[(df.year == 2010) &amp; df.apply(la...
python|python-3.x|pandas
2
357,847
64,122,927
Get unique values along axis in a Numpy 4d array
<p>Given an array (representing an image with 3 rows of 19 RGB pixels) like the following:</p> <pre><code>test_nested_array = np.array([[[ [ 6., 11., 14.], [ 6., 11., 14.], [ 6., 11., 14.], [ 6., 11., 14.], [ 7., 12., 15.], [ 7., 12., 15.], [ 7., 12.,...
<p>Even though the tip by @Divakar helpt me further, I ended up using <code>numpy_indexed</code> package to extract the unique entries like this:</p> <pre><code>import numpy_indexed as npi uniq = npi.unique(data) </code></pre> <p>This turned out much faster for my use-case.</p>
python|arrays|numpy|image-processing|multidimensional-array
0
357,848
63,998,611
Pandas: Updating a rolling average only every minute for one second data
<p>I have a dataframe where rows of data are in one second intervals, so 08:00:00, 08:00:01, etc. I want to take a rolling average over a period of 10 minutes, but I only want the rolling average to update on a minute by minute basis. So the rolling average values for 08:10:00 - 08:10:59 would all be the same value, an...
<p>I have another column for the seconds value called df['sec']. I got the indices of rows where seconds = 0 (the zeroth second of each minute) and replaced every other row with np.nan. Then I used fillna(method='ffill') to copy values downward.</p> <pre><code>df['counts-avg'] = df['counts'].rolling(window=600).mean() ...
python|pandas
0
357,849
63,819,258
StopIteration issue in pandas dataframe with dictionary python
<p>I have 3 column (DM1_ID, DM2_ID, pairs) pandas dataframe with 1 million records.Also, I have a dictionary containing key and multiple values. The function check the dictionary values and get the key and put that key in new_ID field. Function working fine for small part of pandas dataframe but when I applied it to ...
<p>From your data, essentially you just need to look up one column, say &quot;DM1_ID&quot;, as the corresponding &quot;DM2_ID&quot; should belong to the same key in jdic. In this case, it's quite easy to do. I would just reverse your dictionary.</p> <pre><code>jdic = {10045: [1, 6, 7,10045, 15, 45, 55, 80], 11945: [119...
python|pandas|dataframe|dictionary|stopiteration
1
357,850
63,923,352
Can you filter a pandas dataframe based on a sum or count or multiple variables?
<p>I'm trying to filter a Pandas dataframe based on a set of or conditions, but they're all very similar, and I'm wondering if there's a more efficient way to write this.</p> <p>Specifically, I want to include rows from the dataframe (df) where any of a set of variables is 1:</p> <pre><code>df.query(&quot;Q50r5==1 or Q...
<p>You can use <code>any</code> with <code>axis = 1</code> to check that at least one value is <code>True</code> in a row.</p> <p>For example, you can run</p> <pre><code>df[(df[[&quot;Q20r1&quot;, &quot;Q20r2&quot;, &quot;Q20r3&quot;]] == 1).any(axis = 1)] </code></pre>
python|pandas
1
357,851
63,953,309
Reduce image channels in python
<p>I have an image with dimension of (128, 19, 3), i want to convert it to (128, 19, 1). I used this code (in python) but it converts the image size to (128, 19) not (128, 19, 1) which i want. thanks if anyone can help</p> <pre><code>from PIL import Image import glob images = glob.glob('D:\\thesis\\Paper 3\\Feature Ex...
<p>simply add a dimension to the end of your array:</p> <pre><code>img = img[...,None] </code></pre>
python|image|numpy|rgb
0
357,852
63,870,418
Why numpy arrays are slower than lists with for loops?
<p>Aren't arrays supposed to be faster since they consume less memory and as I know with arrays python doesn't apply type method on the elements as it in the lists.</p> <pre><code>import numpy as np import time length = 150000000 my_list = range(length) list_start_time = time.time() for item in my_list: pass...
<p><code>my_list = range(length)</code> is a <code>range</code> object, more of a generator than a list</p> <p>In the loop:</p> <pre><code> for i in range(10): pass </code></pre> <p>there's no significant memory use. But even if we did iterate on a list, each <code>i</code> would just be a reference to an item i...
python|numpy
1
357,853
63,959,460
Extract variables from XML to Pandas
<p>I am working on parsing XML variables to pandas dataframe. The XML files looks like ( <strong>This XML file has been simplified for demo</strong>)</p> <pre><code>&lt;Instrm&gt; &lt;Rcrd&gt; &lt;FinPpt&gt; &lt;Id&gt;BT0007YSAWK&lt;/Id&gt; &lt;FullNm&gt;Turbo Car&lt;/FullNm&gt; ...
<p>Assuming a <code>&lt;root&gt;</code> node in posted XML without namespaces, consider building a dictionary via list/dict comprehension and combining sub dictionaries (<a href="https://stackoverflow.com/a/26853961/1422451">available in Python 3.5+</a>) that parse to needed nodes. Then call the <code>DataFrame()</code...
python|xml|pandas|parsing|xml-parsing
0
357,854
64,014,484
apply function not working as expected in groupby
<p>I have a dataframe that looks like:</p> <pre><code>ID | timestamp |Phase| current ======================================== 001 | 2020-09-20 07:00 | A | 1.4 001 | 2020-09-20 07:00 | B | 2.0 001 | 2020-09-20 07:00 | C | 1.6 002 | 2020-09-20 09:00 | A | 1.4 002 | 2020-09-20 09:00 | B | 1.2...
<p>IIUC you can find the desired rows with pandas functions</p> <pre><code>df['cng'] = (df.groupby('ID')['current'].pct_change() + 1).groupby(df.ID).cumprod()-1 df[df.groupby('ID')['cng'].transform(lambda x: x.fillna(x.max())) &gt; .30] </code></pre> <p>Output</p> <pre><code> ID timestamp Phase current ...
python|pandas|pandas-groupby|pandas-apply
0
357,855
46,902,567
Efficiently taking time slices of variable length in a dataframe
<p>I would like to efficiently slice a DataFrame with a DatetimeIndex (similar to a resample or groupby operation), but the desired time slices are different lengths.</p> <p>This is relatively easy to do by looping (see code below), but with large timeseries the multiple slices quickly becomes slow. Any suggestions on...
<p>You can do this as an apply, which will concat the results rather than iteratively update the DataFrame:</p> <pre><code>In [11]: slicer_df.apply((lambda row: \ df[(df.index &gt;= row.start_window) &amp; (df.index &lt;= row.end_window)].sum()), axis=1) Out[11]: 1 36.381155 2 111....
python|pandas
3
357,856
46,846,828
How to insert multiple IDs into a sql statement?
<p>New to python and pandas, Im facing the following issue:</p> <p>I would like to pass multiple string into a sql query and struggle to insert the delimiter ',' :</p> <pre><code>Example data import pandas as pd data = [['Alex',10],['Bob',12],['Clarke',13]] df = pd.DataFrame(data,columns=['Name','Age']) print (df) ...
<p>Demo:</p> <pre><code>sql_ = """ SELECT * FROM emptable WHERE empID IN ({}) """ sql = sql_.format(','.join([x for x in ['?'] * len(df)])) print(sql) new = pd.read_sql(query, conn, params=tuple(df['Name'])) </code></pre> <p>Output:</p> <pre><code>In [166]: print(sql) SELECT * FROM emptable WHERE empID IN (?,?,?)...
python|pandas
2
357,857
46,680,852
reshaping df into multindex and concatenating along keys
<p>I have a dataframe called "df1":</p> <pre><code> 0 1 2 2015-10-13 96 97.0 59.0 2008-03-18 90 91.0 92.0 </code></pre> <p>and would like to reshape it to :</p> <pre><code> 0 2015-10-13 96 97.0 59.0 2008-03-18 9...
<p>This should get you there, if you're OK with an extra level in the index:</p> <pre><code>import pandas data = {'0': {'2008-03-18': 90, '2015-10-13': 96}, '1': {'2008-03-18': 91.0, '2015-10-13': 97.0}, '2': {'2008-03-18': 92.0, '2015-10-13': 59.0}} df1 = pandas.DataFrame(data) df2 = df1 result = p...
python|pandas|dataframe
2
357,858
46,820,705
Rename specific columns with numbers with str+number
<p>I originally have r number of csv files.</p> <p>I created one dataframe with 9 columns and r of them have numbers as headers.</p> <p>I would like to target only them and change their name into ['Apple']+range(len(files)). </p> <p>Example: I have 3 csv files.</p> <p>The current 3 targeted columns in my dataframe ...
<p>IIUC, you can initialise a <code>itertools.count</code> object and reset the columns in a list comprehension.</p> <pre><code>from itertools import count cnt = count(1) df.columns = ['Apple{}'.format(next(cnt)) if str(x).isdigit() else x for x in df.columns] </code></pre> <p>This will also work very well i...
python|pandas
1
357,859
47,073,936
Matrix of pairwise row operations on pandas.DataFrame
<p>I want to create a matrix of the results of operations on all pairs of rows in a DataFrame.</p> <p>Here's an example of what I want:</p> <pre><code>df = pandas.DataFrame({'val': [ 2, 3, 5, 7 ], 'foo': ['f1', 'f2', 'f3', 'f4']}, index= ['n1', 'n2', 'n3', 'n...
<p>You can just use broadcasted numpy operations:</p> <pre><code>v = df.val.values[:, None] * df.val.values v array([[ 4, 6, 10, 14], [ 6, 9, 15, 21], [10, 15, 25, 35], [14, 21, 35, 49]]) x = df.foo.values[:, None] + df.foo.values x array([['f1f1', 'f1f2', 'f1f3', 'f1f4'], ['f2f1', 'f2...
python|pandas|numpy|dataframe|pairwise
1
357,860
47,050,161
Gini coefficient with keras in python
<p>I want to calculate simple NN model with gini coefficient as its optimizer function. Here is the my gini function:</p> <pre><code>def gini(actual, pred): nT = K.shape(actual)[-1] n = K.cast(nT, dtype='int32') inds = K.reverse(tf.nn.top_k(pred, n)[1], axes=[0]) a_s = K.gather(actual, inds) a_c = ...
<p>This error is typical for functions that are not differentiable. (It also happens when some var is <code>None</code> and shouldn't be. Sometimes it's the case that someone forgot to add the <code>return</code> statement to a custom function somewhere or something like that). </p> <p>In your case, it's not differe...
tensorflow|neural-network|keras|gini
0
357,861
46,723,478
Convert Pandas Column to dataframe
<p>I have a pandas dataframe column called 'Date' with entries of the format: '%Y%m%d%H%M%H%M' (first %H%M is local time &amp; the second %H%M is UTC). </p> <p>I want to convert that to the format: %Y-%m-%d_%H%M (keeping the UTC %H%M).</p> <pre><code>obs_df = pd.read_csv(obs, names= ['WBAN','Date','Extinc Coeff', 'D/...
<p>Use <code>format='%Y%m%d%H%M%S%f'</code></p> <pre><code>In [1454]: pd.to_datetime(df.Date, format='%Y%m%d%H%M%S%f') Out[1454]: 0 2014-10-01 08:48:13.480 1 2014-10-01 08:49:13.490 2 2014-10-01 08:50:13.500 3 2014-10-01 08:51:13.510 4 2014-10-01 08:52:13.520 Name: Date, dtype: datetime64[ns] </code></pre> ...
python|pandas|datetime|dataframe|python-datetime
1
357,862
46,736,803
How to optimize for loops for generating a new random Poisson array in python?
<p>I want to read an grayscale image, say something with (248, 480, 3) shape, then use each element of it as the lam value for making a Poisson random value and do this for each element and make a new data set with the same shape. I want to do this as much as <code>nscan</code>, then I want to add them all together and...
<p><a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.poisson.html#numpy-random-poisson" rel="nofollow noreferrer">numpy.random.poisson</a> can entirely replace your <code>genP()</code> function... This is basically guaranteed to be much faster.</p> <blockquote> <p>If size is None (def...
python|loops|numpy|random
1
357,863
46,676,419
Why can't I remove the default pandas plot logy yticklabels?
<p>Pandas creates default yticklabels for logy plots. I want to replace these labels with my own labels but for some reason I can't seem to remove the default labels.</p> <p>If I specify the yticks inside the <code>plot</code> method, it just writes over the existing default label:</p> <pre><code>x = [1, 1.5, 2, 2.5,...
<p>Matplotlib plots may have major and minor ticks and ticklabels. In cases where the logarithmic plot ranges over less than a decade, minor ticklabels are set on by default. You may set them to an empty list, via <code>ax.set_yticklabels([],minor=True)</code>, or you may turn them off completely via <code>ax.minortick...
pandas|matplotlib
3
357,864
47,024,082
What is a "grappler item" in tensorflow terminology?
<p>I am trying to understand the "grappler" module located at: <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/grappler" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/grappler</a></p> <p>Can somebody tell me what is meant by the "grappler i...
<p>Grappler is Tensorflow's optimization module. When a graph is run, it is optimized similar to how a compiler optimizes a program during compilation. According to <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/grappler/grappler_item.h" rel="nofollow noreferrer">the source</a>, <code>gra...
tensorflow
3
357,865
46,823,941
Groupby cumulative operations in successive rows pandas
<p>I want to find the rolling sum and rolling max for the column <code>B</code> for the same values in <code>A</code> in <code>df</code></p> <pre><code>df = pd.DataFrame({'A': ['a', 'a', 'a', 'b', 'b', 'b', 'b'], 'B': [5, 2, 4, 7, 1, 11, 3]}) df_result = pd.DataFrame({'A': ['a', 'a', 'a', 'b', 'b', 'b', 'b'], 'B': [5...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with aggregation by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>agg</c...
python|pandas|pandas-groupby
3
357,866
46,839,073
Tensorflow object detection API RCNN is slow on CPU: 1 frame per min
<p>I am using a locally trained model from tensorflow object detection API. I am using the <code>faster_rcnn_inception_resnet_v2_atrous_coco_11_06_2017</code> checkpoint. I retrained a 1 class model and exported it to SavedModel</p> <pre><code>python object_detection/export_inference_graph.py \ --input_type image_...
<p>Hopefully this will help other users choose models. Here is my reported average times for 3.1 Ghz CPU processor on OSX (more info above).</p> <p>faster_rcnn_inception_resnet_v2_atrous_coco: 45 sec/image</p> <p>faster_rcnn_resnet101_coco: 16 sec/image</p> <p>fcn_resnet101_coco: 7 sec/image</p> <p>ssd_inception_v2...
tensorflow|object-detection
10
357,867
46,672,168
How to use tensorflow to approximate hessian matrix's norm
<p>I wonder is there any method to recompute gradients with updated weights within a graph or if there is any better way to do this. For example, for estimating hessian norm, we need to compute</p> <pre><code>delta ~ N(0, I) hessian_norm = 1/M \sum_{1}^{M} gradient(f(x+delta))- gradient(f(x-delta))/(2*delta) </code></...
<p><code>b</code> is not a function of <code>a+delta</code>, so you get <code>None</code>s. You either need to create new value <code>b2</code> which depends on <code>a+delta</code>, or just move your <code>a</code> variable by <code>delta</code> and eval again to get second value.</p> <p>This is similar to how you do...
python|tensorflow
1
357,868
46,735,018
Is this function creating a new TensorFlow graph each time?
<p>I am following <a href="https://rdipietro.github.io/tensorflow-scan-examples/" rel="nofollow noreferrer">this tutorial</a> on how to use <code>tf.scan</code> and I wrote a minimal working example (see code below). But each time the function <code>Model._step()</code> is called, isn't it creating another copy of the ...
<p>The <code>Model._step()</code> method will only be called once per <code>Model</code> object constructed. The <a href="https://www.tensorflow.org/api_docs/python/tf/scan" rel="nofollow noreferrer"><code>tf.scan()</code></a> function, like the <a href="https://www.tensorflow.org/api_docs/python/tf/while_loop" rel="no...
python|tensorflow
1
357,869
47,013,530
Tensorflow: gradient_override_map cannot override op tf.stack 's backward gradient
<p>I was trying to edit <code>tf.stack</code> op's backward gradient calculation mechanism with <code>tf.RegisterGradient</code>and<code>tf.gradient_override_map</code>, here are my codes:</p> <pre><code>import tensorflow as tf class SynthGradBuilder(object): def __init__(self): self.num_calls = 0 de...
<p>Tl;dr: The correct code should be:</p> <pre><code>@tf.RegisterGradient(op_name) def _grad_synth(op, grad): x, y = tf.unstack(grad) return [x, tf.zeros_like(y)] g = tf.get_default_graph() with g.gradient_override_map({"Pack": op_name}): y = tf.stack([x, x]) </code></pre> <hr> <p>Because this is a quite comm...
python|tensorflow
4
357,870
46,922,610
Pandas Dataframe merge multi-key
<p>Everyone.</p> <p>I have a question relate in DataFrame Merge.</p> <p>I use DF1, DF2.</p> <p>DF1 have UserID, ContentID, Genre Column. DF2 have UserID, ContentID, Rating Column. </p> <p>I want use multi coloumn-key( UserID, ContentID ) then match rows Rating display, none match row is NAN</p> <p>Plz, check below...
<p>Simple <code>merge</code></p> <pre><code>df1.merge(df2,on=['UserID','ContentID'],how='left') Out[531]: UserID ContentID Genre Rating 0 U-1 C-1 G-1 3.0 1 U-1 C-2 G-2 3.0 2 U-1 C-3 G-3 NaN 3 U-2 C-1 G-1 NaN 4 U-2 C-2 G-2 3.0 5 U-2 ...
python|pandas|dataframe|multiple-columns
4
357,871
47,012,227
Python numpy-like interface for tree structures
<p>I find myself often in need of a flexible data structure which is something between a dict and an array. I hope the following example will illustrate:</p> <pre><code>a = ArrayStruct() a['a', 'aa1'] = 1 a['a', 'aa2'] = 2 a['b', 0, 'subfield1'] = 4 a['b', 0, 'subfield2'] = 5 a['b', 1, 'subfield1'] = 6 a['b', 1, 'su...
<p>I made it myself. It's called a Duck. It currently lives in master branch of <a href="https://github.com/QUVA-Lab/artemis" rel="nofollow noreferrer">Artemis</a>. Here's some code demonstrating its use:</p> <pre><code>from artemis.general.duck import Duck import numpy as np import pytest # Demo 1: Dynamic assignm...
python|arrays|database|numpy|dictionary
3
357,872
46,988,241
Accessing json's elements with Python
<p>I use this code to load my file:</p> <pre class="lang-python prettyprint-override"><code>with open('filepath') as myfile: data = [next(myfile) for x in xrange(100)] print data print json.dumps(data, indent=1, sort_keys=False) </code></pre> <p>In the first case the structure I get, looks like:</p> <pre><cod...
<p>This file is encoded twice in JSON. </p> <p>In case you're using <code>json.dumps()</code> on a JSON file or if you use <code>json.dumps()</code> twice, then this will happen. Can you show us more about it?</p> <p>Possible solution:</p> <pre><code>import json clear_json = json.loads(your_json) </code></pre>
python|json|pandas|jupyter
1
357,873
46,831,752
Function take values from a dataframe as parameter
<p>I have a function which calculates the Holidays for a given year like this:</p> <pre><code>holidays = bf.Holidays(year) </code></pre> <p>the problem is, there is no way to edit the Holidays function so i need another solutions.</p> <p>I have a datafame with some years, example:</p> <pre><code> year 0 2005 1 20...
<p>I think you can follow <a href="https://stackoverflow.com/questions/23586510/return-multiple-columns-from-apply-pandas">this example</a> and just write a little wrapper function to return the dates to their respective columns:</p> <pre><code>def holiday_mapper(row): holidays = bf.Holidays(row['year'],'HH').get_...
python|pandas|dataframe
0
357,874
47,074,894
how to calculate correlation between rows in python pandas data frame
<p>I have large data frame, and I need to calculate efficiently correlation between the data frame rows and given value list. for example:</p> <pre><code>dfa= DataFrame(np.zeros((1,4)) ,columns=['a','b','c','d']) dfa.ix[0] = [2,6,8,12] a b c d 2.0 6.0 8.0 12.0 dfb= DataFrame([[2,6,8,12],[1,3,4,6],[-1,-3,-4,-6]],...
<p><strong>First of all, note that the last 2 correlations are 1 and -1 and not 0.5 and -0.5 as you expected.</strong></p> <p><strong>Solution</strong></p> <pre><code>dfb.corrwith(dfa.iloc[0], axis=1) </code></pre> <p><strong>Results</strong></p> <pre><code>0 1.0 1 1.0 2 -1.0 dtype: float64 </code></pre>
python|performance|pandas|linear-regression|correlation
6
357,875
47,036,922
Handle surrogates with pandas
<p>When saving the data</p> <pre><code>data.to_csv(outp_file, encoding='utf-8') </code></pre> <p>I sometimes get errors like this</p> <blockquote> <p>UnicodeEncodeError: 'utf-8' codec can't encode characters in position 233-234: surrogates not allowed</p> </blockquote> <p>In python3 you can simply replace such ...
<pre><code>for col in train.columns: if train[col].dtype==object: train[col]=train[col].apply(lambda x: np.nan if x==np.nan else str(x).encode('utf-8', 'replace').decode('utf-8')) </code></pre> <p>Try this. It worked for me</p>
python-3.x|pandas
4
357,876
46,718,738
DataFrame with 3 columns to dictionary of dictionaries
<p>I have following <code>DataFrame</code> with 3 columns </p> <pre><code>my_label product count 175 '409' 41 175 '407' 8 175 '0.5L' 4 175 '1.5L' 4 177 ...
<p>The straightforward way is to groupby <code>my_label</code> then iterate over the resulting rows, grabbing the values you need:</p> <pre><code>In [7]: df Out[7]: my_label product count 0 175 '409' 41 1 175 '407' 8 2 175 '0.5L' 4 3 175 '1.5L' ...
python|pandas|dataframe
3
357,877
46,676,738
Using Tensorflow on smartphones
<p>I've been learning a lot about the uses of Machine Learning and Google's Tensorflow. Mostly, developers use Python when developing with Tensorflow. I do realize that other languages can be used with Tensorflow as well, i.e. Java and C++. I see that Google s about to launch Tensorflow Lite that is supposed to be a ga...
<p>In short, yes. It would be safe to learn implementing TensorFlow using python and still comfortably develop machine learning enabled mobile apps.</p> <p>Let me elaborate. Even with TensorFlow Lite, training the data can only happen on the server side; only the prediction, or the inference happens on the mobile devi...
java|android|python|mobile|tensorflow
0
357,878
46,760,037
How to calculate the mean index in array with NumPy
<p>How can I calculate the mean index T for an array nums that minimize the value of </p> <pre><code>abs(sum(nums[:T])-sum(nums[T:])) </code></pre>
<p>The specific problem you're trying to solve has a well known solution called Otsu's method. The code below is from <a href="https://learnopencv.com/otsu-thresholding-with-opencv/" rel="nofollow noreferrer">https://learnopencv.com/otsu-thresholding-with-opencv/</a>:</p> <pre><code># Set total number of bins in the h...
python|numpy|average
0
357,879
47,008,199
How to traverse the result of tf.unqiue?
<p>After invoking <code>tf.unqiue</code>, the shape of tensor will be unknown, but I want to traverse the result of <code>tf.unqiue</code></p> <p>Suppose <code>tensor = tf.unqiue(...)</code></p> <p>I have tried:</p> <ul> <li>for i in tf.range(tf.shape(tensor)[0])</li> <li>tf.unstack(tensor, num=tf.shape(tensor)[0])<...
<p>I just tried this:</p> <pre><code>import tensorflow as tf import numpy as np a = tf.constant(np.random.randn(200), dtype='float32') b = tf.unique(a) print b[0] #Tensor("Unique:0", shape=(?,), dtype=float32) c = tf.map_fn(lambda x: x*x, b[0]) init = tf.global_variables_initializer() sess = tf.Session() sess.run...
tensorflow
0
357,880
46,869,884
How to replace values inside a list inside a pandas row
<p>I have a pandas dataframe that looks like this </p> <pre><code>2 zero zero zero zero zero zero zero 2 zero zero ... 6 6 zero [2, 4] zero 2 zero zero zero zero 3 1 zero 6 1 zero zero zero zero zero zero ... zero zero zero zero...
<p><code>df.replace</code> will look for cells that contain that value, and replace it with the target.</p> <p>In your case, you're dealing with a column of lists, so something a little more aggressive is needed. Let's try <code>astype(str)</code> + <code>str.replace</code> + <code>ast.literal_eval</code>.</p> <pre><...
python|pandas|numpy|dataframe
2
357,881
32,664,374
How can I plot the number of rows that occurred per hour over a long period of time?
<p>I have a large CSV file that looks like this:</p> <pre><code>ID,Time,Disposition,eventsID,Class,teamID 1,"2011-03-02 22:18:37",1,107,2,2 2,"2011-03-02 22:19:05",1,115,1,2 3,"2011-03-02 22:19:10",1,103,4,2 4,"2011-03-02 22:19:41",1,104,1,3 5,"2011-03-03 01:24:31",1,117,4,3 </code></pre> <p>This data spans many mont...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="nofollow noreferrer"><code>DataFrame.plot()</code></a> to plot the graph. Example -</p> <pre><code>count_per_day.plot() </code></pre> <p>Demo with the example data you added -</p> <p><a href="https://i.stac...
python|pandas
1
357,882
33,030,336
Converting a column value when filtering in pandas
<p>In a csv file which I read using pandas, there's a column of type bool but in the string format which is 'F' or 'T'. How can I convert it to the real Bool when filtering? No need to change in the source file, only when filtering:</p> <pre><code># how it is now if something: df1 = df1[df1['str_bool_column'] == 'F'...
<p>You can convert that column to a column of <code>True/False</code> values after reading it from the csv. One method to do that would be to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>Series.map</code></a> , to map <code>'F'</code> to <code>False</co...
python|pandas
0
357,883
32,968,167
In pandas when querying, how to skip filters that are None?
<p>How can I skip (don't apply) the filters that are None?</p> <pre><code>res = df[ (df['Column1'] &gt;= column1_min) &amp; (df_item['Column1'] &lt;= column1_max) &amp; (df['Column2'].isin(column2) ) &amp; (df['Column3'] == column3) &amp; #..... </code></pre> <p>that is, if <code>column1_min</code> or <code>c...
<p>If I understood well, you can try this:</p> <pre><code>res = df[( (df['Column1'] &gt;= column1_min) if column1_min != None else True) &amp; ( (df['Column1'] &lt;= column1_max) if column1_max != None else True) &amp; ( (df['Column2'].isin(column2) ) if column2 != None else True ) &amp; ( (...
python|pandas
1
357,884
33,003,752
pandas DataFrame has only one row
<p>I have problem listing DataFrame rows. The below function returns only one row (if indented returns first row, if not indented returns the last one). Does anyone knows where's the problem?</p> <pre><code>def ols_regression(formula, framedict): for yp in framedict.keys(): ols_model = ols(formula, framedi...
<p>I solve the problem with appending the dictionary to array.</p> <pre><code>def ols_regression(formula, framedict): arr = [] for yp in framedict.keys(): ols_model = ols(formula, framedict[str(yp)]).fit() year = int(yp[:-5]) params = ols_model.params arr.append(dict(yp =...
python|pandas|dataframe
1
357,885
33,059,857
Add time entries to Pandas data series based on interpolation of existing values
<p>I have an annual pandas data series that looks like:</p> <pre><code>Year Price 1940-12-31 33.85 1941-12-31 33.85 1942-12-31 33.85 1943-12-31 33.85 1944-12-31 33.85 1945-12-31 34.71 1946-12-31 34.71 1947-12-31 34.71 1948-12-31 34.71 1949-12-31 31.69 1950-12-31 34.72 </code><...
<p>The following code will do the job:</p> <pre><code>df['Price'].resample('M').interpolate() </code></pre> <p>replace df with the name of your DataFrame. resample('M') change the frequency of the series to monthly. (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="n...
python|pandas|time|interpolation|series
2
357,886
32,633,265
return a list from class object
<p>I am using multiprocessing module to generate 35 dataframes. I guess this will save my time. But the problem is that the class does not return anything. I expect the list of dataframes to be returned from self.dflist</p> <p>Here is how to create dfnames list.</p> <pre><code>urls=[] fnames=[] dfnames=[] for x in xr...
<p>In your case I prefer to write as less code as possible and use <code>Pool</code>:</p> <pre><code>import pandas as pd import logging import multiprocessing def dframe_create(filename): try: return pd.read_excel(filename) except Exception as e: logging.error("Something went wrong: %s", e, ...
pandas|python-multiprocessing
3
357,887
32,638,519
Query same time value every day in Pandas timeseries
<p>I would like to get the 07h00 value every day, from a multiday DataFrame that has 24 hours of minute data in it each day. </p> <pre><code>import numpy as np import pandas as pd aframe = pd.DataFrame([np.arange(10000), np.arange(10000) * 2]).T aframe.index = pd.date_range("2015-09-01", periods = 10000, freq = "1min...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.indexer_at_time.html" rel="noreferrer"><code>indexer_at_time</code></a>:</p> <pre><code>&gt;&gt;&gt; locs = aframe.index.indexer_at_time('7:00:00') &gt;&gt;&gt; aframe.iloc[locs] 0 1 2015-09-...
python|pandas|datetime|dataframe
8
357,888
32,853,124
Why do these two arrays have the same shape?
<p>So I am trying to create an array and then access the columns by name. So I came up with something like this:</p> <pre><code>import numpy as np data = np.ndarray(shape=(3,1000), dtype=[('x',np.float64), ('y',np.float64), ('z',np.float64)]) </code></pre> <p>I am...
<p>The reason why it comes out the same is because 'data' has a bit more structure than the one revealed by shape.</p> <p>Example:</p> <p><code>data[0][0] returns</code>: (6.9182540632428e-310, 6.9182540633353e-310, 6.9182540633851e-310)</p> <p>while <code>data['x'][0][0]:</code> returns 6.9182540632427993e-310</p>...
python|numpy|scipy
1
357,889
32,733,203
"Unsparsing" numpy Arrays with Given Masks
<p>Suppose there are two arrays, <code>vals</code> contains values, and <code>masks</code> contains booleans indicating whether to use the values in <code>vals</code>, or <code>nan</code>s. The goal is to build an array <code>ret</code> of the same length as <code>masks</code>, containing the values from <code>vals</co...
<p>You could do something like this -</p> <pre><code>out = np.empty(masks.shape,dtype=object) out[masks] = vals[:masks.sum()] </code></pre> <p>Please note that <code>:masks.sum()</code> selects first <code>N</code> elements from <code>vals</code>, where <code>N</code> is the number of <code>TRUE</code> elements in m...
python|numpy|vectorization|sparse-matrix
2
357,890
32,996,894
How to get the all the columns which the datatype is not int or float with python pandas?
<p>I want to change the dataframe to numpy.ndarray with datatype float32, so I want to drop those column which dtype is object or other type which is not number. </p>
<pre><code>df.select_dtypes(include=['int', 'float']) </code></pre> <p>will do it for you. There's also an <code>exclude</code> option.</p>
pandas
1
357,891
33,003,547
How to filter through pandas pivot table
<p>I have a pivot table created from pandas (DataFrame object). </p> <p>Currently, I have multiple indexes and I want to be able to filter through some of them. To clarify this is how the pivot tables looks like.</p> <p><img src="https://i.stack.imgur.com/8nADP.png" alt="enter image description here"></p> <p>There a...
<p>First, create a multi-indexed dataframe:</p> <pre><code>df = pd.DataFrame({'i1': [1, 1, 1, 1], 'i2': [2, 2, 3, 3], 'i3': [4, 5, 4, 5], 'v1': [10] * 4, 'v2': [20] * 4}).set_index(['i1', 'i2', 'i3']) &gt;&gt;&gt; df v1 v2 i1 i2 i3 1 2 4 10 20 5 10 20 3 4 10 20 5 10 20 ...
python|pandas
1
357,892
32,853,043
pandas filtering consecutive rows
<p>I got a Dataframe with a Matrix colum like this</p> <pre><code>11034-A 11034-B 1120-A 1121-A 112570-A 113-A 113.558 113.787-A 113.787-B 114-A 11691-A 11691-B 117-A RRS 12 X R 12-476-AT-A 12-476-AT-B </code></pre> <p>I'd like to filter only matrix that ends with A or B only when they are consecutive, so in the exam...
<p>Here is how I would do it.</p> <pre><code>df['ShiftUp'] = df['matrix'].shift(-1) df['ShiftDown'] = df['matrix'].shift() def check_matrix(x): if pd.isnull(x.ShiftUp) == False and x.matrix[:-1] == x.ShiftUp[:-1]: return True elif pd.isnull(x.ShiftDown) == False and x.matrix[:-1] == x.ShiftDown[:-1]: ...
python|pandas
2
357,893
32,805,916
Compute Jaccard distances on sparse matrix
<p>I have a large sparse matrix - using sparse.csr_matrix from scipy. The values are binary. For each row, I need to compute the Jaccard distance to every row in the same matrix. What's the most efficient way to do this? Even for a 10.000 x 10.000 matrix, my runtime takes minutes to finish. </p> <p>Current solution:</...
<p>Vectorization is relatively easy if you use matrix multiplication to calculate the set intersections and then the rule <code>|union(a, b)| == |a| + |b| - |intersection(a, b)|</code> to determine the unions:</p> <pre><code># Not actually necessary for sparse matrices, but it is for # dense matrices and ndarrays, if...
python|numpy|scipy|sparse-matrix
17
357,894
38,577,444
How does one keep track of the training error of a Neural Network when using Batch Normalization in TensorFlow?
<p>I wanted to keep track of my training error as the Neural Network is trained. During testing, it is customary to remove the batch normalization layer. For example:</p> <pre><code># when test # is_training determines if Batch-norm is off or on error = sess.run([opt, loss], feed_dict={x: bx, y: by, is_training=False}...
<p>For reporting you would use the same metric on both your training and test set.</p> <p>For example, while training you might use <a href="https://en.wikipedia.org/wiki/Dropout_(neural_networks)" rel="nofollow">dropout</a> to increase the robustness of the net. To figure out how well your net performs out-of-sample,...
machine-learning|neural-network|tensorflow|conv-neural-network
0
357,895
38,700,694
Pandas: Set multiple MultiColumns as MultiIndex
<p>I generate an empty data frame as follows:</p> <pre><code>topFields = ['desc', 'desc', 'price', 'price', 'units', 'units'] bottomFields = ['foo', 'bar', 'mean', 'mom_2', 'mean', 'mom_2'] resultsDf = pd.DataFrame(columns=pd.MultiIndex.from_arrays([topFields, bottomFields])) </code></pre> <p>Now I would like to set ...
<p>It looks like need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> by tuple:</p> <pre><code>test = resultsDf.set_index(('desc', 'foo')) print (test) Empty DataFrame Columns: [(desc, bar), (price, mean), (price, mom_2), (units,...
python|pandas
1
357,896
38,575,672
pandas: create pivot table by two different dimensions?
<p>I am a pandas newbie. I have a dataframe of examinations taken by sponsor and company:</p> <pre><code>import pandas pd df = pd.DataFrame({ 'sponsor': ['A71991', 'A71991', 'A71991', 'A81001', 'A81001'], 'sponsor_class': ['Industry', 'Industry', 'Industry', 'NIH', 'NIH'], 'year': [2012, 2013, 2013, 2012, 2013]...
<p>I can see how to do it in quite a few steps:</p> <pre><code>import numpy as np, pandas as pd df['total'] = df['passed'].astype(int) ldf = pd.pivot_table(df,index=['sponsor','sponsor_class'],columns='year', values=['total'],aggfunc=len) # total counts rdf = pd.pivot_table(df,index=['sponsor','sp...
python|pandas
2
357,897
38,613,514
Prepare Data Frames to be compared. Index manipulation, datetime and beyond
<p>Ok, this is a question in two steps. </p> <p><strong>Step one:</strong> I have a pandas DataFrame like this:</p> <pre><code> date time value 0 20100201 0 12 1 20100201 6 22 2 20100201 12 45 3 20100201 18 13 4 20100202 0 54...
<p><strong>Step 1 Answer</strong></p> <pre><code>df['DateTime'] = (df['date'].astype(str) + ' ' + df['time'].astype(str) +':'+'00'+':'+'00').apply(lambda x: pd.to_datetime(str(x))) df.set_index('DateTime', drop=True, append=False, inplace=True, verify_integrity=False) df.drop(['date', 'time'], axis=1, level=None, in...
python|datetime|pandas
1
357,898
38,548,871
Tensorflow: How to Propagate Gradient Through tf.gather?
<p>I'm having some issues trying to propagate the gradient of my loss function with respect to a variable that represents the gather index, similar to what is done in spatial transformer networks (<a href="https://github.com/tensorflow/models/blob/master/transformer/spatial_transformer.py" rel="noreferrer">https://gith...
<p>The problem is that you can't differentiate since pt is an integer. It is selecting one index in the x placeholder so it does not have a derivative. Normally when you do this you would input an integer and use this to select a floating point value. You are doing it the other way around.</p>
tensorflow
0
357,899
38,709,570
Divide numpy matrix elements in 2-D matrix by sum of all elements in that position of 1-D
<p>If we have a matrix such as:</p> <p>[ [ 2, 3 ] , [ 4, 9 ], [ 3, 1 ] ]</p> <p>I want to know how to be able to divide matrix elements as follows:</p> <p>Sum the elements in the same position of their respective 1-D vectors</p> <p>2 + 4 + 3 = 9</p> <p>3 + 9 + 1 = 13</p> <p>Then divide each of the elements by the...
<h3>One solution:</h3> <pre><code>import numpy as np data = [[2, 3] , [4, 9], [3, 1]] result = data / np.sum(data, axis=0) print(result) </code></pre> <h3>Output:</h3> <blockquote> <p>[[ 0.22222222 0.23076923] <br> [ 0.44444444 0.69230769] <br> [ 0.33333333 0.07692308]]</p> </blockquote>
python|numpy|matrix
2