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
370,600
48,227,037
Error on weighted histogram in python
<p>I want to calculate the error on a bin height by taking the square root of the sum of the weights squared (sumw2) in that bin (poission error). Is there any way to get the sum of weights (sumw) and/or sumw2 when histogramming data with either matplotlib or numpy (or any other library for that matter)?</p> <p>Let's ...
<p>Consider an array <code>x</code> with weights <code>w</code>. The histogram of the data in <code>x</code> weighted by <code>w</code> with <code>bins</code> is given by:</p> <pre><code>n, bins = np.histogram(x, bins=bins, weights=w) </code></pre> <p>And the associated errors to n can be computed as:</p> <pre><code>n_...
python|numpy|matplotlib|histogram|weighted
2
370,601
48,394,043
Does "from __future__ import..." have any effect in up-to-date versions of Python?
<p>I have the latest version of Python installed. Will <code>from __future__ import...</code> statements have any effect at all? Is there any "future" beyond the most up-to-date version that I should know about - a "pre-release" or beta version not obvious to newcomers perhaps?</p> <p>I ask because I'm working through...
<p>Python 3 already has the <code>print</code> function, so the <code>from __future__ import print_function</code> will have no effect when you are already on Python 3. As <a href="https://www.python.org/dev/peps/pep-0236/" rel="nofollow noreferrer">PEP 236</a> describes, future statements are handled at compile time ...
python|tensorflow
2
370,602
48,343,900
How do I write an encoded jpeg as bytes to Tensorflow tfrecord and then read it?
<p>I am trying to use tensorflows tfrecords format to store my datasets. </p> <p>I managed to read in jpeg images and decode them to raw format and write them to a tfrecord file. I can then later read them using tf.decode_raw.</p> <p>The problem is that this leads to huge file sizes because I am storing the images as...
<p>For writing, just open the file as a binary file (<code>fp = open('something.jpg', 'rb')</code>) and <code>.read()</code> its content. Store that content in the tfrecord <code>Example</code> as you store the image now (i.e., as a bytes feature).</p> <p>For reading, instead of doing <code>decode_raw</code>, use <cod...
tensorflow|jpeg|encode|tfrecord
4
370,603
48,192,152
python Converting and solving of stiff ODE system
<p>I have stiff system of differential equations given to the first-order ODE. This system is written in Maple. The default method used by Maple is the Rosenbrock method. Now my task is to solve these equations with python tools.</p> <p>1) I do not know how to write the equations in the python code.</p> <p>2) I do no...
<p>After drifting on the Internet, I found something in principle:</p> <pre><code>import math import matplotlib.pyplot as plt import numpy as np from scipy import integrate from scipy.signal import argrelextrema from mpmath import mp, mpf mp.dps = 50 varepsilon = pow(10, -2); j = 2.5*pow(10, -4); e = 3.0; tau = 0...
python|numpy|scipy
0
370,604
48,012,349
dataframe to np.array - IndexError: tuple index out of range
<p>i am trying to convert the below pandas dataframe,</p> <pre><code>pd.DataFrame({'PE': [115.45, 8], 'PE FY1': [11, 12], 'EV/Sales':[0.4, 1.9], 'EV/EBIT':[16, 9.8], 'EV/EBITDA': [10.8, 7.5]}) </code></pre> <p>to an np.array but within multiple square brackets - as below - but have so far been unsucce...
<pre><code>v = df.values v array([[ 115.45, 11. , 0.4 , 16. , 10.8 ], [ 8. , 12. , 1.9 , 9.8 , 7.5 ]]) </code></pre> <p>If by multiple brackets, you mean that you want to expand the dimensions by 1 (so as to get an output of shape <code>(2, 1, 5)</code>), you have a few options - <...
python|pandas|numpy
2
370,605
48,427,365
numpy arange with specific gaps
<p>Is there a cleaner and nicer way in python3.x to do</p> <pre><code>a = np.arange(1,4) b = np.arange(5,10) c = np.concatenate((a,b)) </code></pre> <p>? So the result is <code>c = [1,2,3,5,6,7,8,9,10]</code> Please note, that the chosen numbers in this example are arbitrary!</p>
<p>Use the <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.r_.html" rel="nofollow noreferrer"><code>numpy.r_</code></a> object.</p> <pre><code>c = np.r_[1:4, 5:10] </code></pre> <p>I feel like this might have been asked before</p>
python|arrays|python-3.x|numpy
4
370,606
48,251,562
How can I get mode(s) of pandas dataframe object values?
<p>I have a <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="noreferrer"><code>pandas.DataFrame</code></a> containing numerous columns. I am interested in just one of those columns ('names') whose type = 'object'. I want to answer three questions about this column:</p> <ol> <...
<p>You can get that information directly from the <code>Counter</code> like:</p> <h3>Code:</h3> <pre><code>from collections import Counter data = Counter({'Erk': 118, 'James': 120, 'John': 126, 'Michael': 122, 'Phil': 117, 'Ryan': 126}) by_count = {} for k, v in data.items(): by_count.setdefaul...
python|python-3.x|pandas|dataframe|counter
4
370,607
48,341,009
Groupby every 2 hours data of a dataframe
<p>I have a dataframe:</p> <pre><code> Time T201FN1ST2010 T201FN1VT2010 1791 2017-12-26 00:00:00 854.69 0.87 1792 2017-12-26 00:20:00 855.76 0.87 1793 2017-12-26 00:40:00 854.87 0.87 1794 2017-12-26 01:00:00 855.51 0.87 1795 2...
<p>I think you need <code>groupby</code> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Grouper.html" rel="noreferrer"><code>Grouper</code></a> + some aggregate function:</p> <pre><code>df = last8.groupby(pd.Grouper(freq='2H', key='Time')).mean() </code></pre> <p>Or <a href="http://pandas.pyd...
python|pandas|dataframe|pandas-groupby
7
370,608
48,068,938
set new index for pandas DataFrame (interpolating?)
<p>I have a DataFrame where the index is NOT time. I need to re-scale all of the values from an old index which is not equi-spaced, to a new index which has different limits and is equi-spaced.</p> <p>The first and last values in the columns should stay as they are (although they will have the new, stretched index val...
<p>This is works well:</p> <pre><code>import numpy as np import pandas as pd def interp(df, new_index): """Return a new DataFrame with all columns values interpolated to the new_index values.""" df_out = pd.DataFrame(index=new_index) df_out.index.name = df.index.name for colname, col in df.iterit...
pandas|numpy|interpolation
7
370,609
48,070,944
deleting specific strings python
<p>I have the following in a python 3 numpy.ndarray:</p> <pre><code>{"_id" : "123", "text" : "some writing"} {"_id" : "456", "text" : "some more writing"} {"_id" : "789", "text" : "some more more writing"} </code></pre> <p>Question: How do I delete <code>{"_id" :</code> and <code>"text" :</code> to get the following:...
<p>the following was:</p> <pre><code>arr = [{"_id" : "123", "text" : "some writing"}, {"_id" : "456", "text" : "some more writing"}, {"_id" : "789", "text" : "some more more writing"}] ans = [{i['_id']: i['text']}for i in arr] </code></pre>
python|numpy
2
370,610
48,211,358
Python: Store multiple dataframe in list
<p>I have a loop that read Excel sheets in a document. I want to store them all in a list:</p> <pre><code> DF_list= list() for sheet in sheets: df= pd.read_excel(...) DF_list = DF_list.append(df) </code></pre> <p>If I type: </p> <pre><code>[df df df df] </code></pre> <p>it works.</p> <p>Sorry I have ...
<p><code>.append()</code> modifies a list and returns <code>None</code>. You override <code>DF_list</code> with <code>None</code> in your first loop and the append will fail in the second loop.</p> <p>Therefore:</p> <pre><code>DF_list = list() for sheet in sheets: DF_list.append(pd.read_excel(...)) </code></pre>...
python|list|pandas|dataframe|store
20
370,611
48,060,962
How to keep DataFrame / column and index names after calculation with np.where?
<p>I have 2 different <code>pd.DataFrames</code>:</p> <p><code>dailyRtn</code></p> <pre><code>date A B C 2017-12-25 0.069392 0.124916 0.119108 2017-12-26 0.020000 0.100000 0.080000 2017-12-27 1.000000 1.200000 1.500000 </code></pre...
<p>IIUC, you can use <code>set_index</code> and then include <code>index</code> and <code>columns</code> in your dataframe constructor.</p> <pre><code>dailyRtn = dailyRtn.set_index('date') averageofP = averageofP.set_index('date') downsideDev = np.where(dailyRtn &lt; averageofP, dailyRtn, "") downsideDev_df = (pd.Dat...
python|pandas|numpy
2
370,612
48,014,009
How do I solve expressions in python such as f1(x) = f2(x)?
<pre><code>import math import pylab import sympy def f1(x): """function representing a cosine variant function and returned""" return math.cos(2 * math.pi * x) * math.exp(-x ** 2) def f2(x): """function representing a log variant function and returned""" return math.log(x + 2.2) def positive_places(...
<p>When using SymPy you can take advantage of <a href="http://docs.sympy.org/0.6.7/modules/mpmath/calculus/optimization.html" rel="nofollow noreferrer">mpmath's root finder</a> ability to work with arbitrary many digits:</p> <pre><code>import mpmath import sympy as sy sy.init_printing() mpmath.mp.dps = 30 # accuracy...
python|python-3.x|numpy|scipy
0
370,613
48,311,472
Does the tf.data.Dataset support to generate dictionary structure?
<p>The following is a piece of code from [<a href="https://www.tensorflow.org/programmers_guide/datasets]" rel="nofollow noreferrer">https://www.tensorflow.org/programmers_guide/datasets]</a>. In this example, the <code>map</code> function is a user-defined function to read the data. And in the <code>map</code> functio...
<p>Returning dicts inside the function called by <code>tf.data.Dataset.map</code> should work as expected.</p> <p>Here is an example:</p> <pre class="lang-py prettyprint-override"><code>dataset = tf.data.Dataset.range(10) dataset = dataset.map(lambda x: {'a': x, 'b': 2 * x}) dataset = dataset.map(lambda y: y['a'] + y...
tensorflow|tensorflow-datasets|tensorflow-estimator
8
370,614
48,372,989
Tensorflow transpose of randomly generated tensor
<p>I'm practicing with TensorFlow basic commands and I started to use the tf.transpose function. I'm encountering a weird behaviour which I'm not able to explain. If I run this snippet:</p> <pre><code>with tf.Session() as test: ...: tf.set_random_seed(1) ...: A = tf.random_normal([2,3],mean=1,stddev=4) ...: ...
<p><code>tensorflow</code> groups functions and whenever a run is requested, it runs all the operations required for that run.</p> <p>Now, when the first time you do <code>A.eval()</code>, tensorflow sees that it need to initialize it with random numbers for it to output the answer and it does that. Now, when it sees ...
python|tensorflow
3
370,615
48,435,538
Create a scatter chart by matplotlib with mysql database
<p>I want to create a simple chart with these library written below. Here is how I did:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import pandas as pd import MySQLdb def mysql_select_all(): conn = MySQLdb.connect(host='localhost', user='root', ...
<p>By:</p> <pre><code>df = pd.DataFrame(list(sql),columns=["price","size1"]) </code></pre> <p>did you mean to type:</p> <pre><code>df = pd.DataFrame(list(result),columns=["price","size1"]) </code></pre> <p>?</p>
python|mysql|pandas|numpy|matplotlib
2
370,616
48,428,415
ImportError: libcublas.so.9.0: cannot open shared object file
<p>currently I have cuda 8.0 and cuda 9.0 installed in Gpu support system. I ran into this error while importing from keras module. It says like failed to load native tensorflow runtime. The error log which i received was:</p> <pre><code>Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/t...
<p>You will need to update your <code>LD_LIBRARY_PATH</code>, so that it points to the <code>/usr/local/cuda-9.0/lib64</code>. Add the following line to your <code>.bashrc</code> file (or any other terminal you use)</p> <pre><code>export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-9.0/lib64/ </code></pre>
python-3.x|tensorflow|cuda|keras
45
370,617
48,061,508
NumPy slicing: All except one array entry
<p>What is the best way to exclude exact one NumPy array entry from an operation? I have an array <code>x</code> containing <code>n</code> values and want to exclude the <code>i</code>-th entry when I call <code>numpy.prod(x)</code>. I know about <code>MaskedArray</code>, but is there another/better way?</p>
<p>I think the simplest would be</p> <pre><code>np.prod(x[:i]) * np.prod(x[i+1:]) </code></pre> <p>This should be fast and also works when you don't want to or can't modify x.</p> <p>And in case x is multidimensional and i is a tuple:</p> <pre><code>x_f = x.ravel() i_f = np.ravel_multi_index(i, x.shape) np.prod(x_f...
python|python-3.x|numpy
8
370,618
48,270,953
pandas corr and corrwith very slow
<p>I have a pandas dataframe with &lt;30K rows, and 7 columns and I'm trying to get the correlation of 4 of the columns to the fifth one. The problem is, I'd like to do this with massive datasets but this takes ~40s to run. Here is my code:</p> <pre><code>df_a = dfr[['id', 'state', 'perform', 'A']].groupby(['id', 'sta...
<p>The reason pandas corr is <strong>very slow</strong> is that it considers NANs: it is basically a cython for-loop.</p> <p>If your data doesn't have NANs, numpy.corrcoef is <em>much faster</em>.</p>
python|pandas|dataframe
8
370,619
48,789,190
How to assign minimum value based on lookup values in two other columns in pandas?
<p><strong><em>Objective:</strong> Looking to programmatically match combinations in two columns to find the lowest value of another column</em></p> <p>Let's say I have this: </p> <pre><code>import pandas as pd d = {'Part_1': [91, 201, 201], 'Part_2': [201,111,91], 'Result': [3,3, 3], 'Sub-Score': [...
<p>Sort the values, then groupby based on the ngroup and transform min i.e </p> <pre><code>temp = pd.DataFrame(pd.np.sort(df[['Part_1','Part_2']])) grps = temp.groupby(temp.columns.tolist()).ngroup() df['new']=df.groupby(grps)['Sub-Score'].transform('min') Final-Score Part_1 Part_2 Result Sub-Score new 0 ...
python|python-3.x|pandas|dataframe
2
370,620
48,571,138
How to merge columns based on its values - pandas?
<p>I've a table like this:</p> <pre><code> c0 | c1 | c2 | c3 ________________________ 1 | 2 |NaN | NaN 3 | 4 |NaN | NaN NaN |NaN |5 | 6 NaN |NaN |28 | 3 </code></pre> <p>And now I want to merge them, to get only to columns with the non NaN values as:</p> <pre><code> c0 | c1 | _____________...
<p>By using <code>apply</code></p> <pre><code>df.apply(lambda x : sorted(x,key=pd.isnull),1).dropna(1) Out[458]: c0 c1 0 1.0 2.0 1 3.0 4.0 2 5.0 6.0 3 28.0 3.0 </code></pre>
python|pandas
1
370,621
48,571,652
Python: pandas dataframe comparison of rows with the same value in one column
<p>I have a dataframe which looks like:</p> <pre><code>id name num_1 num_2 1 A 12 14 1 A 15 2 B 10 9 3 C 19 18 3 C 16 </code></pre> <p>My desired output would be:</p> <pre><code>id name num_1 num_2 1 A 12 14 1 A ...
<p>Try to use groupby with filter</p> <pre><code>df.groupby('name').filter( lambda x: len(x) &gt; 1 and x['num_1'].iloc[1] &gt; x['num_2'].iloc[0]) </code></pre>
python|pandas
1
370,622
48,651,699
How to sum panda column by unique index, but then reset the sum?
<p>New to Python. I have a pandas DataFrame as follows:</p> <pre><code>User_ID Clicks 23 2 19 3 19 5 22 1 98 8 19 1 19 3 </code></pre> <p>I want to sum the clicks for each User_ID but I want the sum to reset when the User_ID shows up again with a new row, lik...
<p>By using <code>diff</code> and <code>cumsum</code> create the group key , then we using <code>agg</code></p> <pre><code>df.groupby(df['User_ID'].diff().ne(0).cumsum()).agg({'User_ID':'first','Clicks':'sum'}) Out[1176]: User_ID Clicks User_ID 1 23 2 2 19 ...
python|python-3.x|pandas|sum|pandas-groupby
2
370,623
48,484,475
converting results of pickle file (json) to dataframe
<p>I'm reading from a pickle file as follows:</p> <pre><code>data=pickle.load(open("name_ethnicities.pkl", "rb")) </code></pre> <p>it returns what looks like a json file that looks as follows: </p> <pre><code> {'t creavalle': [{'scores': [{'ethnicity': 'Asian', 'score': '0.01'}, {'ethnicity': 'GreaterAfri...
<p>Try this:</p> <pre><code>pd.DataFrame([(k, ", ".join([x["best"] for x in v])) for k, v in data.items()], columns=["name", "ethnicity"]) </code></pre> <p>Explanation:</p> <ul> <li>items and k,v is the way to allow some operations to be done.</li> <li>See for example the output of <code>[(k, v) for k,...
python|python-3.x|pandas|pickle
1
370,624
48,527,270
Pandas Excelwriter Diverging Color Data Bar
<p>I've been fairly successful in conditionally formatting my excel file using pandas/excelwriter</p> <p>However, I am having trouble create diverging colored databars, like the ones that can be create in excel:</p> <p><a href="https://i.stack.imgur.com/0NSJA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/...
<p>This is now possible in XlsxWriter version 1.0.4. See the databar <a href="https://xlsxwriter.readthedocs.io/working_with_conditional_formats.html#conditional-format-options" rel="nofollow noreferrer">Conditional Formatting Options</a>.</p> <p>For you case you could do something like this:</p> <pre><code>worksheet...
python|python-2.7|pandas|pandas.excelwriter
2
370,625
48,455,749
how to merge multi index in pandas
<p>test1.csv</p> <pre><code>"P","E","DT02","DT03" 1, 4, 20020111, 20121222 2, 5, 20021111, 20141222 3, 4, 20021112, 20151222 </code></pre> <p>test2.csv</p> <pre><code>"P", "DT02", "dd" 1, 20020111, 1 2, 20021111, 1 3, 20021113, 0 </code></pre> <p></p> <p>Code:</p> <pre><code>df1 = pd.read_csv('test1.csv') ...
<p>One way to do this is to flatten the multiindex columns, merge and expand flatten column names back to multiindex:</p> <pre><code>df1.columns = df1.columns.map('|'.join) df2.columns= df2.columns.map('|'.join) df_out = df1.merge(df2, on='info|P') df_out.columns = df_out.columns.str.split('|',expand=True) df_out ...
python|pandas
2
370,626
48,494,903
tensorflow reduce_mean with multidimension second argument
<p>I met the usage of the reduce_mean with the vector as the second arguments. I looked through sensor flow manual but can't find the corresponding example. The codes are below:</p> <pre><code>tf.reduce_mean(train, [0,1,2] </code></pre> <p>where train is at size batchsize x H x L x 2 I also played with some experimen...
<p>Just figure out tf.reduce_mean(train, [0,1,2]) if the second argument is the vector. It will reduce the dimension as the order of the element is the vector. For example, the [0,1,2] will reduce along the axis of 0,1,2</p>
tensorflow
1
370,627
48,733,618
How to drop rows from a dataframe as per null values in a specific column?
<p>How to drop rows from a dataframe as per null values in a specific column?</p> <p>Say I have a dataframe that has three columns a,b,c and all can have null values, but I only want to droprows where column b has null/NaN. How can I do that in pandas dataframe?</p>
<p>This should do the trick:</p> <pre><code>df = df.dropna(subset=['b'], axis=1) </code></pre>
python|pandas|dataframe
0
370,628
48,736,149
Pandas Groupby Conditional Filtering
<p>I have a large dataframe similar to below. I want to Groupby 'account', having the Groupby keep only those groups, where there is a "grade" among the group (at least one record within that "account" group has a "grade" more than 0).<br> In this example after grouping by "account", there should only be four groups r...
<p>It sounds like you want <a href="https://pandas-docs.github.io/pandas-docs-travis/generated/pandas.core.groupby.DataFrameGroupBy.filter.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.filter</code></a>, which in your case would boil down to</p> <pre><code>df.groupby('account').filter(lambda x: any(x.grade)) ...
python|python-3.x|filtering|conditional-statements|pandas-groupby
1
370,629
48,719,867
How to create identity matrix with numpy with a specific value K at the diagonal
<p>I would like the array to be like this:</p> <pre><code> array([[K., 0., 0., 0.], [0., K., 0., 0.], [0., 0., K., 0.], [0., 0., 0., K.]]) </code></pre>
<p>Addition to liliscent answer.</p> <p>If you want to have different elements at digonal you can create a list of your diagonal elements.</p> <pre><code>x= [2,3,4] </code></pre> <p>and use <code>np.diag()</code></p> <pre><code>print(np.diag(x)) </code></pre> <p>output:</p> <pre><code>array([[2, 0, 0], [0,...
python|arrays|numpy|matrix
5
370,630
48,637,793
matplotlib ignore missing data
<p>The question has already been asked and has a <a href="https://stackoverflow.com/questions/14399689/matplotlib-drawing-lines-between-points-ignoring-missing-data">good solution</a> using masks. </p> <p>Asking again because I'd like to know if is there a way to make matplotlib handle missing data on its own, somethi...
<p>Short answer: No!</p> <p>Long answer: One could indeed imagine that some feature would be built into matplotlib's <code>plot</code> function that would allow to remove <code>nan</code>s from the input.</p> <p>However, there is none. </p> <p>But since the solution is essentially only one extra line of code, the fa...
python|numpy|matplotlib|missing-data
1
370,631
48,591,623
How to make loading/preprocessing batch data and training parallel in Tensorflow?
<p>I was wondering if we can load and prepossess next batch data while training current batch in Tensorflow.</p> <p>My model requires to load multiple images from different source and do some preprocessing for each training operation, and this whole process is pretty slow. It takes my computer 1.4 seconds to load/proc...
<p>First of all, your code is not possible to execute. Maybe an <a href="https://stackoverflow.com/help/mcve">MVCE</a> can help people to understand better your question.</p> <p>To answer your question, there are two possibilities: </p> <ol> <li><p>The program is launched in CPU. Then the problem is quite simple. I n...
tensorflow
1
370,632
48,626,141
Unnamed Op not showing in list_tensors command during debug session
<p>I have these two unnamed op tensors <code>logits</code> and <code>outputs</code> under a variable scope, but the <code>lt</code> command isn't listing these two tensors under the op 'MatMul' and 'Softmax' during the <code>tfdbg</code> session after a test run on a checkpoint. Here is a snapshot of the code:</p> <pr...
<p>There is really no such thing as "unnamed tensor". If you don't provide a name for an op, it will use a default name. The output tensors will usually be named using the operation's OpDef spec. If there is a single output, it can be named using just the op name. If the name is already taken, it will be made unique by...
python|tensorflow
0
370,633
48,528,190
Get dummies when some categories are not present in a pandas column
<p>Say I have a pandas column as below</p> <p><b>Type</b><br> type1 <br>type2 <br> type3</p> <p>and now i will take dummies for above as follows: <br> <code>type_dummies = pd.get_dummies(["Type"], prefix="type")</code></p> <p>Then after joing it with the main DataFrame the resulting df would be something like below:...
<p>You can using <code>categroy</code> data type </p> <pre><code>df.Type=df.Type.astype('category', categories=['type1','type2','type3','type4']) df Out[200]: Type 0 type1 1 type2 2 type3 pd.get_dummies(df["Type"], prefix="type") Out[201]: type_type1 type_type2 type_type3 type_type4 0 1 ...
python|pandas|dataframe|data-science|data-processing
4
370,634
48,570,778
installing numpy for pypy: No module named setuptools
<p>When I try to set up numpy on windows with the command prompt with</p> <pre><code>C:\numpy&gt;pypy setup.py install </code></pre> <p>I get:</p> <pre><code>ImportError: No module named setuptools </code></pre> <p>But setuptools seems to be installed, do I miss something?</p> <pre><code>&gt;python -m pip install ...
<p><code>python -m pip install --upgrade pip setuptools</code> is installing setuptools for CPython. You need to say <code>pypy -m pip install --upgrade pip setuptools</code>.</p> <p>You may have to say first <code>pypy -m ensurepip</code>, once.</p>
numpy|module|installation|pypy
2
370,635
48,550,201
What does train_on_batch() do in keras model?
<p>I saw a sample of code (too big to paste here) where the author used <code>model.train_on_batch(in, out)</code> instead of <code>model.fit(in, out)</code>. The official documentation of Keras says: </p> <blockquote> <p>Single gradient update over one batch of samples.</p> </blockquote> <p>But I don't get it. Is ...
<p>Yes, <code>train_on_batch</code> trains using a single batch only and once. </p> <p>While <code>fit</code> trains many batches for many epochs. (Each batch causes an update in weights).</p> <p>The idea of using <code>train_on_batch</code> is probably to do more things yourself between each batch.</p>
python|tensorflow|machine-learning|keras|artificial-intelligence
15
370,636
48,483,505
can't install numpy package in pycharm with latest pycharm and python 2.7
<p>I installed Python 2.7, Pycharm 2017.3 and in pycharm in </p> <pre><code>settings &gt; project interpreter &gt; add package </code></pre> <p>I searched for numpy and installed the package but I get this error:</p> <p><img src="https://i.stack.imgur.com/ToCLt.png" alt="error"></p> <pre><code>Error occured: _c...
<p>I suppose that you are trying to install numpy on windows. <br> On windows, install this package could be quite complicated, so my suggestion is to use an unofficial installer for Numpy.</p> <p><a href="https://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow noreferrer">Here</a> you can find the link with all un...
python|python-2.7|numpy|installation|pycharm
0
370,637
48,490,297
Graph a custom function in python
<p>I would like to graph a custom function including <code>min</code> and <code>max</code> :</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.pyplot as plt f = lambda x: max(0, x) x = np.linspace(-10, 10) y = f(x) plt.plot(x, y) plt.show() </code></pre> <p>Result:</p> <block...
<p>use vectorized <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html" rel="nofollow noreferrer"><code>np.clip()</code></a> instead of <code>f</code> - this way you can set both lower (<code>a_min</code>) and upper (<code>a_max</code>) boundaries in one step:</p> <pre><code>y = np.clip(x, a_m...
python|numpy|matplotlib
5
370,638
48,754,049
Pandas group by on one column with max date on another column python
<p>i have a dataframe with following data :</p> <pre><code>invoice_no dealer billing_change_previous_month date 110 1 0 2016-12-31 100 1 -41981 2017-01-30 5505 2 0 2017-01-30 5635 ...
<p>You can use boolean indexing using groupby and transform</p> <pre><code>df_new = df[df.groupby('dealer').date.transform('max') == df['date']] invoice_no dealer billing_change_previous_month date 1 100 1 -41981 2017-01-30 2 5505 2 0 ...
python-2.7|pandas
30
370,639
48,799,502
Size mismatch error during VGG finetuning
<p>I have been following the ants and bees transfer learning tutorial from the official PyTorch Docs (<a href="http://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html" rel="nofollow noreferrer">http://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html</a>). I am trying to finetune a VGG19 mode...
<p>When you are defining your model you are just considering the <code>classifier</code> which consists on the fully connected part of the network only. Then, when feeding the 224*224*3 image to the model it tries to "go through" a linear layer with 25K features as the input. To solve it you just need to add the convol...
python|deep-learning|pytorch|vision|vgg-net
0
370,640
48,546,091
How to filter a pandas DatetimeIndex by day of week and hour in the day
<p>I have a pandas DatetimeIndex and I would like to filter the index by the criterion that the day of the week and hour of the day matches a list. For example, I have of list of tuples indicating valid (day of week, hour, minute) for each TimeStamp:</p> <pre><code>[(4, 6), (5, 7)] </code></pre> <p>The final index s...
<p>You could store the <code>dayofweek</code> and <code>hour</code> methods from your <code>index</code> in variables, and then use them with <code>iloc</code> to filter:</p> <pre><code>dayofweek = df.index.dayofweek hour = df.index.hour df.iloc[((dayofweek == 4) &amp; (hour == 6)) | ((dayofweek == 5) &amp; (hour == ...
python|pandas|filter|datetimeindex
7
370,641
48,797,775
How to select columns of data from a DataFrame
<p><strong>I'm retrieving survey results from Lime Survey via its API (Remote Control):</strong></p> <p><a href="https://i.stack.imgur.com/w08hw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w08hw.png" alt="enter image description here"></a></p> <p><strong>And I manage to get it into a DataFrame....
<p>Check out jq - <a href="https://stedolan.github.io/jq/" rel="nofollow noreferrer">https://stedolan.github.io/jq/</a></p> <p>You can pass your df ['responses'] json to jq and extract the required field and create that as a separate df column.</p> <p>And then you can get the average of the columns from the df.</p>
python|python-3.x|pandas|limesurvey
1
370,642
48,466,640
Python: Why does have 2^-n work for n>52 and not 1+2^-n-1?
<p>I'm pretty new to python, and I've made a table which calculates <code>T=1+2^-n-1</code> and <code>C=2^n</code>, which both give the same values from <code>n=40</code> to <code>n=52</code>, but for <code>n=52</code> to <code>n=61</code> I get 0.0 for <code>T</code>, whereas <code>C</code> gives me progressively smal...
<p>The "floating" in floating point means that values are represented by storing a fixed number of leading digits and a <em>scale factor</em>, rather than assuming a fixed scale (which would be <em>fixed</em> point).</p> <p><code>2**-53</code> only takes one (binary) digit to represent (not including the scale), but <...
python|numpy|math|floating-point
1
370,643
48,457,321
How to filter and keep only 6 digit number in a dataframe column
<p>I have dataframe column . I need keep only numbers which are 6 digits and all others should be named as 'Not Valid'</p> <p><strong>Input</strong></p> <pre><code>data['Post_Code'] 629785 588778 760-\63 76063 76063 S4P2Z6 NP443HO 999999999 8 4 3 3 460803 460803 460803 760439 569139 ABVCD </code></pre> <p><strong>...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>str.extract</code></a> by regex - <code>^</code> for start of string, <code>\d{6}</code> for <code>6 digit</code>s and <code>$</code> for end of string:</p> <pre><code>data['Cle...
python|regex|pandas
1
370,644
48,620,968
How to find min and max time in Chat log conversation using pandas for calculating duration?
<p>Want to calculate the duration of each ID and to write in the separate Columns </p> <pre><code>ID Ques Time Expected output ---------------------------------- 11 Hi 11.21 1min 11 Hello 11.22 13 hey 12.11 10mins 13 what 12.22 14 so 01.01 2mins 14 ok 01.03 -----------------------...
<p>Assumption made:</p> <ol> <li>The file contains time for eachID and Timemin and TimeMax is calculated. The bellow code explains how to calculate the diff in the time and add as a new row</li> </ol> <blockquote> <p>Assuming the <strong><em>data</em></strong> contains the DataFrame.</p> </blockquote> <pre><code>i...
python|pandas|ipython|jupyter-notebook|pandas-groupby
0
370,645
48,609,280
Alternative for Pandas resample
<p>I am looking for a solution to <code>resample</code> <code>time series</code> data on a big scale (tens or hundreds of millions of data records). <code>Pandas</code> <code>resample()</code> worked well until about 10 mio data records were reached, afterwards it actually stopped working, because the hardware had not ...
<p>Look at this: <a href="https://stackoverflow.com/questions/33130490/pandas-panel-resampling-alternatives">Pandas Panel resampling alternatives</a></p> <p>Meanwhile the package is called xarray. Although you can check out dask, which together with xarray can offer fast, parallel resampling (and many other numpy and ...
pandas|for-loop|time-series|resampling
1
370,646
48,741,504
ValueError: operands could not be broadcast together with shapes (400,400,3) (400,400)
<p>I am using pyshearlab package to denoise image.The function expects an image shape of equal size.After the code is executed denoising is ok for some images but some images generates an error like this. ValueError: operands could not be broadcast together with shapes (400,400,3) (400,400). so i i printed the shape of...
<p>When you have an image array of shape (400, 400, 3) in numpy that means that your image has a height and width of 400x400 and 3 channels.</p> <p>Most of the time that would be Red, Green and Blue. Your other image with shape (400, 400) only has one channel. So these images won't work together nicely.</p> <p>You ha...
python-2.7|numpy|image-processing|opencv3.0|scikit-image
2
370,647
48,733,989
How to see the output size of a layer in TensorFlow?
<p>I am new to TensorFlow and currently writing my first CNN using the library. Previously I have used keras and to check the output dimensions of layers used the model.summary() function. How do I check the output dimensions of layers in TensorFlow ? This is my model :</p> <pre><code>generator(input, random_dim, is_...
<p>At compile time (unkown dimensions will have <code>None</code> or <code>?</code> values): </p> <pre><code>a = ... # Your tensor print(a.shape.dims) </code></pre> <p>At runtime (unknown dimensions will be computed from input data): </p> <pre><code>sess = tf.Session() a = ... # Your tensor feed_dict = {...} # Val...
python|tensorflow|deep-learning|conv-neural-network
1
370,648
48,827,226
Python: Replace values while reading CSV file
<p>I have a CSV file with several columns that include integers and a string. Naturally, I get a dtype warning because of the mixed dtypes. I read the file with this general command.</p> <pre><code>df = pd.read_csv(path, sep=";", na_values=missing) </code></pre> <p>I could use <code>low_memory=False</code> or <code>d...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer">converters</a>:</p> <pre><code>In [156]: def conv(val, default_val=999): ...: try: ...: return int(val) ...: except ValueError: ...: return default_...
python|pandas|csv
5
370,649
48,448,472
Try to download all the csv from the ipython console from datacamp
<p>In the working space I have bunch of csv </p> <pre><code>'summer_xxx1.csv' 'summer_xxx2.csv' 'summer_xxx3.csv' </code></pre> <p>that is accesssable from the remote ipython command shell , I want to download them to local machine and try to make sense out of them.</p> <p>I have try following code</p> <pre class="...
<ul> <li>first, <strong>open any datacamp course</strong> , it contains dataset section</li> </ul> <p><a href="https://i.stack.imgur.com/OdXS6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OdXS6.jpg" alt="datacamp dataset" /></a></p> <ul> <li><p>click on file , will be <strong>downloaded as <code>....
python|pandas|csv|ipython
0
370,650
48,462,326
Python - Getting Start and End Index of a Dataframe based on a condition
<p>I am looking for help with the following.</p> <p>Lets say I have a python dataframe as follows:</p> <pre><code>Index A B C 1 10 15 20 2 Null 20 11 3 Null 10 Null 4 Null Null Null 5 29 35 40 </code></pre> <p>I would like to create a record like given below by iterating through...
<p><strong>Option 1</strong></p> <pre><code>In [236]: d = df[list('ABC')].eq('Null') In [246]: pd.DataFrame([[s[s].index[0]+1, s[s].index[-1]+1, 'Null', c] for c, s in d.items()], columns=['StartIndex', 'EndIndex', 'Comment', 'ColumnName']) Out[246]: StartIndex End...
python|pandas|dataframe|record
0
370,651
48,667,739
NumPy module not found after install
<p>So after numerous attempts at installing NumPy, all seem to have gone well until I boot up PyCharm and import numpy. It throws the "Module not found" error with just a single line of code, being:</p> <pre><code>import numpy as numpy </code></pre> <p>It's getting fairly frustrating, after installing numpy through p...
<p>Without knowing exactly what you have installed in your computer, it can be a bit tricky to troubleshoot it. However, you have to be aware that you can have multiple Python installations in your computer. It is quite common to have Python2.X and Python3.X side by side. </p> <p>When you used pip to install numpy, yo...
python|numpy
0
370,652
48,872,234
Using Apply in Pandas Lambda functions with multiple if statements
<p>I'm trying to infer a classification according to the size of a person in a dataframe like this one:</p> <pre><code> Size 1 80000 2 8000000 3 8000000000 ... </code></pre> <p>I want it to look like this:</p> <pre><code> Size Classification 1 80000 &lt;1m 2 8000000 1-1...
<p>Here is a small example that you can build upon:</p> <p>Basically, <code>lambda x: x..</code> is the short one-liner of a function. What apply really asks for is a function which you can easily recreate yourself.</p> <pre><code>import pandas as pd # Recreate the dataframe data = dict(Size=[80000,8000000,800000000...
python|pandas|if-statement|lambda|apply
16
370,653
48,570,596
Why are the pandas plots so different for very similar dataframes?
<p>The following code snippet with partial display from print executes with no problem:</p> <pre><code>import pandas as pd from matplotlib import pyplot as plt import numpy as np import csv ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) df = pd.DataFrame(np.random.randn(1000, 3...
<p>The following code was inserted where strings were being modified for output to the csv files and this works fine --- Eureka :-)</p> <pre><code>if '.' not in nums[3]: # Append '.00' to integer strings nums[3] = nums[3] + '.00' </code></pre>
python|pandas|dataframe|plot
0
370,654
48,758,876
How to do accumulative calculation in data frame in Python?
<p>I have a dataframe like this,</p> <pre><code>import pandas as pd d = {'col1': ["2004-02-26", "2004-02-27", "2004-03-01", "2004-03-02", "2004-03-03", "2004-03-04", "2004-03-05", "2004-03-08", "2004-03-09", "2004-03-10", "2004-03-11", "2004-03-12"], 'col2': [3, 4, 5, 3, ...
<p>Use, <code>cumprod</code> with <code>where</code> and <code>fillna</code>:</p> <pre><code>df['col4'] = (((df.col3.where(df.col3.gt(0))*df.col2) .fillna(1) .cumprod()) .astype(int).mul(1000)) </code></pre> <p>Output:</p> <pre><code> col1 col2 col3 col4...
python|pandas|numpy|dataframe
1
370,655
48,592,885
Finding the index of items cotaining 'inf' or 'nan'
<p>The following is a sample of <em>1 item</em> in my list:</p> <pre><code>array([[ 1, 2, 3, 43, 83, 92], [ 12, 54, 93, 23, 94, 83], [ 23, inf, inf, inf, inf, inf], [ 83, 33, 33, 83, 13, 83], [ 83, nan, 83, ...
<p>Following suggestion by @coldspeed you can obtain an index of elements containing <code>inf</code>s or <code>nan</code>s as </p> <p><code>idx = [i for i, arr in enumerate(f) if not np.isfinite(arr).all()]</code></p> <p>There is a gotcha coming from <code>idx.append(f.index(x))</code> that results in your error. It...
python|list|numpy|indexing
2
370,656
48,748,377
Opening a 20GB file for analysis with pandas
<p>i am new to data Science and Dta Analytics i hope my question is not too naive. I am currently trying to open a file with pandas and python for machine learning purposes it would be ideal for me to have them all in a DataFrame. Now The file is 18GB large and my RAM is 32 GB but i keep getting memory errors.</p>...
<p>Can you work with the data in chunks? If so you can use the iterator interface of pandas to go through the file.</p> <pre><code>df_iterator = pd.read_csv('test.csv', index_col=0, iterator=True, chunksize=5) for df in df_iterator: print(df) # do something meaningful print('finished iteration on {} rows'....
python|pandas|bigdata|anaconda|data-science
0
370,657
48,800,899
error on preprocessing machine learning
<p>I am trying to apply preprocessing on the training data and I also tried rehsape function but that didn't work,I am getting the following errror:</p> <pre><code>ValueError: Found input variables with inconsistent numbers of samples: [34, 12700] </code></pre> <p>Here is my code:</p> <pre><code>import pandas as pd ...
<p>The issue is with <code>X = preprocessing.StandardScaler().fit(X)</code> <code>X=X.mean_</code></p> <p>After this your X will only contain mean of each columns.</p> <p>To transform the data use following code:</p> <pre><code>from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaler.fit(X...
python-3.x|numpy|machine-learning|scikit-learn
1
370,658
48,755,701
How to prevent float imprecision from affecting numpy.arange?
<p>Because <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html" rel="nofollow noreferrer">numpy.arange()</a> uses <code>ceil((stop - start)/step)</code> to determine the number of items, a small float imprecision <code>(stop = .400000001)</code> can add an unintended value to the list.</p> <...
<p>Your goal is to calculate what <code>ceil((stop - start)/step)</code> would be if the values had been calculated with exact mathematics.</p> <p>This is impossible to do given <strong>only</strong> floating-point values of <code>start</code>, <code>stop</code>, and <code>step</code> that are the results of operation...
python|python-2.7|numpy|floating-point
6
370,659
70,865,704
Is there a way to send patches of image into a transformer model for inference or combine the patches together to make one image?
<p>I am making inference with a single image of size <code>224x224</code> on a vision transformer model (deit). However, I divided the image into 196 patches and manipulated the pixels of one patch to check its behaviour. Each patch is of size <code>16x16</code>.</p> <p>On feeding these patches to the model, I got the...
<p>You can use <a href="https://stackoverflow.com/a/66963266/1714410"><code>fold</code> and <code>unfold</code></a> to extract the patches, manipulate them and then re-arrange them back into an image:</p> <pre class="lang-py prettyprint-override"><code># divide the batch of images into non-overlapping patches u = nnf.u...
python|image-processing|pytorch|computer-vision
1
370,660
70,880,589
what does cardinality mean in relation to an image dataset?
<p>After successfully creating a tensorflow image <code>Dataset</code> with:</p> <p><code>dataset = tf.keras.utils.image_dataset_from_directory(...)</code></p> <p>which returns</p> <p><em>Found 21397 files belonging to 5 classes. Using 17118 files for training.</em></p> <p>There is the cardinality method:</p> <p><code>...
<p>The cardinality, in your case, is simply the rounded number of batches:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf import pathlib dataset_url = &quot;https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz&quot; data_dir = tf.keras.utils.get_file('flo...
python|tensorflow|math|tensorflow-datasets
1
370,661
71,089,699
shap.summary_plot(shap_values, X_train3.values, feature_names= X_train3.columns) giving an error after applying data preprocessing
<pre class="lang-py prettyprint-override"><code>df = pd.read_csv(&quot;C:\\Users\\user\\Desktop\\R_Data41.csv&quot;) df.head() feature_names = ['Al', 'Co', 'Cr', 'Fe', 'Ni', 'Cu', 'Mn', 'Ti', 'V', 'Nb', 'Mo', 'Zr','Hf', 'Ta', 'W', 'C', 'Mg', 'Zn', 'Si', 'Re', 'N', 'Sc', 'Li', 'Sn','Be', 'Num_of_Elem', 'Density_calc', ...
<p>Try changing the line</p> <pre><code>shap.summary_plot(shap_values, X_train3.values, feature_names= X_train3.columns) </code></pre> <p>To</p> <pre><code>shap.summary_plot(shap_values, X_train3, feature_names= X_train3.columns) </code></pre> <p>This is because X_train3 is already in the format of a numpy array and do...
python|pandas|numpy|shap
1
370,662
71,025,655
How do filter with multiple contains in pyspark
<p>I'm going to do a query with pyspark to filter row who contains at least one word in array. For example, the dataframe is:</p> <pre><code> &quot;content&quot; &quot;other&quot; My father is big. ... My mother is beautiful. ... I'm going to travel. ... </code></pre> <p...
<p>I think this solution works. Let me know what you think.</p> <pre><code>import pyspark.sql.functions as f phrases = ['bc', 'ij'] df = spark.createDataFrame([ ('abcd',), ('efgh',), ('ijkl',) ], ['col1']) (df .withColumn('phrases', f.array([f.lit(element) for element in phrases])) .where(f.expr('exists(phras...
python|pandas|dataframe|pyspark
2
370,663
71,003,562
Keras denoising autoencoder - logits and labels must have the same first dimension, got logits shape [986624,38] and labels shape [32]
<p>I am trying to construct a denoising autoencoder for a facial recognition project, and with the initial tests i am using the cropped yalefaces dataset, with the training (noisy) images in a folder (with separate folders for each class/person inside) and the testing (regular) images in another one with the same struc...
<p>I was able to reproduce the error, the input dimension and the output dimension needs to be the same in an autoencoder. Changing the architecture of the decoder as follows will help.</p> <pre><code>#decoding architecture x3 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', padding='same')(encoded) x3 = tf.ker...
python|tensorflow|machine-learning|keras|deep-learning
0
370,664
70,777,985
How to create a multiIndex (hierarchical index) dataframe object from another df's column's unique values?
<p>I'm trying to create a pandas multiIndexed dataframe that is a summary of the unique values in each column.</p> <p>Is there an easier way to have this information summarized besides creating this dataframe?</p> <p>Either way, it would be nice to know how to complete this code challenge. Thanks for your help! Here is...
<p>This is a fairly straightforward application of <code>.melt</code>:</p> <pre><code>data.melt().reset_index().groupby(['variable', 'value']).count()/len(data) </code></pre> <p>output</p> <pre><code> index variable value A case 1.0 B 2001 0.2 2002 0.2 2003 0.2 ...
pandas|dataframe|unique|multi-index|hierarchical
0
370,665
70,968,734
How to deal with CUDA version?
<p>How to set up different versions of CUDA in one OS?</p> <p>Here is my problem: Lastest Tensorflow with GPU support requires CUDA 11.2, whereas Pytorch works with 11.3. So what is the solution to install both libraries in Windows and Ubuntu?</p>
<p>One solution is to use Docker Container Environment, which would only need the Nvidia Driver to be of version <code>XYZ.AB</code>; in this way, you can use both PyTorch and TensorFlow versions.</p> <p>A very good starting point for your problem would be this one(ML-WORKSPACE) : <a href="https://github.com/ml-tooling...
tensorflow|deep-learning|pytorch|environment-variables|virtualenv
1
370,666
70,963,646
tensorflow, keras and circular import error
<p>I'm trying my hand at replicating what this dude did on his github and trying to run some of his scripts (stock price prediction allegedly). I keep bumping into this error no matter what I do. I have a feeling I didn't set up tensorflow or keras properly.</p> <pre><code>File &quot;/home/mihai/.local/lib/python3.8/si...
<p>you can look here -&gt; This worked taking from <a href="https://www.tensorflow.org/api_docs/python/tf/keras/utils/plot_model" rel="nofollow noreferrer">TensorFlow documentation</a></p> <p>try is also</p> <pre><code>from keras.utils.vis_utils import plot_model </code></pre> <p>or</p> <pre><code>from tensorflow.keras...
python|tensorflow|keras|plot|model
0
370,667
71,017,287
How can I fill a column with values that are computed between two dates in pandas, with a delay of one row, respecting certain conditions?
<p>I have the following DataFrame:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Distance</th> <th>Position</th> <th>TrainerID</th> </tr> </thead> <tbody> <tr> <td>2017-09-03</td> <td>1000</td> <td>2</td> <td>6529</td> </tr> <tr> <td>2017-09-03</td> <td>1600</td> <td>4</td> ...
<p>I prefer to add a temporary column to calculate the winning probability.</p> <p>In my environment, the following code works fine.</p> <h2>Code</h2> <pre class="lang-py prettyprint-override"><code>import pandas as pd from pandas import Timestamp # create a sample dataframe (a markdown table is shown below as input d...
python|pandas
1
370,668
71,076,558
Pandas: Check each row for condition and insert row below if condition is met
<p>this is my first question here as I really couldn't figure it out with related answers: I have a list of dataframes &quot;df_list&quot;, for each user I have a dataframe which basically looks like:</p> <pre><code>- |User |Timestamp |Timestamp2 |check |in_out 0 |0001 |2022-01-07 ...
<p>You can create a boolean mask using &quot;check&quot; column and add a row using <code>Index.repeat</code> and <code>reindex</code>ing. Then <code>sort_index</code> and delete duplicate values:</p> <pre><code>msk = df['check'].astype('timedelta64[h]') &gt; 15 df = df.reindex(df[msk].index.repeat(2)).append(df[~msk])...
python|pandas|dataframe|datetime
1
370,669
70,888,794
frequency of string (comma separated) in Python
<p>I'm trying to find the frequency of strings from the field &quot;Select Investors&quot; on this website <a href="https://www.cbinsights.com/research-unicorn-companies" rel="nofollow noreferrer">https://www.cbinsights.com/research-unicorn-companies</a></p> <p>Is there a way to pull out the frequency of each of the co...
<p>The solution provided by @Mazhar checks whether a certain term is a substring of a string delimited by commas. As a consequence, the number of occurrences of <code>'Sequoia Capital'</code> returned by this approach is the sum of the occurrences of all the strings that contain <code>'Sequoia Capital'</code>, namely <...
python|pandas|dataframe|frequency|word-cloud
1
370,670
70,806,953
Python - Calculating a rolling mode on a dataframe
<p>I have a dataset that is reporting values for a specific date, that can then be updated on subsequent dates, thus creating 2 columns, <code>Date</code> and <code>Reported_Date</code>, for each <code>Reported_Value</code>. There is a separate <code>ID</code> field that is my dataframe's index. I want to calculate the...
<p>Mode is not a predefined function, however you can apply a custom function using <code>rolling(5).apply(custom_function)</code>. For your case that could be</p> <pre class="lang-py prettyprint-override"><code>dataset['Reported_Value'].rolling(5).apply(lamba s: s.mode()) </code></pre>
python|pandas|mode|rolling-computation
0
370,671
70,875,377
Dask compute on dataframe to add column returns AttributeError
<p>I have a function that adds a column to a DataFrame using a function, for eg</p> <pre class="lang-py prettyprint-override"><code> def myfunc(x): resp_data = {'status': '1', 'data': x} return json.dumps(resp_data) </code></pre> <p>The original Pandas dataframe <code>df</code> is converted into <cod...
<p>A few suggestions:</p> <ul> <li><p>if your function is simple, then it is not necessary to pass the series as an argument, so something like <code>ddf.apply(myfunc, axis=1)</code> should work. If the function takes multiple arguments, then content of the function should specify how to handle multiple columns.</p> </...
python|json|pandas|dask|dask-dataframe
1
370,672
70,765,082
“ warnings.warn('the tensorboard callback does not support '”
<p>“ warnings.warn('the tensorboard callback does not support '” when i wanted to use the Tensorboard ,i meet such promblem <a href="https://i.stack.imgur.com/fqOYh.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>You didn't list the callback in <code>model.fit</code> call.</p> <p>Try:</p> <pre><code>tb_callback = Tensorboard(...) model.fit(..., callbacks=[tb_callback]) </code></pre> <p>I didn't like naming the callback <code>Tensorboard</code>, so I changed it to <code>tb_callback</code>. Then I told <code>model.fit</code> t...
python|tensorflow|keras
0
370,673
70,980,771
Couldn't import pandas in python
<p><img src="https://i.stack.imgur.com/LD4Mh.png" alt="enter image description here" /></p> <p>I have already installed pandas for using it in python but when I write the code to import pandas, it couldn't be used. How can I fix this problem?</p>
<p>Your IDLE and Command Prompt might use different python binaries.</p> <p>There are two options you can try:</p> <ol> <li>To make sure you're using the same python binary that has pandas installed, launch IDLE using <code>python -m idlelib</code> from command prompt</li> <li>If you want to use IDLE from start menu th...
python|pandas
0
370,674
70,906,869
Why my tensorflow do not perform properly
<p>I tried to work tensorflow on my computer but the error message shows as follows<a href="https://i.stack.imgur.com/JNo3h.png" rel="nofollow noreferrer">1</a>, I did install the tensorflow by following the exact instruction of the official website through pip, I do not understand why it happens. Does anyone have the ...
<p>Please check if you have installed <code>CUDA, cuDNN</code> version compatible to your <code>tensorflow</code> version. You can check the <a href="https://www.tensorflow.org/install/source_windows#gpu" rel="nofollow noreferrer">build configurations</a> details here.</p> <p>Also check <a href="https://www.tensorflow....
python|tensorflow
0
370,675
70,911,464
How do I convert one level of pandas MultiIndex column to a standalone column?
<p>I have a dataframe with a MultiIndex column with two levels like this:</p> <pre><code>import pandas as pd df = pd.DataFrame( np.arange(16).reshape(4,4), columns=pd.MultiIndex.from_tuples( ((&quot;ID1&quot;, &quot;Field1&quot;), (&quot;ID1&quot;, &quot;Field2&quot;), (&quot;ID2&quot;, &quot;Field1&quo...
<p>You can try the following:</p> <pre><code>out = (df .set_index('Date') .stack(level=0) .reset_index() .rename({'level_1': 'ID'}, axis=1)) print(out) </code></pre> <p>It gives:</p> <pre><code> Date ID Field1 Field2 0 2021-11-01 ID1 0 1 1 2021-11-01 ID2 2 ...
python|pandas|dataframe
0
370,676
70,870,984
Retraining a Model from 3 Channels (RGB) to 4 Channels (RGBA), can I use the 3 channel weights?
<p>I need to expand a model from RGB to RGBA. I can handle the code rewrite on the model, but instead of retraining the entire model from scratch, I would love to start it off with it's 3 channel weights + zeros.</p> <p>Is there an easy way to change torch's save of 3 channel weights into 4?</p>
<p>Yes, you can do a little bit of &quot;model surgery&quot;. Assuming the input to the model is only processed directly by a convolutional layer then you can just replace that conv layer with another that has <code>in_channels</code> set to <code>4</code>. Then you can set weights to zero and copy over the old weights...
python|pytorch|rgba
4
370,677
70,956,465
Edge weight in networkx
<p>How do I assign to each edge a weight equals to the number of times node i and j interacted from an edge list?</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import networkx as nx import scipy.sparse df = pd.read_csv(&quot;thiers_2011.csv&quot;, header = None) df = df.rename(c...
<p>You can first aggregate the <code>pandas</code> tables to have a weight column, and then load it to <code>networkx</code> with that edge column:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;weight&quot;] = 1.0 df = df.groupby([&lt;id_columns&gt;]).agg({&quot;wight&quot;: sum}).reset_index() </code></...
python|pandas|numpy|networkx|weighted-graph
3
370,678
71,023,592
How to calculate the average of a column where the row meets a certain condition in Pandas
<p>Basically I have this Dataframe:</p> <pre><code>import pandas as pd dict = {'number': [1,1,1,1,1,2,2,2,4,4,4,4,6,6], 'time':[34,33,41,36,43,22,24,32,29,28,33,32,55,51]} df = pd.DataFrame(dict) print(df) </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/CGC4l.png" rel="nofollow noreferrer"><img src="...
<p>Simply use <code>groupby</code> + <code>agg</code>:</p> <pre><code>agg = df.groupby('number')['time'].agg(['count', 'mean']).reset_index() </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; agg number count mean 0 1 5 37.4 1 2 3 26.0 2 4 4 30.5 3 6 2 53.0 </code...
python|pandas|average
3
370,679
70,876,085
Assigning a value in a column based on unique values in another - Pandas
<p>I have 2 columns, column A has many string values, some unique, and some repeat several times in the column. Column B has either 1 or 0. Some unique values have only an equivalent zero in column B and some have only 1, and for some, it may differ between 1 and zero in different rows. I'd like to 'override' the zeroe...
<p>One way I can think of is to sort and use the fillna method to forward fill the zeros -</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'A': list('ABBABCB'), 'B': list('0100011')}) # A B #0 A 0 #1 B 1 #2 B 0 #3 A 0 #4 B 0 #5 C 1 #6 B 1 # First we replace all 0's with nan's df...
pandas
0
370,680
70,984,949
Function of Activation functions
<p>is it possible to define a function of activation function? I tried to do :</p> <pre><code>def activation(): # return nn.Sin() # return nn.Tanh() # return nn.Sigmoid() # return nn.Tanhshrink() return nn.HardTanh(-1,1) # return nn.Hardswish() # return nn.functionnal.silu() </code></pre> <p...
<p>You can either use the object-oriented approach:</p> <pre><code>&gt;&gt;&gt; f = nn.Tanh() &gt;&gt;&gt; output = f(x) </code></pre> <p>Or the functional approach where you will find the equivalent for <a href="https://pytorch.org/docs/stable/generated/torch.nn.Tanh.html" rel="nofollow noreferrer"><code>nn.Tanh</code...
python|pytorch|activation-function
2
370,681
70,789,782
Filter rows in numpy array based on second array
<p>I have 2 2d numpy arrays A and B I want to remove all the rows in A which appear in B.</p> <p>I tried something like this:</p> <pre><code>A[~np.isin(A, B)] </code></pre> <p>but isin keeps the dimensions of A, I need one boolean value per row to filter it.</p> <p>EDIT: something like this</p> <pre><code>A = np.array(...
<p>Probably not the most performant solution, but does exactly what you want. You can change the dtype of <code>A</code> and <code>B</code> to be a unit consisting of one row. You need to ensure that the arrays are contiguous first, e.g. with <a href="https://numpy.org/doc/stable/reference/generated/numpy.ascontiguousa...
python|numpy
2
370,682
70,838,696
How do i find the row echelon form (REF)
<pre><code>import numpy as np import sympy as sp Vec = np.matrix([[1,1,1,5],[1,2,0,3],[2,1,3,12]]) Vec_rref = sp.Matrix(Vec).rref() print(Vec_rref) ##&lt;-- this code prints the RREF, but i am looking for the code for REF (See below) </code></pre> <p>I have found plenty of codes which solves the RREF but not codes f...
<p>You are using the function of sympy: rref wich is associated to &quot;reduced row-echelon form&quot;. You might want to use <code>.echelon_form()</code> instead</p> <pre><code>import numpy as np import sympy as sp from scipy import linalg Vec = np.matrix([[1,1,1,5], [1,2,0,3], [2,1...
python|numpy|sympy|linear-algebra
1
370,683
71,034,704
How to convert images into numpy array quickly?
<p>To train the image classification model I'm loading input data as NumPy array, I deal with thousands of images. Currently, I'm looping through each image and converting it into a NumPy array as shown below.</p> <pre><code>import glob import cv2 import numpy as np tem_arr_list = [] from time import time images_list...
<p>Use the multiprocessing pool to load data parallely. In my PC the cpus count is 16. I tried loading 100 images and below you could see the time taken.</p> <pre><code>import multiprocessing import cv2 import glob from time import time def load_image(image_path): return cv2.imread(image_path) if __name__ == '__...
python|python-3.x|numpy|opencv|computer-vision
2
370,684
70,974,724
Pandas reorder raw content
<p>I do have the following <a href="https://docs.google.com/spreadsheets/d/1ylBKDCNo3srJrwhKBuWa9pMIseBX1LQX62EOlhCSWUs/edit?usp=sharing" rel="nofollow noreferrer">Excel-File</a></p> <p>Which I've converted it to <code>DataFrame</code> and dropped 2 columns using below code:</p> <pre class="lang-py prettyprint-override...
<p>Split the name and reconcat them.</p> <pre><code>import pandas as pd data = {'Name': ['Adedokun, Babatunde Olubayo', &quot;Uwizeye, Dieudonné&quot;]} df = pd.DataFrame(data) def swap_name(name): name = name.split(', ') return name[1] + ' ' + name[0] df['Name'] = df['Name'].apply(swap_name) df </code></pre...
python|pandas
2
370,685
71,086,088
Count strings in Series Python
<p>I have the following dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame({'X': ['Ciao, I would like to count the number of occurrences in this text considering negations that can change the meaning of the sentence', &quot;Hello, not number of negations, in this case we need to take c...
<p>Use <code>iterrows</code>:</p> <pre><code>import re words = ['need', 'number'] res = {} for idx, row in df.iterrows(): count = len(re.findall('|'.join(words), row['X'])) res[idx] = count df['count'] = pd.Series(res) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df ...
python|pandas
1
370,686
70,997,545
how to interpret z-score of a column to find the distribution type?
<p>I have a pandas dataframe with couple of columns.</p> <p>I calculated z-score based on mean and standard deviation for one of the column.</p> <p>Now, i would like to know what distribution based on z-score? Based on histogram i can tell its normal distribution.</p> <p>Is there an programmatic to tell distribution ty...
<p>If distribution is normal distribution, from <code>68–95–99.7</code> rule, <code>68%</code> of the <code>df[col_zscore]</code> will be between <code>-1</code> to <code>1</code> , <code>95%</code> between <code>-2</code> to <code>2</code>, and <code>99.7%</code> between <code>-3</code> to <code>3</code>. On the oth...
python|pandas|statistics|normal-distribution
1
370,687
70,742,037
Python: Calculating the distance between points in an array
<p>I would like to calculate the distance between data points in an array.</p> <p>Example</p> <pre><code>A1 = array([[ 54. , 15. , 1. ], [ 55. , 13.66311896, 1. ], [ 56. , 10.16311896, 1.95491503], [ 57. , 5.83688104, 4.45491503], # ...
<p>Pythagoras theorem states <code>sqrt(a^2+b^2)=c</code> where <code>c</code> is the distance between the tips of the orthogonal lines reaching point <code>a</code> and <code>b</code>.</p> <pre class="lang-py prettyprint-override"><code>import math from math import sqrt dist_list=[] for i in A1[1:]: dist=sqrt(pow(...
python|arrays|numpy|distance
1
370,688
70,993,019
How to get more values from pandas .loc series without Index, Name and dtype
<p>I am creating function that returns value of columns of pandas dataframe depending on input conditions.</p> <p>I am using df.loc to append my list of results but I want my list only to contain the names of Pokemons I need to get instead of the Index, value of column Name, Name of the column and data type of the obje...
<p>Add <code>.iloc[0]</code> to the end of your row selections:</p> <pre><code>def get_best (move,type_poke,stat): max_stat=int() name=[] df =pd.read_csv('get_best.csv') if type_poke!='all' and move!='all': max_stat = df[df['type'].str.contains(type_poke) &amp; df['move'].str.contains(move)][sta...
python|pandas|dataframe|csv
0
370,689
70,908,988
How to do add/merge/concat two or more multiindex pandas dataframe in python to get below output?
<p>This is my first Multiindex DataFrame <strong>df0</strong></p> <pre><code>Attributes Adj Close Close High Symbols AARON AART AARON AART AARON AART Date 2021-12-01 111.3 512.2 111.3 512.2 114.0 519.5 2021-12-02 116.6 512.5 ...
<p>You can simply <code>pd.concat</code> them, and use <code>groupby</code> with <code>level=0</code> (to group by the 0th (1st) level of the index) + <code>first</code>:</p> <pre><code>df = pd.concat([df0, df1]).groupby(level=0).first() </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df Adj Close ...
python|pandas|dataframe
2
370,690
70,779,047
How can I avoid dropping rows with NaNs when using Pandas `where` method?
<p>I'm running into a problem when using the Pandas <code>where</code> method. Specifically, I'm using the <code>where</code> to identify rows in a dataframe that meet specific conditions. If these conditions are met, the <code>where</code> method correctly assigns <code>NaN</code>s to these values. The problem I'm ...
<p>One workaround is to fill your <code>NaNs</code> with some value that you would never otherwise get such as <code>-999</code>. Then these rows definitely won't meet your conditions in <code>np.where</code> and will be filled with <code>NaN</code> in your resulting <code>grouped1</code> DataFrame:</p> <pre><code>grou...
python-3.x|pandas|pandas-groupby|apply|where-clause
1
370,691
70,820,318
How to reorder levels columns in pandas?
<p>this code is same my code except i have 300 columns, i need to reorder columns like this: Total provit, Catgory ,numberofgoodsold for each company. it easy if i have few columns but as i said i have 300.</p> <pre><code>data = {'company': ['AMC', 'ER','CRR' , 'TYU'], 'Reg-ID': ['1222','2334','3444', '4566'], 'Total_p...
<p>What about using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>pandas.DataFrame.reindex</code></a> as follows</p> <pre><code>&gt;&gt;&gt; desired_order = ['Total_provit', 'Catgory', 'numberofgoodsold'] &gt;&gt;&gt; d2.reindex(desired_order, level...
python|pandas|data-analysis
1
370,692
70,759,584
Separating two interleaved arrays into continuous sequences
<p>I'm not sure how to best explain my question in words, so I will provide a code example below. But to at least give it a try. I am solving an eigenvalue problem as a function of some external parameter, which results in two eigenvalues. Those two eigenvalues cross, as the function of the external parameter. Eigenval...
<p>I'm sure there are many adjustments to be made to improve performance, but here's my guess, based on second derivative thresholding:</p> <pre><code># first derivative deriv = np.diff(fun_c) # second derivative deriv2 = np.diff(deriv) # adjust threshold to detect discontinuities switch_points = deriv2 &gt; 0.0002 # i...
python|numpy
1
370,693
51,837,384
Python Pandas Merge data from different Dataframes on specific index and create new one
<p>My code is given below: I have two data frames a,b. I want to create a new data frame c by merging a specific index data of a, b frames. </p> <pre><code>import pandas as pd a = [10,20,30,40,50,60] b = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6] a = pd.DataFrame(a,columns=['Voltage']) b = pd.DataFrame(b,columns=['Current']) c =...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a> for select rows by positions and add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_i...
python-3.x|pandas|dataframe
2
370,694
51,852,465
pandas converting a float remove exponents
<p>I have data that looks like this:</p> <pre><code>Date MBs GBs 0 2018-08-14 20:10 32.00 MB 0.00 GB 1 2018-08-14 20:05 4.00 MB 0.00 GB 2 2018-08-14 20:00 1000.99 MB 1.23 GB </code></pre> <p>I stripped away the MB and GB by doing this:</p> <pre><code>df['MBs']=df['MB'].str.strip...
<p>You are trying to avoid using scientific notation:So here is what you can do:</p> <pre><code>import pandas as pd pd.set_option('display.float_format', lambda x: '%.3f' % x) </code></pre> <p>this line of code set the pandas display format so it will not use scientific notaion</p> <p>reference:<a href="http://panda...
python|pandas|dataframe|jupyter-notebook
9
370,695
51,831,127
Python3.x, Pandas: creating a list of y values depending on the x values
<p>I have a two data sets that are composed of different x values. It looks like the following. </p> <pre><code>import pandas as pd data1=pd.csv_read('Data1.csv') data2=pd.csv_read('Data2.csv') print(data1) data1_x data1_y1 data1_y2 data1_y3 -347.2498 0 2 8 -237.528509 0 3 7 -127.807218 0 0 6 -1...
<pre><code>import pandas as pd from re import sub repl = lambda x : sub("data\d_(\w+)", "New_\\1_data2", x) data1.rename(repl, axis = 'columns').append(data2.rename(repl, axis='columns')).sort_values('New_x_data2') Out[1024]: New_x_data2 New_y1_data2 New_y2_data2 New_y3_data2 0 -394.798507 2 ...
python-3.x|pandas
0
370,696
51,740,012
how to add column as year-month using pandas
<p>I want to create and add one column year-month as index. so how to do it ? my dataset is contain 168 raws.</p> <pre><code> 23.59 26.931 24.740 25.806 24.364 24.477 23.901 . . </code></pre> <p>i want dataset which is look like this:</p> <pre><code> Year-Month product 1990-1 ...
<p>Use</p> <pre><code>In [263]: df['Y_M'] = pd.date_range( start='1990-01-01', periods=len(df.index), freq='MS').strftime('%Y-%m') In [264]: df Out[264]: product Y_M 0 23.590 1990-01 1 26.931 1990-02 2 24.740 1990-03 3 25.806 1990-04 4 24.36...
python|pandas
4
370,697
51,741,665
Calculating the difference between each element against other randomly generated elements in python
<p>I am calculating the difference of each element in a numpy array. My code is</p> <pre><code>import numpy as np M = 10 x = np.random.uniform(0,1,M) y = np.array([x]) # Calculate the difference z = np.array(y[:,None]-y) </code></pre> <p>When I run my code I get <code>[[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]]</code>. ...
<p>You should read the <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" rel="nofollow noreferrer">broadcasting rules</a> for numpy</p> <pre><code>y.T - x </code></pre> <p>Another way:</p> <pre><code>np.subtract.outer(x, x) </code></pre>
python|numpy
2
370,698
51,922,609
Dataframe groupby - rows to columns
<p>DF have</p> <pre><code>,manufacturer,project,type,Metric 0,Honda,project_a,sedan,10 1,Honda,project_a,suv,20 2,Honda,project_a,hatchback,2 3,Toyota,project_a,sedan,11 4,Toyota,project_a,suv,21 5,Toyota,project_a,hatchback,3 6,Honda,project_b,sedan,101 7,Honda,project_b,suv,201 8,Honda,project_b,hatchback,21 9,Toyot...
<p>Seems like you want to <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow noreferrer"><code>pivot_table</code></a> with multiple columns</p> <pre><code>df.pivot_table(columns=['project', 'type'], index=['manufacturer'], values=['Metric']) project project_...
python|pandas|dataframe
1
370,699
51,706,730
Tensorflow, Keras: Tensor normalization by axis
<p>Assume we have images Tensor <code>A</code> with shape <code>(None, 200, 200, 1)</code>. where <code>None</code> is the batch size, and <code>(200, 200, 1)</code> is the image size. </p> <p>How to perform normalization (0 to 1) on each image (not using <code>for</code> iteration)?</p> <p>That is:</p> <pre><code>A...
<p>You can use <code>tf.reduce_max</code> and <code>tf.reduce_min</code>.</p> <pre><code>import tensorflow as tf A = tf.random_normal(shape=(-1, 200, 200, 1)) B = tf.reduce_max(A, axis=(1, 2, 3)) C = tf.reduce_min(A, axis=(1, 2, 3)) print(B.shape) print(C.shape) </code></pre> <p>Output:</p> <pre><code>(?,) (?,) </...
python|tensorflow|keras
0