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
6,300
44,986,651
delete elements from a data frame w.r.t columns of another data frame
<p>I have a data frame say <code>df1</code> with MULTILEVEL INDEX:</p> <pre><code> A B C D 0 0 0 1 2 3 4 5 6 7 1 2 8 9 10 11 3 2 3 4 5 </code></pre> <p>and I have another data frame with 2 common columns in <code>df2</code...
<p>You can do this in a one liner using <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer">pandas.dataframe.iloc</a>, <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer">numpy.where</a> and <a...
python|pandas
1
6,301
45,126,962
Python Numpy array assignment casting int
<p>I'm fairly new with numpy.</p> <p>As shown below, when I try to cast the numeric values from strings to integers, it doesn't seem to 'stick', as below:</p> <pre><code>&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.array([['a','1','2'],['b','3','4']]) &gt;&gt;&gt; a[:,1:3].astype(int) array([[1, 2], [3, 4]]...
<p>You need to first change the <code>dtype</code> of the full array to <code>object</code> in order for it to contain both strings and integers:</p> <pre><code>a = a.astype(object) a[:,1:3] = a[:,1:3].astype(int) print(a) &gt; [['a' 1 2] ['b' 3 4]] </code></pre> <p>Though note that better solutions may exist, for...
python|numpy|int
2
6,302
44,955,185
Change every single element in Numpy object
<p>I have a Numpy object with random N*M elements, and I also have two numbers A and B.</p> <p>Now I want to access every element in this N*M array and make a change, i.e., if the element > 0, replace this element to A (i.e., element &lt;- A), and if this element &lt; 0, replace this element to B (i.e., element &lt;- ...
<p>Boolean masked assignment will change values in place:</p> <pre><code>In [493]: arr = np.random.randint(-10,10,(5,7)) In [494]: arr Out[494]: array([[ -5, -6, -7, -1, -8, -8, -10], [ -9, 1, -3, -9, 3, 8, -1], [ 6, -7, 4, 0, -4, 4, -2], [ -3, -10, -2, 7, -4, 2, 2...
numpy
2
6,303
45,131,230
Reuse value of TensorFlow Variable between sessions without writing to disk
<p>In sklearn, I'm used to having a model that I can run <code>fit</code> and then <code>predict</code> on. However, with TensorFlow, I'm having trouble loading the learned parameters from <code>fit</code> when I'm calling <code>predict</code>. It boils down to me not knowing how to reuse the value of a variable betwee...
<p>To mimic sklearn's model, just wrap <code>session</code> into a single class so that you can share it between methods e.g.</p> <pre><code>class Model: def __init__(self): self.graph = self.build_graph() self.session = tf.Session() self.session.run(tf.global_variables_initializer()) ...
python|tensorflow
2
6,304
56,951,455
How to replace NaN and NaT with None - pandas 0.24.1
<p>I need to replace all <code>NaN</code> and <code>NaT</code> in a <code>pandas.Series</code> with a <code>None</code>.</p> <p>I tried this:</p> <pre><code>def replaceMissing(ser): return ser.where(pd.notna(ser), None) </code></pre> <p>But it does not work:</p> <pre><code>import pandas as pd NaN = float('nan'...
<p>For me working change order of your second solution, tested in <code>0.24.2</code>, but <code>dtype</code>s is changed to object, because mixed types - <code>None</code>s with <code>float</code>s or <code>timestamp</code>s:</p> <pre><code>def replaceMissing(ser): return ser.replace({pd.NaT: None}).where(pd.notn...
python|pandas
2
6,305
45,851,263
pd.describe(include=[np.number]) return 0.00
<p>I use the <code>df_30v.describe(include=[np.number])</code> to give me the summary on my variables in the data frame. However the result is something with too many digit</p> <blockquote> <p>count 235629.000000 235629.000000 235629.000000 119748.000000</p> </blockquote> <p>how can i get the below as a resul...
<p>Call <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.set_option.html" rel="nofollow noreferrer"><code>pd.set_option('precision', 2)</code></a>:</p> <pre><code>In [165]: pd.set_option('precision', 2) In [167]: df = pd.DataFrame(np.random.uniform(0, 10**6, size=(100,5))) In [168]: df.describe()...
python|pandas|dataframe|describe
0
6,306
45,996,727
numpy.random and Monte Carlo
<p>I wrote a Monte Carlo (MC) code in Python with a Fortran extension (compiled with f2py). As it is a stochastic integration, the algorithm relies heavily on random numbers, namely I use <code>~ 10^8 - 10^9</code> random numbers for a typical run. So far, I didn't really mind the 'quality' of the random numbers - this...
<p>I do not think anyone can tell you if this algorithm suffices without knowing how the random numbers are being used.</p> <p>What I would do is to replace the numpy random numbers by something else, certainly there are other modules already available that provide different algorithms. If your simulation results are ...
python|numpy|random|montecarlo|mersenne-twister
2
6,307
45,783,080
Saving model in Tensorflow not working under GPU?
<p><strong>UPDATE: I've found out that the below code DOES work correctly when using tensorflow-cpu. The problem only persists when using tensorflow-gpu. How can I make it work?</strong></p> <p>I cannot find the problem in my code - I am trying to save my variables, and then reload them, and they don't appear to load ...
<p>I've encountered the same problem, and I guess you use <code>tf.Variable()</code>, right? Try to change it to <code>tf.get_variable()</code>. It worked for me :)</p>
python|tensorflow
1
6,308
46,161,119
Pandas - merge many rows into one
<p>with this:</p> <pre><code>dataset = pd.read_csv('lyrics.csv', delimiter = '\t', quoting = 3) </code></pre> <p>I print my dataset in this fashion:</p> <pre><code> lyrics,classification 0 "I should have known better with a girl like you 1 That I would love every...
<h3>Solution that worked for OP (from comments):</h3> <p>Fixing the problem at its source (in <code>read_csv</code>):</p> <blockquote> <p>@nbeuchat is probably right, just try</p> <p><code>dataset = pd.read_csv('lyrics.csv', quoting = 2)</code></p> <p>That should give you a dataframe with one row and two columns: lyric...
python|pandas
1
6,309
45,726,485
Group by column in pandas dataframe and average arrays
<p>I have a movie dataframe with movie names, their respective genre, and vector representation (numpy arrays).</p> <pre><code>ID Year Title Genre Word Vector 1 2003.0 Dinosaur Planet Documentary [-0.55423898, -0.72544044, 0.33189204, -0.1720... 2 2004.0 Isle of Man TT 2004 Review Sports &amp; Fitness ...
<p>If I understand correctly, to get the component-wise averages you can simply apply <code>np.mean</code> to the <code>'Word Vector'</code> SeriesGroupBy explicitly. </p> <pre><code>df.groupby('Genre')['Word Vector'].apply(np.mean) </code></pre> <hr> <p><strong>Demo</strong></p> <pre><code>&gt;&gt;&gt; df = pd.Dat...
python|arrays|pandas|numpy|mean
11
6,310
35,678,910
Pandas GroupBy Index
<p>I have a dataframe with a column that I want to groupby. Within each group, I want to perform a check to see if the first values is less than the second value times some scalar, e.g. (x &lt; y * .5). If it is, the first value is set to True and all other values False. Else, all values are False.</p> <p>I have a ...
<p>Looks like <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow"><code>transform</code></a> is what you need:</p> <pre><code>&gt;&gt;&gt; def func(group): ... res = [False] * len(group) ... if group.iloc[0] &lt; group.iloc[1] * .5: ... res[0] = True ... return res &gt...
python|pandas
2
6,311
35,622,773
The size of an array created from np.random.normal
<p>I am using the numpy's <code>random.normal</code> routine to create a Gaussian with a given mean and standard deviation. </p> <pre><code>array_a = an array of len(100) gaussian = np.random.normal(loc=array_a,scale=0.1,size=len(2*array_a)) </code></pre> <p>So I expect the <code>gaussian</code> to have a <code>mean...
<p>you have to multiplicate <code>len(array_a) * 2</code> instead of <code>len(array_a * 2)</code> and <code>loc=array_a.mean()</code> Try:</p> <pre><code>import numpy as np array_a = np.arange(100) gaussian = np.random.normal(loc=array_a.mean(), scale=0.1, size=2 * len(array_a)) </code></pre> <p>Now <code>gaussian....
python|arrays|numpy|random|gaussian
1
6,312
28,709,810
How can I take a list and add elements in columns in intervals?
<p>Here's my problem: This is for an introductory Python course, however I just cannot wrap my head around how to do this without using loops. I have a list of lists, with each list containing 12 float values corresponding to sunshine hours in a month. Each list of 12 months corresponds to a year (1929 - 2009). Here is...
<p>To answer your updated question, to group the data into decades you can <code>reshape</code> your array and take the mean along the correct axis.</p> <p>This assumes that the number of years you have is divisible by 10 (which it appears to be since you have an array of length 80).</p> <p>So, as a small example, if...
python|arrays|list|numpy
1
6,313
51,003,769
How to apply scipy.stats.describe to each group?
<p>I would appreciate if you could let me know how to apply <code>scipy.stats.describe</code> to calculate summary statistics by group. My data (<code>TrainSet</code>) is like this:</p> <pre><code>Financial Distress x1 x2 x3 0 1.28 0.02 0.87 0 1.27 0.01 0.82 ...
<p>If you wish to describe 3 series independently by group, it seems you'll need 3 dataframes. You can construct these dataframes and then concatenate them:</p> <pre><code>from scipy.stats import describe grouper = df.groupby('FinancialDistress') variables = df.columns[1:] res = pd.concat([pd.DataFrame(describe(g[x...
python|python-3.x|pandas|scipy|statistics
2
6,314
50,748,340
Improve program readability for logic over multiple pandas columns
<p>I need to apply some logic over multiple columns, but all I could do is just write it one at a time (and that's not python way). </p> <pre><code>import numpy as np import pandas as pd data = { 'Ticker':['S&amp;P','Kospi','FTSE','DAX','Topix'], 'P/E_Cur':[26,21,16,14,23], 'P/E_lag_1yr':[22,14,28,31,18...
<p>Here's my attempt using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.all.html" rel="nofollow noreferrer"><code>pd.DataFrame.all</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html" rel="nofollow noreferrer"><code>pd.DataFrame.ma...
python|pandas|dataframe
3
6,315
33,503,806
Use Regex to extract file path and save it in python
<p>I have a text file which holds lots of files path <em>file.txt</em>:</p> <pre><code>C:\data\AS\WO\AS_WOP_1PPPPPP20070506.bin C:\data\AS\WO\AS_WOP_1PPPPPP20070606.bin C:\data\AS\WO\AS_WOP_1PPPPPP20070708.bin C:\data\AS\WO\AS_WOP_1PPPPPP20070808.bin ... </code></pre> <p>What I did with <em>Regex</em> to extract the ...
<p>You can simplify your regex to this:</p> <pre><code>/(....)(..)..\.bin$/ </code></pre> <p>Group 1 will have the year while Group 2 will have the month. I assume that the format is pertaining throughout the file. </p> <p>Now, <code>.</code> represents <em>any</em> character and <code>\.</code> represents "dot" or ...
python|regex|pandas
3
6,316
5,657,444
NumPy: load heterogenous columns of data from list of strings
<p>I'm working with array data stored in an ASCII file (similar to <a href="http://thread.gmane.org/gmane.comp.python.numeric.general/42342" rel="nofollow">this thread</a>). My file is at least 2M lines (158 MB), and is divided into multiple sections with different schemas. In my module to read the format, I want to re...
<p><a href="http://docs.python.org/release/2.6.4/library/stringio.html" rel="nofollow"><code>StringIO</code></a> can make file-type objects from strings. So you could do</p> <pre><code>from StringIO import StringIO m = np.loadtxt(StringIO('\n'.join(lines[5:10]))) </code></pre> <p>Or even easier, just do</p> <pre><co...
python|load|numpy
3
6,317
66,425,898
How to not SELECT rows where certain columns are the same and one column is different?
<p>This seems like a simple thing I'm surprised I haven't done before, but I basically want to remove duplicates based on a few different columns, but only when a particular column is different. I have the option to do this either in SQL or pandas, though SQL would be preferable. So given the following query:</p> <pre>...
<p>It's not that easy with <code>SQL</code> AFAIK. You need to do an implicit join one way or another.</p> <p>For pandas, it's <code>drop_duplicates</code>:</p> <pre><code>(df.sort_values('order_date', ascending=False) .drop_duplicates(['fname', 'lname', 'product_id']) ) </code></pre>
sql|pandas|ssms
1
6,318
66,529,856
Pandas: Combine two data-frames with different shape based on one common column
<p>I have a <code>df</code> with columns:</p> <pre><code>Student_id subject marks 1 English 70 1 math 90 1 science 60 1 social 80 2 English 90 2 math 50 2 science ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> for helper column used for merge with left join:</p> <pre><code>df['g'] = df.groupby('Student_id').cumcount() df1['g'] = df1.groupby('Student_i...
python|python-3.x|pandas|dataframe
1
6,319
66,619,277
Fuzzymatcher returns NaN for best_match_score
<p>I'm observing odd behaviour while performing <code>fuzzy_left_join</code> from <code>fuzzymatcher</code> library. Trying to join two df, left one with 5217 records and right one with 8734, the all records with <code>best_match_score</code> is 71 records, which seems really odd . To achieve better results I even remo...
<p>You could give <a href="https://pypi.org/project/polyfuzz/" rel="nofollow noreferrer"><code>polyfuzz</code></a> a try. Use the examples' setup, for example using <code>TF-IDF</code> or <code>Bert</code>, then run:</p> <pre><code>model = PolyFuzz(matchers).match(df1[&quot;amazon_s3_name&quot;].tolist(), df2[&quot;ama...
python|python-3.x|pandas|fuzzy-search
1
6,320
16,064,308
Include labels for each data point in pandas plotting
<p>Assume we have a DataFrame with prices and volume(think finance).</p> <p>What's the best way to label each price point with the volume of that price point?</p> <pre><code> Price Volume 2013-04-10 04:46 1300 19 2013-04-10 04:47 1305 20 2013-04-10 04:48 1302 6 2013-04-10 04:49 ...
<p>Here is one possible implementation</p> <p>I have import the following:</p> <pre><code>import pandas as pd import datetime as dt import matplotlib.pyplot as plt </code></pre> <p>Now we can recreate the data</p> <pre><code>ind = pd.date_range(start=dt.datetime(2013, 4, 10, 4, 46), periods=4,...
python|pandas
2
6,321
57,373,034
Quickest way to assign cell values in Pandas
<p>I have a list of tuples:</p> <pre><code>d = [("a", "x"), ("b", "y"), ("a", "y")] </code></pre> <p>and the <code>DataFrame</code>:</p> <pre><code> y x b 0.0 0.0 a 0.0 0.0 </code></pre> <p>I would like to replace any <code>0s</code> with <code>1s</code> if the row and column labels correspond to a tuple...
<p><strong>Approach #1: No bad entries in <code>d</code></strong></p> <p>Here's one NumPy based method -</p> <pre><code>def assign_val(df, d, newval=1): # Get d-rows,cols as arrays for efficient usage latet on di,dc = np.array([j[0] for j in d]), np.array([j[1] for j in d]) # Get col and index data...
python|pandas|numpy
2
6,322
57,432,437
Optimize iteration through numpy array when averaging adjacent values
<p>I have a definition in python that </p> <ol> <li>Iterates over a sorted distinct array of Floats</li> <li>Gets the previous and next item</li> <li>Finds out if they are within a certain range of each other</li> <li>averages them out, and replaces the original values with the averaged value</li> <li>rerun through th...
<p>First, if the length of the input array <code>a</code> is large and <code>close</code> is relatively small, your proposed algorithm may be numerically unstable.</p> <p>That being said, here are some ideas that reduce the time complexity from <code>O(N^3)</code> to <code>O(N)</code> (for an approximate implementatio...
python|numpy
2
6,323
24,230,233
Fit gaussian integral function to data
<p>I have a problem with finding a least-square-fit for a set of given data. I know the data follows a function witch is a convolution of a gaussian and a rectangle (x-ray through a broad slit). What I have done so far is taken a look at the convolution integral and discover that it comes down the this: <img src="https...
<p>You have two problems. One is that <code>quad</code> returns a tuple with the value and an estimate of the error, and the other is in how you are vectorizing. You don't want to vectorize on the vectors parameter. <code>np.vectorize</code> has a for loop, so there is no performance gain from doing it yourself:</p> <...
python|numpy|model-fitting
0
6,324
24,089,409
Create dataframe row with positive numbers and other with negative
<p>I have the following dataframe called <strong>Utilidad</strong></p> <pre> Argentina Bolivia Chile España Uruguay 2004 3 6 1 3 2 2005 5 1 4 1 5 </pre> <p>And I calculate the difference between 2004 and 2005 using</p> <pre> Utilidad.ix['resta...
<p><code>numpy.clip</code> will be handy here, or just calculate it .</p> <pre><code>In [35]: Utilidad.ix['positive']=np.clip(Utilidad.ix['resta'], 0, np.inf) Utilidad.ix['negative']=np.clip(Utilidad.ix['resta'], -np.inf, 0) #or Utilidad.ix['positive']=(Utilidad.ix['resta']+Utilidad.ix['resta'].abs())/2 Utilidad.ix['...
python|pandas
1
6,325
43,901,238
pandas keep rows with multiple delimiters
<p>one text file with multiple columns for represntation just showing 2 columns and 5 rows original df has ~400,000 rows</p> <pre><code>col0 col1 A1 info A2 info1,info2 A3 info4,info1,info6 A4 info3,info10 A5 info7,info1,info2,info4,info9 </code></pre> <p>What I would like to do is in there is a row where ...
<p>You need</p> <pre><code>df.col1 = df.col1.str.split(',').str[0] col0 col1 0 A1 info 1 A2 info1 2 A3 info4 3 A4 info3 4 A5 info7 </code></pre> <p>For your second question,</p> <pre><code>df[df.col1.str.split(',').str.len() &gt;1] </code></pre> <p>will return all the row...
python|pandas
3
6,326
43,768,426
numpy vectorization functions
<p>I want to use vectorization to do some computation on <code>numpy.ndarray</code>. Suppose I have the following vectorized function:</p> <pre><code>import numpy as np fun = lambda x:x[0]+x[1] fun = np.vectorize(fun) </code></pre> <p>and the following <code>numpy.ndarray</code></p> <pre><code> a = range(10) b = ra...
<p><code>np.vectorize</code> feeds scalar values to your function. It iterates on the input arrays, broadcasting if needed, and feeds <code>func</code> scalars, not arrays or lists. It then collects the values in a new array of shape and dtype that it deduces.</p> <p>For example:</p> <pre><code>In [108]: fun = lamb...
python|function|numpy|vectorization
1
6,327
43,813,948
Pandas read_csv get rid of enclosing double quotes
<p>Here is my example:</p> <p>I first create dataframe and save it to file</p> <pre><code>import pandas as pd df = pd.DataFrame({'col_1':[['a','b','s'], 23423]}) df.to_csv(r'C:\test.csv') </code></pre> <p>Then <code>df.col_1[0]</code> returns <code>['a','b','s']</code> a list</p> <p>Later I read it from file:</p> ...
<p>You're not going to get the list back without a bit of work</p> <p>Use <a href="https://docs.python.org/2/library/ast.html" rel="nofollow noreferrer"><strong><code>literal_eval</code></strong></a> to convert the lists</p> <pre><code>import ast conv = dict(col_1=ast.literal_eval) pd.read_csv(r'C:\test.csv', index_...
python|csv|pandas
6
6,328
43,817,349
TensorFlow: test_session and device placement
<p>I'm trying to use <code>tf.test.TestCase</code> and test specifically on both GPU and CPU. To this end, I'm using <code>self.test_session</code> and set <code>force_gpu</code> to either <code>True</code> or <code>False</code>. However, when running on a machine without a GPU, the behavior is different depending on w...
<p>The relevant piece of code is here: <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/test_util.py#L385" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/test_util.py#L385</a></p> <p>It is not that enabling logging af...
python-3.x|tensorflow
0
6,329
73,046,713
Replacing all elements except NaN in Python
<p>I want to replace all elements in array <code>X</code> except <code>nan</code> with <code>10.0</code>. Is there a one-step way to do it? I present the expected output.</p> <pre><code>import numpy as np from numpy import nan X = np.array([[3.25774286e+02, 3.22008654e+02, nan, 1.85356823e+02, 1.85356823e+02,...
<p>You can get an array of <code>True</code>/<code>False</code> for <code>nan</code> location using <code>np.isnan</code>, invert it, and use it to replace all other values with 10.0</p> <pre><code>indices = np.isnan(X) X[~indices] = 10.0 print(X) # [[10. 10. nan 10. 10. 10. nan 10.]] </code></pre>
python|numpy
3
6,330
72,886,437
Plot Dynamic graph of live dataframe of multiple columns using Python
<p>I'm trying to plot dynamic graph with live data. Below is sample dataframe in which after every 30 seconds I want to add data which I'm collecting from other function.</p> <p>Dynamic DataFrame</p> <pre><code> TIME CE_15750 CE_15800 CE_15850 CE_15900 CE_15950 PE_16000 PE_16050 PE_16100 PE_16150 PE_16200...
<p>Try this. And tell me how it went. Is worth noting, my changes were the following. I highly doubt you want to make more than one window be displayed every 30 seconds so i took out plt.show() from you func. And i utilized the FuncAnimation, cause that guy is going to call your dataframe multiple times, and update it ...
python|pandas|dataframe|matplotlib|seaborn
0
6,331
73,096,947
How to get the maximum value of a group in the past
<p>In group 3, I want to get the max value of group 1</p> <p>In group 5, I want to get the max value of group 3</p> <p>Input:</p> <pre><code>import pandas as pd A=[20,13,15,25,24,13,14,19,13,11] group=[1,1,2,2,2,3,3,4,4,5] df=pd.DataFrame({'A':A,'group':group}) </code></pre> <p>Expected Output</p> <pre><code> A gr...
<p>One way to go, would be as follows:</p> <pre><code>df['g_max'] = df.groupby('group')['A'].transform('max') df['g-2_max'] = df.group.apply(lambda x: df.g_max[df.group == x-2].max()) print(df) A group g_max g-2_max 0 20 1 20 NaN 1 13 1 20 NaN 2 15 2 25 NaN 3 25 ...
python|pandas|dataframe
1
6,332
73,125,638
Declaring Variables inside the Tensorflow GradientTape
<p>I have a model with a complex loss, computed per class of the model output.</p> <p>As you can see below, I'm computing the loss with some custom loss function, assigning this value to the variable, as tensor are immutable in tensorflow.</p> <pre><code>def calc_loss(y_true, y_pred): num_classes=10 pos_loss_cl...
<p>My current second guess, is that the assign method blocks the gradient, as explained in the tensorflow page you liked... instead, try to use just a plain list:</p> <pre><code>def calc_loss(y_true, y_pred): num_classes=10 pos_loss_class = [] for idx in range(num_classes): pos_loss = SOME_LOSS_FUNC...
tensorflow|gradienttape
0
6,333
3,986,345
How to find the local minima of a smooth multidimensional array in NumPy efficiently?
<p>Say I have an array in NumPy containing evaluations of a continuous differentiable function, and I want to find the local minima. There is no noise, so every point whose value is lower than the values of all its neighbors meets my criterion for a local minimum.</p> <p>I have the following list comprehension which w...
<p>The location of the local minima can be found for an array of arbitrary dimension using <a href="https://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array/3689710#3689710">Ivan</a>'s <a href="https://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array/3689710#3689710">detect_peaks functio...
python|numpy|discrete-mathematics|mathematical-optimization
20
6,334
70,433,762
Filter a cell Dataframe by cell based on a dynamic threshold
<p>I hope you are doing very well and have a good end of the year. First of all, excuse me for my English as I am not a native speaker.</p> <p>My problem is that having a Dataframe on python (for example 30 row and 6 columns), I try to filter cell by cell based on the average of the values on each row (as example: if t...
<p>If need replace values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mean.html" rel="nofollow noreferrer"><code>DataFrame.mean</code></a> use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.clip.html" rel="nofollow noreferrer"><code>DataFra...
python|pandas|dataframe
1
6,335
70,561,070
Dataframe is showing as nill
<p>import pandas as pd from bs4 import BeautifulSoup import requests baseurl = &quot;https://www.amazon.com/&quot; headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36&quot;, &quot;Accept-language&quot;:&quot;en-US, en;q=0.5'} for x i...
<p>The scraping code seems to be working fine, the only problem is with the <code>book_data</code> dictionary variable. The variables link, title, etc does not work in the way you think it does, that is why you are getting a null dataframe as the dictionary variable is empty/wrong.</p> <pre><code>import pandas as pd fr...
python|pandas|web-scraping|beautifulsoup
0
6,336
30,418,489
How do I plug distance data into scipy's agglomerative clustering methods?
<p>So, I have a set of texts I'd like to do some clustering analysis on. I've taken a <a href="http://en.wikipedia.org/wiki/Normalized_compression_distance" rel="nofollow">Normalized Compression Distance</a> between every text, and now I have basically built a complete graph with weighted edges that looks something lik...
<p>You're on the right track with converting the data into a table like the one on the linked page (a redundant distance matrix). According to the documentation, you should be able to pass that directly into <code>scipy.cluster.hierarchy.linkage</code> or a related function, such as <code>scipy.cluster.hierarchy.single...
numpy|machine-learning|scipy|hierarchical-clustering
1
6,337
30,681,446
Python Pandas Dataframe pull column value/index down by one
<p>I am using a pandas DataFrame and I would like to pull one column value/index down by one. So the list Dataframe Length will be one less. Just like this in my example image:</p> <p><img src="https://i.stack.imgur.com/Xts9L.png" alt="DataFrame before -&gt; after"></p> <p>The new DataFrame should be <code>id</code> ...
<p>You can <a href="http://pandas.pydata.org/pandas-docs/version/0.16.1/generated/pandas.Series.shift.html#pandas.Series.shift" rel="nofollow"><code>shift</code></a> the name column and then take a slice using <a href="http://pandas.pydata.org/pandas-docs/version/0.16.1/generated/pandas.DataFrame.iloc.html#pandas.DataF...
python|python-2.7|pandas
2
6,338
30,620,323
Merge two files in Python PANDAS?
<p>I have two files from where I need to fetch information for <code>data analysis</code>. I am using <strong><code>Python Pandas</code></strong> for this. Any help on how to do this will be appreciated. </p> <p>I already know how merge 2 files using Python - I am looking forward to achieve this job in <code>PANDAS</c...
<p>I would suggest to read the csv files into dataframes and concatenate them this way</p> <pre class="lang-py prettyprint-override"><code>frames = [pd.read_csv('f1.csv'), pd.read_csv('f2.csv')] result = concat(frames,ignore_index=True) </code></pre>
python|pandas|analytics
6
6,339
26,678,467
Export a Pandas dataframe as a table image
<p>Is it possible to export a Pandas dataframe as an image file? Something like <code>df.to_png()</code> or <code>df.to_table().savefig('table.png')</code>.</p> <p>At the moment I export a dataframe using <code>df.to_csv()</code>. I then open this csv file in Excel to make the data look pretty and then copy / paste th...
<p>With some additional code, you can even make output look decent:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import six df = pd.DataFrame() df['date'] = ['2016-04-01', '2016-04-02', '2016-04-03'] df['calories'] = [2200, 2100, 1500] df['sleep hours'] = [2200, 2100, 1500] df...
python|pandas
60
6,340
39,220,504
Applying an operation on multiple columns with a fixed column in pandas
<p>I have a dataframe as shown below. The last column shows the sum of values from all the columns i.e. <code>A</code>,<code>B</code>,<code>D</code>,<code>K</code> and <code>T</code>. Please note some of the columns have <code>NaN</code> as well.</p> <pre><code>word1,A,B,D,K,T,sum na,,63.0,,,870.0,933.0 sva,,1.0,,3.0,...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> for selecting columns from <code>A</code> to <code>T</code>, then divide by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="no...
python|pandas|dataframe|sum|multiple-columns
5
6,341
19,521,493
numpy.view gives valueerror
<p>Ran into this in the context of libtiff saving a file, but now I'm just confused. Can anyone tell me why these two are not equivalent?</p> <pre><code>ar1 = zeros((1000,1000),dtype=uint16) ar1 = ar1.view(dtype=uint8) # works ar2 = zeros((1000,2000),dtype=uint16) ar2 = ar2[:,1000:] ar2 = ar2.view(dtype=uint8) # Valu...
<h2>Summary</h2> <p>In a nutshell, just move the view before the slicing.</p> <p>Instead of:</p> <pre><code>ar2 = zeros((1000,2000),dtype=uint16) ar2 = ar2[:,1000:] ar2 = ar2.view(dtype=uint8) </code></pre> <p>Do:</p> <pre><code>ar2 = zeros((1000,2000),dtype=uint16) ar2 = ar2.view(dtype=uint8) # ar2 is now a 1000x...
python|numpy
3
6,342
19,820,280
Offset date for a Pandas DataFrame date index
<p>Given a Pandas dataframe created as follows:</p> <pre><code>dates = pd.date_range('20130101',periods=6) df = pd.DataFrame(np.random.randn(6),index=dates,columns=list('A')) A 2013-01-01 0.847528 2013-01-02 0.204139 2013-01-03 0.888526 2013-01-04 0.769775 2013-01-05 0.175165 2013-01-06 -...
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/dev/timeseries.html#dateoffset-objects">DateOffset</a>:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame(np.random.randn(6),index=dates,columns=list('A')) &gt;&gt;&gt; df.index = df.index + pd.DateOffset(days=15) &gt;&gt;&gt; df A 2013-01-16 ...
python|pandas
24
6,343
29,172,934
Difference in shapes of numpy array
<p>For the array:</p> <pre><code>import numpy as np arr2d = np.array([[1,2,3],[4,5,6],[7,8,9]]) &gt;&gt;&gt; arr2d array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) &gt;&gt;&gt; arr2d[2].shape (3,) &gt;&gt;&gt; arr2d[2:,:].shape (1, 3) </code></pre> <p>Why do I get different shapes when both statements return th...
<blockquote> <p>Why do I get different shapes when both statements return the 3rd row?</p> </blockquote> <p>Because with the first operation you are indexing the rows, and selecting just ONE element, which -as mentioned in the <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#single-element-indexing...
python|numpy
5
6,344
23,695,851
python - repeating numpy array without replicating data
<p>This question has been asked before, but the solution only works for 1D/2D arrays, and I need a more general answer.</p> <p>How do you create a repeating array without replicating the data? This strikes me as something of general use, as it would help to vectorize python operations without the memory hit.</p> <p>M...
<p>One simple trick is to use <code>np.broadcast_arrays</code> to broadcast your <code>(x, y)</code> against a <code>z</code>-long vector in the first dimension:</p> <pre><code>import numpy as np M = np.arange(1500*2000).reshape(1500, 2000) z = np.zeros(700) # broadcasting over the first dimension _, M_broadcast = n...
python|numpy|memory|large-data
5
6,345
29,761,266
Should Image.fromarray(pixels) and np.array(img) leave the data unchanged?
<p>I am trying to generate PNGs using the Image.fromarray() function from PIL but not getting the expected images.</p> <pre><code>arr=np.random.randint(0,256,5*5) arr.resize((5,5)) print arr </code></pre> <p>gives</p> <pre><code>[[255 217 249 221 88] [ 28 207 85 219 85] [ 90 145 155 152 98] [196 121 228 101 ...
<p>The problem is that <code>np.random.randint()</code> returns signed int, while the <code>'L'</code> option to <code>Image.fromarray()</code> tells it to interpret the array as 8-bit <strong>unsigned</strong> int (<a href="https://pillow.readthedocs.org/en/latest/handbook/concepts.html#concept-modes" rel="nofollow">P...
python|numpy|python-imaging-library
1
6,346
29,704,455
NumPy: finding N largest elements in a matrix
<p>Edited since my last question was a duplicate, but I'm struggling with this as well. I'm currently working with a matrix and can easily find the largest element with</p> <pre><code>M[M != 1].max() </code></pre> <p>However, I'm interested in getting the N largest elements and can't find an easy way to do this with ...
<p>Yes there is a <code>where</code> method which takes a condition as one of the parameter ,</p> <pre><code>minimum = M[M != 0].min() print numpy.where(M==minimum) </code></pre>
python|numpy|matrix
0
6,347
62,274,904
How to generate an nd-array where values are greater than 1?
<p>Is it possible to generate random numbers in an nd-array such the elements in the array are between 1 and 2 (The interval should be between 1 and some number greater than 1 )? This is what I did.</p> <pre><code>input_array = np.random.rand(3,10,10) </code></pre> <p>But the values in the nd-array are between 0 and...
<p>You can try scaling:</p> <pre><code>min_val, max_val = 1, 2 input_array = np.random.rand(3,10,10) * (mal_val-min_val) + min_val </code></pre> <p>or use <code>uniform</code>:</p> <pre><code>input_array = np.random.uniform(min_val, max_val, (3,10,10)) </code></pre>
python-3.x|numpy|numpy-ndarray
0
6,348
62,160,650
CSV file to JSON using python
<p>I am currently trying to convert a csv with 4 different fields to a json body for making an api call. The current csv looks like this:</p> <pre><code>firstname, lastname, email, login Jake, Smith, jake.smith@example.com, jake.smith@example.com John, Appleseed, john.appleseed@example.com, john.appleseed@example.com ...
<p>Try this, not the best solution but works:</p> <pre><code>df = pd.read_csv('test.csv') for i in range(0, df.shape[0]): json_data = df.loc[[i]].to_json(orient='records') json_data = json_data.strip('[]') x = json.loads(json_data) j = {'profile': x} print(json.dumps(j)) </code></pre> <p><strong>O...
python|json|python-3.x|pandas|csv
1
6,349
51,466,308
Indices of multiple elements in a numpy array
<p>I have a numpy array and a list as follows</p> <pre><code>y=np.array([[1],[2],[1],[3],[1],[3],[2],[2]]) x=[1,2,3] </code></pre> <p>I would like to return a tuple of arrays each of which contains the indices of each element of x in y. i.e.</p> <pre><code>(array([[0,2,4]]),array([[1,6,7]]),array([[3,5]])) </code></...
<p>One solution is to <code>map</code></p> <pre><code>y = y.reshape(1,len(y)) map(lambda k: np.where(y==k)[-1], x) [array([0, 2, 4]), array([1, 6, 7]), array([3, 5])] </code></pre> <hr> <p>Reasonable performance. For 100000 rows,</p> <pre><code>%timeit list(map(lambda k: np.where(y==k), x)) 3.1 ms ± 113 µs per...
python|numpy
1
6,350
48,789,430
Obtaining index based on connditions
<p>From the following code:</p> <pre><code>aps1.Status.head(10) Out[663]: 0 OK 1 OK 2 OK 3 OK 4 OK 5 OK 6 Fail 7 OK 8 Fail 9 OK </code></pre> <p>How to obtain the indexes for which Status is Fail? I tried:</p> <pre><code> print (index for index,value in enumerate(aps1.Status) if value ...
<p>remove the ']' at the end</p> <pre><code>print (index for index,value in enumerate(aps1.Status) if value == "Fail"**]**) </code></pre>
python|pandas
2
6,351
48,667,218
How to get the N nearest entries to the median in a Pandas series?
<p>For a Pandas Series:</p> <pre><code>ser = pd.Series([i**2 for i in range(9)]) print(ser) 0 0 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 dtype: int64 </code></pre> <p>The median can be grabbed with <code>ser.median()</code>, which returns <code>16</code>. How can the <em>N</em> entries aro...
<p>You can find the abs difference between each value and the median and use <code>sort_values()</code>: </p> <pre><code>ser[abs(ser - ser.median()).sort_values()[0:3].index] #4 16 #3 9 #5 25 #dtype: int64 </code></pre> <p>If you want it as a function, where <code>n</code> is an input variable:</p> <pre...
python|pandas|series|median
3
6,352
48,524,402
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()?
<p>I'm noob with pandas, and recently, I got that 'ValueError' when I'm trying to modify the columns that follows some rules, as:</p> <pre><code>csv_input = pd.read_csv(fn, error_bad_lines=False) if csv_input['ip.src'] == '192.168.1.100': csv_input['flow_dir'] = 1 csv_input['ip.src'] = 1 cs...
<p>So Andrew L's comment is correct, but I'm going to expand on it a bit for your benefit.</p> <p>When you call, e.g.</p> <pre><code>csv_input['ip.dst'] == '192.168.1.100' </code></pre> <p>What this returns is a Series, with the same index as csv_input, but all the values in that series are boolean, and represent wh...
python|pandas|valueerror
0
6,353
48,751,140
Pandas: select rows where two columns are different
<p>Suppose I have a dataframe as below</p> <pre><code>a b c 1 1 45 0 2 74 2 2 54 1 4 44 </code></pre> <p>Now I want the rows where column a and b are not same. So the expected outpu is</p> <pre><code>a b c 0 2 74 1 4 44 </code></pre> <p>How can I do this?</p>
<p>I am a fan of readability, use <code>query</code>:</p> <pre><code>df.query('a != b') </code></pre> <p>Output:</p> <pre><code> a b c 1 0 2 74 3 1 4 44 </code></pre>
python|pandas
21
6,354
48,715,401
set limits to numpy polyfit
<p>I have two arrays with some data. In particular, the y array contains percentages that can not exceed y = 100 value. The y values satisfy the condition y &lt;100 but if I make a fit, the result is that the curve exceeds y = 100, as shown in the figure below.</p> <p>Is there any way to make a curve fit that does not...
<p>You can pass the <code>polyfit</code> function a list of degrees that you want to fit, which means that you can leave out certain degrees (for example the constant value). With a bit of manipulation you can get what you want.</p> <p>Assuming that you want your fit function to reach 100 at your minimum x value (0.25...
python|numpy|matplotlib|curve-fitting
2
6,355
71,073,257
How can i use loop to show the data distribution in a dataset
<p>I am a beginner<br /> How can i use for loop to print all them</p> <pre><code>['MSZoning', 'Street', 'LotShape', 'LandContour', 'Utilities', 'LotConfig', 'LandSlope', 'Neighborhood', 'Condition1', 'Condition2', 'BldgType', 'HouseStyle', 'RoofStyle', 'RoofMatl', 'Exterior1st', 'Exterior2nd', 'MasVnrType', 'E...
<pre><code>xs = ['MSZoning', 'Street', 'LotShape', 'LandContour', 'Utilities', 'LotConfig', 'LandSlope', 'Neighborhood', 'Condition1', 'Condition2', 'BldgType', 'HouseStyle', 'RoofStyle', 'RoofMatl', 'Exterior1st', 'Exterior2nd', 'MasVnrType', 'ExterQual', 'ExterCond', 'Foundation', 'BsmtQual', 'BsmtCond', ...
python|pandas|loops|for-loop|data-science
1
6,356
70,968,601
How to groupby year and unstack years into columns in pandas?
<p>I have a pandas time series <code>ser</code></p> <pre><code>ser &gt;&gt;&gt; date x 2018-01-01 0.912 2018-01-02 0.704 ... 2021-02-01 1.285 </code></pre> <p>and I want to take a cumulative sum by year and make each year into a column as such, and the date index should now be just dates in year (e.g. Jan...
<p>First you can aggregate <code>sum</code> per <code>MM-DD</code> with years and then reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>Series.unstack</code></a>:</p> <pre><code>df = ser.groupby([ser.index.strftime('%m-%d'), ser.in...
pandas|group-by|cumsum
1
6,357
70,790,473
pytorch lightning epoch_end/validation_epoch_end
<p>Could anybody breakdown the code and explain it to me? The part that needs help is indicated with the &quot;#This part&quot;. I would greatly appreciate any help thanks</p> <pre><code>def validation_epoch_end(self, outputs): batch_losses = [x[&quot;val_loss&quot;]for x in outputs] #This part epoch_loss = tor...
<p>Based on the structure, I assume you are using <code>pytorch_lightning</code>.</p> <p><code>validation_epoch_end()</code> will collect outputs from <code>validation_step()</code>, so it's a <code>list</code> of <code>dict</code> with the length of number of batch in your validation dataloader. Thus, the first two <c...
neural-network|pytorch|pytorch-lightning
1
6,358
51,957,712
Can an xlwings UDF return a list of numpy arrays?
<p>I am trying to write an <em>xlwings</em> user-defined function (UDF) which returns a list of <em>numpy</em> arrays in Excel VBA. Is this possible?</p> <p>Whenever I try, I get this error in VBA:</p> <p><a href="https://i.stack.imgur.com/E4nGb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E4nG...
<p>Probably the simplest way to return multiple Numpy arrays is to combine them into a single 2D array in Python and return that.</p>
python|excel|vba|numpy|xlwings
1
6,359
42,073,239
tf.get_collection to extract variables of one scope
<p>I have <code>n</code> (e.g: n=3) scopes and <code>x</code> (e.g: x=4) no of Variables defined in each scope. The scopes are:</p> <pre><code>model/generator_0 model/generator_1 model/generator_2 </code></pre> <p>Once I compute the loss, I want to extract and provide all the variables from only one of the scope base...
<p>You can do something like this in TF 1.0 rc1 or later:</p> <pre><code>v = tf.Variable(tf.ones(())) loss = tf.identity(v) with tf.variable_scope('adamoptim') as vs: optim = tf.train.AdamOptimizer(learning_rate=0.1).minimize(loss) optim_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=vs.name) print([...
python|tensorflow
4
6,360
41,830,190
python - Fill in missing dates with respect to a specific attribute in pandas
<p>My data looks like below:</p> <pre><code>id, date, target 1,2016-10-24,22 1,2016-10-25,31 1,2016-10-27,44 1,2016-10-28,12 2,2016-10-21,22 2,2016-10-22,31 2,2016-10-25,44 2,2016-10-27,12 </code></pre> <p>I want to fill in missing dates among id. For example, the date range of id=1 is 2016-10-24 ~ 2016-10-28, and 2...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="noreferrer"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="noreferrer"><code>resample</code></a> - then is problem <code>fi...
python|pandas
6
6,361
64,334,422
What is wrong with this Numpy/Pandas code to construct new boolean column based on the values in two other boolean columns?
<p>I have the following data set:</p> <p>Beginning Data Set:</p> <pre><code>ObjectID,Date,Price,Vol,Mx 101,2017-01-01,,145,203 101,2017-01-02,,155,163 101,2017-01-03,67.0,140,234 101,2017-01-04,78.0,130,182 101,2017-01-05,58.0,178,202 101,2017-01-06,53.0,134,204 101,2017-01-07,52.0,134,183 101,2017-01-08,62.0,148,176 1...
<p>Use <code>|</code> for bitwise <code>OR</code>, working same like <code>&amp;</code> for bitwise <code>AND</code>:</p> <pre><code>Observations['DoubleCheck'] = Observations['Check'] | Observations['VolPrice'] </code></pre> <p>Or <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.any....
python|pandas|numpy
1
6,362
64,397,362
how to create a new numpy array by masking another numpy array with a single assignment
<p>Supposing A is an NP array.</p> <p>If I do this:</p> <pre><code>B = np.copy(A) B[B !=0] = 1 </code></pre> <p>or</p> <pre><code>A[A != 0]=1 B=np.copy(A) </code></pre> <p>I get B as the masked version of A, i.e. the desired output. However if I try the assignment like this:</p> <pre><code>B= A[A !=0]=1 </code></pre> ...
<p>I must preface this by saying any attempt in doing so massively decreases readability. Just use two lines if you don't want to other people (or yourself) to ever work with that code again. This answer is just supposed to demonstrate what <em>could</em> be done, not what <em>should</em> be done.</p> <p>The expression...
python|arrays|numpy|masking
2
6,363
64,494,143
Pandas to_csv is removing commas
<p>I have a column in my pandas dataframe as a list and when I write the file to csv, it is removing commas inside the list.</p> <p>code to replicate</p> <pre><code>import numpy as np def to_vector(probs, num_classes): vec = np.zeros(num_classes) for i in probs: vec[i] = 1 return vec import pandas...
<p>If you convert the numpy array to list then you will find the desired result. By default, the numpy array wont be dispalyed using commas. The representation of the data inside computer does not use or need commas, they are simply there for display.</p> <pre><code>import numpy as np import pandas as pd def to_vector...
python|pandas|export-to-csv
3
6,364
64,555,242
Personalize pandas boxplot with colors
<p>I've been trying to make a boxplot of some gender data that I divided into two sapareted dataframes, one for male, and one for female. I managed to make the graph basically how I wanted it, but now I would like to make it look better. I'd like to make it look like a seaborn graph, but I wasn't able to find a way to ...
<p>Since <code>sns</code> is best suitable for long form data, let's try melting the data and use <code>sns</code>.</p> <pre><code># melting the data plot_data = df.melt('TP_SEXO') fig, axes = plt.subplots(figsize = (10,7), ncols=2, sharey=True) for ax, (gender, data) in zip(axes, plot_data.groupby('TP_SEXO')) : ...
python|pandas|seaborn|boxplot
0
6,365
64,420,532
How to load and process dataset with million columns with Pandas or Pandas-like library?
<p>I usually find question and discussion about loading dataset with several million rows to python, by using Dask or Pandas chunk-size, but my problem is a bit different. I got millions of columns/features, and only a few thousand records. I found that the data loading time(from csv) with such dataset is absurdly slow...
<p>This was my idea in the comments if you were to use pandas. This is untested, but you could do columns in chunks using <code>usecols</code> dynamically. I said <code>iloc</code> in comments, but that would still require reading the entire file first, so what I meant was <code>usecols</code>. You can just adjust <cod...
python|pandas
2
6,366
47,878,659
Using TensorFlow Audio Recognition Model on iOS
<p>I'm trying to use the TensorFlow audio recognition model (<code>my_frozen_graph.pb</code>, generated here: <a href="https://www.tensorflow.org/tutorials/audio_recognition" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/audio_recognition</a>) on iOS. </p> <p>But the iOS code <code>NSString* network_p...
<p>I believe you are using the pre-build Tensorflow from Cocapods? It probably does not have that op type, so you should build it yourself from latest source.</p> <p>From <a href="https://www.tensorflow.org/mobile/ios_build#building_the_tensorflow_ios_libraries_from_source" rel="nofollow noreferrer">documentation</a>:...
ios|tensorflow
2
6,367
47,947,310
How to specify model directory in Floydhub?
<p>I am new to Floydhub. I am trying to run the code from <a href="https://github.com/dennybritz/chatbot-retrieval/" rel="nofollow noreferrer">this github repository</a> and the corresponding tutorial.</p> <p>For the training, I successfully used this command:</p> <pre><code> floyd run --gpu --env tensorflow-1.2 --da...
<p>You can mount the output of any job just like you mount a data. In your example:</p> <p><code>--data janinanu/projects/retrieval-based-dialogue-system- on-ubuntu-corpus/18/output:model_dir</code></p> <p>should mount the entire output directory from run 18 to <code>/mount_dir</code> of the new job.</p> <p>You can ...
tensorflow|nlp|deep-learning
2
6,368
47,894,387
How to correlate an Ordinal Categorical column in pandas?
<p>I have a DataFrame <code>df</code> with a non-numerical column <code>CatColumn</code>.</p> <pre><code> A B CatColumn 0 381.1396 7.343921 Medium 1 481.3268 6.786945 Medium 2 263.3766 7.628746 High 3 177.2400 5.225647 Medium-High </code></pre> <p>I want to include <code>CatColumn</code>...
<p>I am going to <strong>strongly</strong> disagree with the other comments.</p> <p>They miss the main point of correlation: How much does variable 1 increase or decrease as variable 2 increases or decreases. So in the very first place, order of the ordinal variable must be preserved during factorization/encoding. If ...
python|pandas|scikit-learn|correlation|categorical-data
32
6,369
48,927,671
assigning the value to a user depending on the cluster he comes from
<p>I have two dataframes, one with the customers who prefer songs, and my other dataframe consists of users and their cluster.</p> <p>DATA 1:</p> <pre><code>user song A 11 A 22 B 99 B 11 C 11 D 44 C 66 E 66 D 33 E 55 F 11 F 77 </code></pre> <p>DATA 2:</p> <pre><code>user cluster A 1 ...
<p>Use sets for comparison.</p> <p><strong>Setup</strong></p> <pre><code>df1 # user song # 0 A 11 # 1 A 22 # 2 B 99 # 3 B 11 # 4 C 11 # 5 D 44 # 6 C 66 # 7 E 66 # 8 D 33 # 9 E 55 # 10 F 11 # 11 F 77 df2 # user cluster # 0 A...
python|pandas|pandas-groupby
1
6,370
49,302,095
Plot dataframe then add vertical lines; how get custom legend text for all?
<p>I can plot a dataframe (2 "Y" values) and add vertical lines (2) to the plot, and I can specify custom legend text for either the Y values OR the vertical lines, but not both at the same time.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt d = {'x' : [1., 2., 3., 4.], 'y1' : [8., 6., 4., 2.], '...
<p>Each call to <code>legend()</code> overwrites the initially created legend. So you need to create one single legend with all the desired labels in. </p> <p>This means you can get the current labels via <code>ax.get_legend_handles_labels()</code> and replace those you do not like with something else. Then specify th...
python|pandas|matplotlib
6
6,371
48,997,373
output logical series based on multiple conditions pandas
<p>I'd like to create a new series of logical values based on the evaluation of multiple conditions.</p> <p>For example</p> <pre><code>&gt; df = pd.DataFrame({'id':[40, 20, 50, 5, 80], 'value': ['a', 'd', 'g', 'g', 'g']}) ​ &gt; df[(df.id &gt; 40) &amp; (df.value.isin(['a', 'g']))] id value 2 50 g 4 80 g </co...
<p>Just use:</p> <pre><code>s = (df.id &gt; 40) &amp; (df.value.isin(['a', 'g'])) print(s) </code></pre> <p>Output:</p> <pre><code>0 False 1 False 2 True 3 False 4 True dtype: bool </code></pre>
python|pandas
1
6,372
49,099,440
Print string list vertically
<p>I have a dataframe as below.</p> <pre><code>df = pd.DataFrame({'Title': ['x','y','z','aa'], 'Result': [2, 5, 11, 16]}) </code></pre> <p>I want to return a text string only including those which are more than 10. </p> <p>example of the result i want is below</p> <pre><code>From the results in df, the below return...
<p>change</p> <pre><code>print ('From the results in df, the below returned greater than 10:\n\t%s' (df3)) </code></pre> <p>to</p> <pre><code>print ('From the results in df, the below returned greater than 10:') for n in df3: print('\t' + str(n)) </code></pre>
python|numpy
2
6,373
58,889,216
Rolling average and sum by days over timestamp in Pyspark
<p>I have a PySpark dataframe where the timestamp is in units of days. Following is an example of the dataframe (let's call it <code>df</code>):</p> <pre><code>+-----+-----+----------+-----+ | name| type| timestamp|score| +-----+-----+----------+-----+ |name1|type1|2012-01-10| 11| |name1|type1|2012-01-11| 14| |nam...
<p>You can use below code to calculate the sum and average of score over last 3 days including current day.</p> <pre><code># Considering the dataframe already created using code provided in question df = df.withColumn('unix_time', F.unix_timestamp('timestamp', 'yyyy-MM-dd')) winSpec = Window.partitionBy('name').order...
python|pandas|pyspark|pyspark-sql|pyspark-dataframes
3
6,374
58,909,204
Proper way to extract embedding weights for CBOW model?
<p>I'm currently trying to implement the CBOW model on managed to get the training and testing, but am facing some confusion as to the "proper" way to finally extract the weights from the model to use as our word embeddings.</p> <h2>Model</h2> <pre><code>class CBOW(nn.Module): def __init__(self, config, vocab): ...
<p>Yes, <code>model_train.embed.weight</code> will give you a torch tensor that stores the embedding weights. Note however, that this tensor also contains the latest gradients. If you don't want/need them, <code>model_train.embed.weight.data</code> will give you the weights only.</p> <p>A more generic option is to cal...
deep-learning|nlp|pytorch
1
6,375
58,960,475
Pandas - Apply logic to every column in DataFrame
<p>I have Dataframe that has 50 columns. I am trying to apply a certain logic to every column</p> <p>Logic I am trying to apply is </p> <pre><code>df[1] = df[1].str.split("'",expand=True) </code></pre> <p>The above logic works well for column with <code>index 1</code>, how could I extend this to every column in the ...
<p>Actually it is neater to use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>.apply()</code></a>:</p> <pre><code>def custom_split(string): return string.str.split("'", expand=True) df.apply(custom_split) </code></pre>
python|pandas
2
6,376
58,763,079
Subtracting booleans obtained from numpy variables results in TypeError
<p>I have trouble understanding this weird behaviour while using numpy variable-</p> <pre><code>import numpy as np from operator import lt,gt val = lt(np.float64(0.8514),0) - gt(np.float(0.8514),0) </code></pre> <p>This fails with the following error- </p> <pre><code>TypeErrorTraceback (most recent call last) &lt;ip...
<p>As the error message indicates, the <code>-</code> operator is deprecated. Just use the <code>^</code> operator for logical operations instead.</p> <pre><code>import numpy as np from operator import lt, gt exp1 = lt(np.float64(0.8514), 0) exp2 = gt(np.float64(0.8514), 0) val = exp1 ^ exp2 print(val) # True </code...
python|numpy
1
6,377
70,168,024
How to transpose two particular column and keep first row in python?
<p>I have the data frame as follows:</p> <pre><code> df = pd.DataFrame({ 'ID': [12, 12, 15, 15, 16, 17, 17], 'Name': ['A', 'A', 'B', 'B', 'C', 'D', 'D'], 'Date':['2019-12-20' ,'2018-12-20' ,'2017-12-20' , '2016-12-20', '2015-12-20', '2014-12-20', '2013-12-20'], 'Color':['Black', 'Blue', ...
<p>Use virtual groups to set each row to a column. The rest is just formatting.</p> <pre><code># Identify target column for each row out = df.assign(col=df.groupby('Name').cumcount().astype(str)) \ .pivot(index=['ID', 'Name'], columns='col', values=['Date', 'Color']) \ .ffill(axis=1) # Sort columns acc...
python|pandas|multiple-columns|rows|swap
2
6,378
70,215,756
When using geopandas explore() method is there a way to restrict the boundaries of the resulting map?
<p>I am trying to show an interactive heatmap of the United States using explore(). But it shows the entire world. Is there any way to restrict it to only the United States?</p>
<p>you can pass same parameters as if you were using <strong>folium</strong> directly. For example, center on USA geometry centroid</p> <pre><code>gdf = gpd.read_file(gpd.datasets.get_path(&quot;naturalearth_lowres&quot;)) gdf.explore( &quot;pop_est&quot;, cmap=&quot;Blues&quot;, location=gdf.loc[gdf[&quot...
python|pandas|geopandas
0
6,379
70,120,519
Python version mismatch: module was compiled for Python 3.6, but the interpreter version is incompatible: 3.9.8
<p>In order to install the newest <code>tensorflow</code>(2.7.0), I updated my <code>python3</code> verison from <code>3.6.6</code> to <code>3.9.8</code>. Here is how I do it inside my <strong>docker</strong>!!.</p> <pre><code>Download the Python-3.9.8.tgz file 1. tar -xf Python-3.9.8.tgz 2. cd Python-3.9.8 &amp; ./c...
<p>For my question, the issue starts from <code>File &quot;/usr/local/lib/python3.6/site-packages/tensorflow/__init__.py&quot;</code>. Though I installed <code>Python3.9</code>, python search <code>python3.6</code> lib as well. The solution is simple: delete <code>/usr/local/lib/python3.6/</code></p>
python-3.x|tensorflow|tensorflow2.0|cpython
0
6,380
55,712,905
dataframe parameters: Why do the changes on my df are local?
<p>I have a function that is supposed to implement some transformations and calculations on a df, the code runs but once it's done df remains the same as before.</p> <p>EDIT: The problem is solved when I remove the line 2 (pd.merge), but I'd like to understand why.</p> <pre class="lang-py prettyprint-override"><code>...
<p>You are setting the global var <code>Tilt</code> with the sum of <code>ptf</code> but not returning the modified <code>ptf</code> DataFrame. </p>
python|pandas
0
6,381
55,777,588
Size mismatch for DNN for the MNIST dataset in pytorch
<p>I have to find a way to create a neural network model and train it on the MNIST dataset. I need there to be 5 layers, with 100 neurons each. However, when I try to set this up I get an error that there is a size mismatch. Can you please help? I am hoping that I can train on the model below:</p> <pre><code>class Mni...
<p>You setup your layer to get a batch of 1D vectors of dim 784 (=28*28). However, in your <code>forward</code> function you <code>view</code> the input as a batch of 2D matrices of size 28*28.<br> try viewing the input as a batch of 1D signals:</p> <pre><code>xb = xb.view(-1, 784) </code></pre>
neural-network|pytorch|mnist
0
6,382
64,732,158
boxplot not show the plots
<p>Following this <a href="https://towardsdatascience.com/a-step-by-step-introduction-to-pca-c0d78e26a0dd" rel="nofollow noreferrer">tutorial</a>, I used the first few statements in order to show the distribution of iris data as below</p> <pre><code>from sklearn.datasets import load_iris from pandas import DataFrame im...
<p>I'm using jupyter notebook and the same code showed me the plots. if you are use python code I think you have to use</p> <pre><code>matplotlib.pyplot.show() </code></pre> <p>to see the plots</p>
python-3.x|pandas|dataframe
1
6,383
64,911,356
How to optimally update cells based on previous cell value / How to elegantly spread values of cell to other cells?
<p>I have a &quot;large&quot; DataFrame table with index being country codes (alpha-3) and columns being years (1900 to 2000) imported via a pd.read_csv(...) [as I understand, these are actually string so I need to pass it as '1945' for example].</p> <p>The values are 0,1,2,3. I need to &quot;spread&quot; these values ...
<p>You can use <code>df.replace(to_replace=0, method='ffil)</code>. This will fill all zeros in your dataframe (except for zeros occuring at the start of your dataframe) with the previous non-zero value per column.</p> <p>If you want to do it <code>rowwise</code> unfortunately the <code>.replace()</code> function does ...
python|pandas
1
6,384
65,045,427
Callbacks in tensorflow 2.3
<p>I was writing my own callback to stop training based on some custom condition. EarlyStopping has this to stop the training once condition is met:</p> <pre><code>self.model.stop_training = True </code></pre> <p>e.g. from <a href="https://www.tensorflow.org/guide/keras/custom_callback" rel="nofollow noreferrer">https:...
<p>I copied your code and added a few print statements to see what is going on. I also changed the loss being monitored from training loss to validation loss because training loss tends to keep decreasing over many epochs while validation loss tends to level out faster. Better to monitor validation loss for early stop...
tensorflow|keras|callback|early-stopping
1
6,385
64,678,082
Getting same result for different CSV files
<p>DESCRIPTION: I have a piece of Python code, and this code takes a CSV file as input and produces a .player file as output. I've four different CSV files, hence, after running the code four times (taking each CSV file one by one), I've four .player files.</p> <p>REPOSITORY: <a href="https://github.com/divkrsh/gridlab...
<p>Analyzing the repository we can see:</p> <p><code>x = np.arange(rows_to_make)</code></p> <p><code>x = preprocessing.minmax_scale(x, feature_range=(0, rows_to_make), axis=0, copy=True)</code></p> <p><code>y_new = preprocessing.minmax_scale(x, feature_range=(0, 1), axis=0, copy=True)</code></p> <p>x is the same for ev...
python|python-3.x|pandas|numpy|csv
2
6,386
64,793,458
fastest polynomial evaluation in python
<p>I'm working on an old project of building Newton Basins and I'm trying to make it as fast as possible. The first thing I'm trying to speed up is how to evaluate a polynomial function at a given complex point <code>x0</code>. I thought of 4 different ways of doing this and tested them with <code>timeit</code>. The co...
<p>Examining the <a href="https://github.com/numpy/numpy/blob/v1.19.0/numpy/lib/polynomial.py#L665-L735" rel="nofollow noreferrer">source code</a> of the <code>polyval()</code> function of numpy you'll observe that this is a purely pythonic function. Numpy uses Horner's method for polynomial evaluation (and facilitates...
python|algorithm|performance|numpy
3
6,387
64,841,988
How to apply distance IoU loss?
<p>I'm currently training custom dataset using this repository: <a href="https://github.com/zylo117/Yet-Another-EfficientDet-Pytorch" rel="nofollow noreferrer">https://github.com/zylo117/Yet-Another-EfficientDet-Pytorch</a>.</p> <p>The result of training is not satisfactory for me, so I'm gonna change the regression lo...
<ol> <li><p>I've seen this done a couple ways, but typically the methods work by assigning the boxes. Calculating 1000x2 array of IOU, you can assign each prediction box a ground truth target and threshold the IOU for good/bad predictions as seen in RetinaNet or assign each ground truth target the best prediction box a...
python|pytorch|object-detection|loss-function|bounding-box
1
6,388
40,026,441
Joining Dataframes on DatetimeIndex by Seconds and Minutes for NaNs
<p>I'm looking for a good way to align dataframes each having a timestamp that "includes" seconds without loosing data. Specifically, my problem looks as follows:</p> <p>Here <code>d1</code> is my "main" dataframe.</p> <pre><code>ind1 = pd.date_range("20120101", "20120102",freq='S')[1:20] data1 = np.random.randn(le...
<p>Use the DateTimeIndex attribute <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.minute.html" rel="nofollow"><code>.minute</code></a> to perform grouping and later fill the missing values with it's mean across each group(every minute):</p> <pre><code>df['0'] = df.groupby(df.index....
python|pandas|datetimeindex|datetime64
0
6,389
44,077,331
Pandas iterate max value of a variable length slice in a series
<p>Let's assume i have a Pandas DataFrame as follows: </p> <pre><code>import pandas as pd idx = ['2003-01-02', '2003-01-03', '2003-01-06', '2003-01-07', '2003-01-08', '2003-01-09', '2003-01-10', '2003-01-13', '2003-01-14', '2003-01-15', '2003-01-16', '2003-01-17', '2003-01-21', '2003-01-22', '2003...
<ul> <li>find zeros</li> <li><code>cumsum</code> to make groups</li> <li><code>mask</code> the zeros into their own group <code>-1</code></li> <li>find the max location in each group <code>idxmax</code></li> <li>get rid of the one for group <code>-1</code>, that was for zeros anyway</li> <li>get <code>a.original</code>...
pandas|python-3.5
4
6,390
44,165,605
Pandas add calculated row to bottom of dataframe
<p>Below is a small sample of a dataframe I have, and I want to add a calculated row to the bottom of it:</p> <pre><code>sch q1 q2 q3 acc Yes Yes No acc Yes No No acc Yes No No acc Yes Yes Yes </code></pre> <p>I want to add a row at the bottom that will give me th...
<p>I see your lambda and raise a pure pandas solution:</p> <pre><code>df.append(df.eq('Yes').mean(), ignore_index=True) </code></pre> <p>You don't specify what should happen to the <code>sch</code> column, so I ignored it. In my current solution this column will get the value <code>0</code>.</p>
python|pandas
3
6,391
69,559,617
Open certain amount of files by glob
<p>I'm trying to use <code>glob</code>to open excel file in one folder and then <code>concat</code> them into 1 file but it takes quite a long time to open all files and then concat like that (each file contents around 20000 rows).</p> <p>So I would like to ask is there anyway to open certain amount of files using glob...
<blockquote> <p>Or is there another way to make it</p> </blockquote> <p>I generally deal with this by using the os method <code>listdir</code> to list all available files in a given directory (<em>e.g.</em> <code>path_to_files</code>), then open them using the pandas <code>read_csv</code> or <code>read_excel</code> me...
python|pandas
1
6,392
69,543,371
Filter rows based on multiple columns entries
<p>I have a dataframe which contains millions of entries and looks something like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Chr</th> <th style="text-align: center;">Start</th> <th style="text-align: right;">Alt</th> </tr> </thead> <tbody> <tr> <td style...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.all.html" rel="nofollow noreferrer"><code>DataFrame.all</code></a> + <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.sum.html" rel="nofollow noreferrer"><code>Series.sum</code></a>:</p> <pre><code>res = (df[[&quot;Chr&quot...
python|pandas
1
6,393
40,819,246
python pandas - retrieve index timestamp value at cummax()
<p>I am retrieving the cummax() value of the following dataframe,</p> <pre><code> exit_price trend netgain high low MFE_pr exit_time 2000-02-01 01:00:00 1400.25 -1 1.00 1401.50 1400.25 1400.25 2000-02-01 01...
<p>This is probably what you are looking for.</p> <pre><code>import pandas as pd import datetime df = pd.DataFrame({'a': [1, 2, 1, 3, 2, 5, 4, 3, 5]}, index=pd.DatetimeIndex(start= datetime.datetime.fromtimestamp(0), pe...
python|pandas
2
6,394
41,216,528
Importing sklearn error
<p>So I have been trying to install numpy, scipy and sklearn for a course I am taking. After many issues and numerous attempts, I installed pycharm and used their built in package manager to get numpy and scipy. I also installed sklearn but when I import it in my code i get the following error:</p> <pre><code>Tracebac...
<p>If you just want to get something up and running for a course and you want to make it work on Windows. Then I suggest you to install anaconda package manager. It works like a breeze on Windows and is very easy to install and contains all the necessary packages (you don't have to worry about version mismatch and ever...
python|numpy|scipy|scikit-learn|pycharm
0
6,395
53,970,350
ValueError contains new labels when trying to label encode in python
<p>I have a dataset which requires label encoding. I am using sklearn's label encoder for the same.</p> <p>Here is the reproducible code for the problem:</p> <pre><code>import pandas as pd from sklearn.preprocessing import LabelEncoder data11 = pd.DataFrame({'Transaction_Type': ['Mortgage', 'Credit reporting', 'Cons...
<p>You are missing <strong>fit_transform()</strong> and that's why you are getting error.</p> <p><strong>sklearn.preprocessing.LabelEncoder</strong> -> Encode labels with value between 0 and n_classes-1 (from official docs)</p> <p>Still if you want to encode your classes between 1 and n_classes, you just need to add ...
python|pandas|dataframe|encoding
1
6,396
54,116,967
What is an efficient way to make rows by every set of two data elements?
<p><strong>Objective</strong>: to take pairs from data and create a new labeled dataframe with the appropriate rows</p> <pre><code>data = [2618926, -1, 2955664, 2978, 2959058, -1, 3038766, 4470, 3044420, -1] column = ['Date','Value'] </code></pre> <p>I need to create a dataframe from the variable 'Data' and display ...
<p>I'll use my favourite <code>zip</code> and <code>iter</code> recipe:</p> <pre><code>it = iter(data) pd.DataFrame(list(zip(it, it)), columns=column) # Or, let pandas exhaust the iterator for you. # pd.DataFrame.from_records(zip(it, it), columns=column) Date Value 0 2618926 -1 1 2955664 2978 2 295905...
python|python-3.x|pandas|list|dataframe
4
6,397
53,953,121
Dataframe summary math based on condition from another dataframe?
<p>I have what amounts to 3D data but can't install the Pandas recommended <a href="http://xarray.pydata.org/en/stable/" rel="nofollow noreferrer">xarray package</a>.</p> <h3>df_values</h3> <pre><code> | a b c ----------------- 0 | 5 9 2 1 | 6 9 5 2 | 1 6 8 </code></pre> <h3>df_conditi...
<p>IIUC Boolean mask </p> <pre><code>df[c.eq('y')].mean().mean() 6.5 </code></pre> <p>Or you may want </p> <pre><code>df[c.eq('y')].sum().sum()/c.eq('y').sum().sum() 5.833333333333333 </code></pre>
python|pandas|dataframe
1
6,398
54,117,856
How to create a loss-function for an unsupervised-learning model, where the ouput resembles the direct input for a game agent?
<p>I'm trying to setup a deep neuronal network, which predicts the next move for a game agent to navigate a world. To control the game agent it takes two float inputs. The first one controls the speed (0.0 = stop/do not move, 1.0 = max. speed). The second controls the steering (-1.0 = turn left, 0.0 = straight, +1.0 =...
<p>The problem you are talking is belong to <code>reinforcement-learning</code>, where agent interact with environment and collect data that is game state, its action and reward/score it got at end. Now there are many approaches.</p> <p>The one you are talking is <code>policy-gradient</code> method, And loss function ...
tensorflow|deep-learning|unsupervised-learning|loss
1
6,399
54,063,768
Selecting rows with the highest value based on 1 column in the dataframe
<p>I have a set of dataframe with about 20k rows. with headings X,Y,Z,I,R,G,B. ( yes its point cloud)</p> <p>I would wanna create numerous sub dataframes by grouping the data in rows of 100 after sorting out according to column X. Subsequently i would like to sort all sub dataframes according to Y column and breaking ...
<p>Considering a dummy dataframe of 1000 rows,</p> <pre><code>df.head() # first 5 rows X Y Z I R G B 0 6 6 0 3 7 0 2 1 0 8 3 6 5 9 7 2 8 9 7 3 0 4 5 3 9 6 8 5 1 0 0 4 9 0 3 0 9 2 9 </code></pre> <p>First, extract the highest valu...
python|pandas|csv
0