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
12,700
42,374,485
Python array using numpy
<p>I am confused about doing vectorization using <code>numpy</code>. </p> <p>In particular, I have a matrix of this form: of type <code>&lt;type 'list'&gt;</code></p> <p><code>[[0.0, 0.0, 0.0, 0.0], [0.02, 0.04, 0.0325, 0.04], [1, 2, 3, 4]]</code></p> <p>How do I make it look like the following using numpy?</p> <pr...
<p>This is not a matrix of type list, it is a list that contains lists. You may think of it as matrix, but to Python it is just a list</p> <pre><code>alist = [[0.0, 0.0, 0.0, 0.0], [0.02, 0.04, 0.0325, 0.04], [1, 2, 3, 4]] arr = np.array(alist) </code></pre> <p>works just the same as</p> <pre><code>arr = np.array(...
python|arrays|numpy|vectorization
2
12,701
69,688,799
passing PIL image to OpenCV causes TypeError: Expected cv::UMat for argument 'src'
<p>I'm trying to apply CLAHE method using OpenCV library to the green channel which has been split, but then this error appears:</p> <pre><code> cl = clahe.apply(multiBands[1]) TypeError: Expected cv::UMat for argument 'src' </code></pre> <p>My code:</p> <pre><code># Example Python Program for contrast stretching fro...
<p>PIL and OpenCV both have different formats of image objects but they can be interchangeable, e.g. OpenCV accepts ndarray and you can change PIL image into array using NumPy. Similarly, you can get PIL image object from numpy array using <code>PIL.Image.fromarray()</code> method. I've modified your code and I think i...
python|numpy|opencv|computer-vision|python-imaging-library
2
12,702
43,138,782
How to iterate over columns in a df and compare value with previous column and perform a action in Python
<p>The operation I am trying to perform is similar to this mysql delete statement :</p> <pre><code> DELETE FROM ABCD WHERE val_2001&gt;val_2000*1.5 OR val_2001&gt;val_1999*POW(1.5,2); </code></pre> <p>And the column_names varies from val_2001 to val_2017.</p> <p>All the data from the table ABCD is dumped into a cs...
<p>This code creates a random DataFrame that fairly closely mimics your DataFrame. It seems one of the key components of your questions was iterating through multiple columns, which this does (via pandas). </p> <p>Build DataFrame:</p> <pre><code>cols = [ 'val_{}'.format(c) for c in range(2000, 2018)] d = {} for c i...
python|mysql|pandas|dataframe|delete-row
2
12,703
43,353,172
Producing spectrogram from microphone
<p>Below I have code that will take input from a microphone, and if the average of the audio block passes a certain threshold it will produce a spectrogram of the audio block (which is 30 ms long). Here is what a generated spectrogram looks like in the middle of normal conversation:</p> <p><a href="https://i.stack.im...
<p>First, observe that your code plots up to 100 spectrograms (if <code>processBlock</code> is called multiple times) on top of each other and you only see the last one. You may want to fix that. Furthermore, I assume you know why you want to work with 30ms audio recordings. Personally, I can't think of a practical app...
python|numpy|audio|matplotlib|scipy
21
12,704
72,191,298
What is the pythonic way of "iterating" over a single item?
<p>I come across this issue often, and I would be surprised if there wasn't some very simple and pythonic one-liner solution to it.</p> <p>Suppose I have a method or a function that takes a list or some other iterable object as an argument. I want for an operation to be performed once for each item in the object.</p> <...
<p>The short answer is nope, there is no simple built-in. And yep, if you want <code>str</code> (or <code>bytes</code> or bytes-like stuff or whatever) to act as a scalar value, it gets uglier. Python expects callers to adhere to the interface contract; if you say you accept sequences, say so, and it's on the caller to...
python|numpy
3
12,705
50,339,261
Selection of activation function
<p>I am making a AutoEncoder on Tensorflow which takes input as a 3 D Matrix whose value lie in the range of [-1,1]. What is the optimal activation function for this scenario?</p> <p>Also, what is the rule of thumb in selecting the activation function w.r.t to the input ranges?</p>
<p>First of all, it is generally advisable to start the network with batch normalization, which would more or less confine the values between -1 and 1 anyway.</p> <p>The activation function of the hidden layers should have non-linearity to be able handle higher levels of complexity. So I'd choose <strong>relu</strong>...
tensorflow|machine-learning|deep-learning|autoencoder
0
12,706
50,485,466
compare multiple columns of pandas dataframe with one column
<p>I have a dataframe: df-</p> <pre><code> A B C D E 0 V 10 5 18 20 1 W 9 18 11 13 2 X 8 7 12 5 3 Y 7 9 7 8 4 Z 6 5 3 90 </code></pre> <p>I want to add a column 'Result' which should return 1 if the value in column 'E' is greater than the values in B, C &amp; D co...
<p>One possible solution is compare in <code>numpy</code> and last convert boolean mask to <code>int</code>s:</p> <pre><code>df['Result'] = (df.iloc[:, 1:4].values &lt; df[['E']].values).all(axis=1).astype(int) print (df) A B C D E Result 0 V 10 5 18 20 1 1 W 9 18 11 13 0 2 X 8 ...
python|pandas|dataframe|compare
9
12,707
50,477,318
Cygwin: import numpy error
<p>I am trying to <code>import numpy</code> in Cygwin. I get the following error message.</p> <p>I have <code>numpy 1.11.2-1</code>, a.k.a. the <code>python2-numpy: Python scientific computing module</code> package, installed through the Cygwin installer. I also have <code>Python 2.7.14-1</code>, a.k.a. the <code>pyth...
<p>Numpy is unable to load the BLAS library, probably as the PATH was redefined to NOT include <code>/usr/lib/lapack</code> or you are not using bash or csh.</p> <pre><code>$ cygcheck -l liblapack0 /etc/profile.d/lapack0.csh /etc/profile.d/lapack0.sh /usr/lib/lapack/cygblas-0.dll /usr/lib/lapack/cyglapack-0.dll </code...
python|numpy|cygwin
2
12,708
45,561,072
Separating similar values from array in python
<p>I have numpy array with values 0,1,2. I want to separate them in different arrays and plot them. How can I do that?</p> <pre><code>for i in range(2): if i==0 z = [i] elif i==1 y = [i] else w = [i] </code></pre> <p>this is what i tried</p>
<p>just use the histogram function from pyplot</p> <pre><code>import numpy as np import matplotlib.pyplot as plt y = np.random.randint(0,3,100) plt.hist(y) plt.show() </code></pre>
python|arrays|numpy
0
12,709
45,467,975
.Split() in for loop not returning list
<p>I wrote a for loop that is supposed take win-loss records of a football team and split them, to get a value for games won and games lost. Unfortunately my split('-') command does not seem to be returning a list when used in the for loop I wrote.</p> <p>The data set was picked up from wikipedia and the data is with...
<p>Change your for loop to split on that actual character</p> <pre><code>for season in year_football['Conference'].values: win_loss = season.split(chr(8211)) # I changed this line wins.append(win_loss[0]) games.append(int(win_loss[0])) + int(win_loss[1])) print(season) print(ty...
python|python-3.x|pandas
4
12,710
62,476,253
How to show seaborn countplot and print dataframe side by side in Python?
<p>I have plotted a seaborn countplot and showing the values of each categorical variables in my code. The code is as follows : </p> <pre><code>sns.countplot("NAME_HOUSING_TYPE",data=applicationDF,hue="TARGET",palette=['g','r']) plt.xticks(rotation=90) plt.legend(labels = ['Repayer','Defaulter']) plt.yscale('log') plt...
<p>I looked at the official references and added a table to the right of the graph through trial and error. The table data could not be quoted from the data frame, so I created it manually. Unfortunately, I couldn't control the font size.</p> <pre><code>import seaborn as sns import matplotlib.pyplot as plt fig = plt.fi...
python|pandas|seaborn
0
12,711
62,590,950
Getting the wrong window back from df.rolling
<p>I'm converting a series of data from 1 minute intervals to 5 minute intervals. To do this I am using the rolling and sum funcitons from pandas then attempting to slice in steps of 5. This makes sense to me, sum everything up, then take the rows that have the information I want, which is every 5th row.</p> <p>However...
<p>If this was me I would take the following approach:</p> <pre><code>tmp_df = df.rolling(window=5).sum() df_5 = tmp_df[(tmp_df.index % 5) == 4] </code></pre> <p><code>df_5</code> will be your desired output</p>
python|pandas|slice
0
12,712
62,558,885
Unpad all-zero rows from the end of an array
<p>I have this line:</p> <pre><code>x = np.zeros((10, 2), int) </code></pre> <p>and a for loop that fills this for the first 6 elements.<br /> Is there a way to remove the remaining 0 elements?</p>
<p>If you want to remove the last all zero rows:</p> <pre><code>x = x[:(np.where(x.any(axis=1))[0]).max()+1] </code></pre> <p>example:</p> <p>x:</p> <pre><code>[[1 2] [0 0] [1 2] [0 0]] </code></pre> <p>output:</p> <pre><code>[[1 2] [0 0] [1 2]] </code></pre>
python|arrays|numpy
2
12,713
62,537,144
Create one df from multiple dfs
<p>I have multiple pd dfs like this:</p> <pre><code>df1 = [nan nan nan 1 nan 2 nan nan nan nan nan nan] df2 = [ 1 nan nan nan nan nan nan nan nan nan nan 4] df3 = [nan nan nan nan 5 nan 3 nan nan nan nan nan] </code></pre> <p>Now I want to create a new df with the ...
<p>You can do a concat:</p> <pre><code>pd.concat([df1,df2,df3]).groupby(level=0).first() </code></pre>
python|pandas|dataframe
0
12,714
54,333,039
How to add NaN for missing data while appending data?
<p>I have a function, like below:</p> <pre><code> def fsheet_DCOP(s,j,k,l): ret=pd.DataFrame([]) j=j[j[3].str.contains(s,na=False)] for i in k: ret=ret.append(j[j[5] == i]) ret=ret[ret[7]==l] ret=ret[:1] return ret </code></pre> <p>Sometimes in the da...
<p>As it became apparent, there is no option or method to check if the value is null at the same time as appending. So, here is my workaround: Before the function returns the ret variable, add check if ret is empty ad fill it with some NaN values.</p> <pre><code>import numpy as np . . . def fsheet_DCOP(...
python|pandas|append|missing-data
1
12,715
54,542,096
pandas: reshape column and row information into separate columns
<p>Using python pandas, I would like to transform the following data (frame)...</p> <pre><code>A1 - A2 - A3 10 - 30 - 50 11 - 31 - 51 12 - 32 - 52 </code></pre> <p>to something like...</p> <pre><code>Ro - Co - Value R1 - A1 - 10 R1 - A2 - 30 R1 - A3 - 50 R2 - A1 - 11 R2 - A2 - 31 R2 - A3 - 51 R3 - A1 - 12 R3 - A2 - ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.melt.html" rel="nofollow noreferrer"><code>.melt</code></a>:</p> <pre><code>df.reset_index().melt(id_vars='index') index variable value 0 0 A1 10 1 1 A1 11 2 2 A1 12 3 0 ...
python|pandas
2
12,716
54,372,352
python pandas - calculate percentage change using last non-na value
<p>I am pretty new to python (mostly I use R) and I would like to perform a simple calculation but keep getting errors and incorrect results. I would like to calculate the percentage change for a column in a pandas df using the latest non-na value. A toy example is below.</p> <pre><code>price = ['Nan', 10, 13, 'NaN',...
<p>I believe what you're looking for is to employ backfill when calling the <code>pct_change</code> function.</p> <p><code>df['price_chg'] = df.price.pct_change(periods = -1, fill_method='backfill')</code></p> <p>This results in:</p> <pre><code>1 -0.230769 2 0.444444 3 0.000000 4 0.000000 5 NaN </...
python|pandas|dataframe
1
12,717
54,619,471
Why changes in Numpy array are not reflecting in two different cases?
<p>I am confused about below two codes:</p> <p>1st code: Changes getting reflected in both array</p> <pre><code> import numpy as nm ab=nm.arange(10) ba=ab ba[0]=99 print(ba) print (ab) </code></pre> <p>Output:</p> <pre><code>ba=[99 1 2 3 4 5 6 7 8 9] ab=[99 1 2 3 4 5 6 7 8 ...
<p>The variable that holds the array actually holds the memory address where the array is located, by doing <code>ba=ab</code> you're setting the same address for both arrays, so if you change one of them the changes will be reflected in the other, but by doing <code>ba=ab-ab</code> you're overwriting this address with...
python|numpy|numpy-ndarray
2
12,718
54,385,268
Vectorizing scipy norm.pdf
<pre><code>def predictDigit(img): prob = [0] * 10 for digit in range(10): for pix in range(len(img)): std = pix_std[digit][pix] mean = pix_means[digit][pix] if std == 0: continue else: prob[digit] += np.log(norm.pdf(img[pi...
<p>norm.pdf is vectorized right out the box!</p> <blockquote> <p>To compute the cdf at a number of points, we can pass a list or a numpy array.</p> <pre><code> norm.cdf([-1., 0, 1]) array([ 0.15865525, 0.5, 0.84134475]) import numpy as np norm.cdf(np.array([-1., 0, 1])) </code></pre> </blockquote> <blockqu...
python|numpy|scipy
0
12,719
73,691,320
Create a column with the keys of a dictionary in python
<p>I have the following dictionary and DataFrame in python:</p> <pre><code>dicti = {'328392': 1, '657728': 2, '913532': 3, '0153G23': 4, '23932Z': 5} </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>color</th> <th>num_ID</th> <th>other</th> </tr> </thead> <tbody> <tr> <td>red</td> ...
<p>You can use <code>map</code>, but with a reverse dictionary:</p> <pre><code>df['number'] = df['num_ID'].map({v:k for k,v in dicti.items()}) </code></pre>
python|pandas|dataframe
1
12,720
73,756,557
Convert a dataframe array item to a dataframe column
<p>I have a dataframe that was filled from a json response. I can flatten the response to be a single row dataframe, but I'm struggling to determine the most efficient way to then map an dataframe object that is an array of numbers to another dataframe column.</p> <p>I can make it work by using a temporary dataframe, ...
<p>I found a single line solution <code>df['%SolarGen']=dfjson.iloc[0,30]</code> where 30 is the column number in the original json dataframe. I guess the next advance is to find the column number by name so I don't have to count them or in case anything changes.</p>
python|json|pandas|dataframe
1
12,721
73,779,154
Does anyone know what to do with this error? TypeError: unhashable type: 'numpy.ndarray'
<p>we got following instructions from our class:</p> <p>It seems, that other people can do it, but there are no other steps mentioned, what did I do wrong?</p> <pre><code>import pandas as pd import numpy as np house1 = pd.read_csv(&quot;House1.csv&quot;) house1.set_index('tstp', drop=True, inplace=True) # replace 'Null...
<p>There are a couple of ways to fix this issue, that have been suggested on the comments already:</p> <h1>Option 1</h1> <p>Specify the <code>x</code>, and <code>y</code> arguments of <code>plt.plot</code>:</p> <pre class="lang-py prettyprint-override"><code>plt.plot(x=house1['SOME_COL'], y=house1['SOME_OTHER_COL'], la...
python|pandas|numpy|matplotlib
0
12,722
72,573,357
Dataframe to dictionary without loosing decimal digits after comma
<p>I try to get a dictionary with values with two digits after comma mainly for 0.0 as 0.00. Any suggestion how I could get that? I tried to iterate throw the dictionary and replace 0.0 for 0.00 but I couldn't solve it</p> <pre><code>import pandas as pd from tkinter import * def create(): data = {'1': [0.99999, 0...
<p>Could you try this please?</p> <pre><code>data = {'A':[0.99999, 0.00000, 1.22222, 0.000000], 'B':[0.99999, 0.00000, 1.22222, 0.000000]} df = pd.DataFrame(data) print(df.dtypes) df.A = df.A.apply(lambda x : '{:.3f}'.format(x)) df.B = df.B.apply(lambda x : '{:.3f}'.format(x)) df1 = df.to_dict() df1 </code></pre> <p...
python|pandas|dataframe|dictionary
1
12,723
72,698,077
Pandas fill dataframe with count of values within a range from another dataframe
<p>I currently have two dataframes, df_ages and df_count:</p> <pre><code>In [1]: df_ages Out [1]: Enrolled Age 1 Y 44 2 Y 35 3 N 37 4 Y 55 5 N 26 6 Y ...
<p>You can try <code>apply</code> on rows with <code>Series.between</code></p> <pre class="lang-py prettyprint-override"><code>df_count['counts'] = df_count.apply(lambda row: df_ages['Age'].between(row['Min'], row['Max']).sum(), axis=1) df_count['percentage'] = df_count['counts'].div(len(df_ages)).mul(100).round(1) </c...
python|pandas|dataframe|range
1
12,724
72,780,539
Loading data from a file and converting into an array in Python
<p>I am trying to load the data from a file. There are 3 rows and columns and I want to convert into an array <code>A</code> with shape <code>(3,3)</code>. How do I go about doing it?</p> <pre><code>import numpy as np np.loadtxt('A.csv')[:, 0] </code></pre> <p>The data looks like</p> <p><a href="https://i.stack.imgur.c...
<p>Following my comment, convert the file to a panda dataframe first to get rid of the empty rows in your dataset. Then convert the resulting dataframe to numpy.</p> <h3>data.csv</h3> <pre><code>0.751900795,0.720029442,0.519947357 0.757660601,0.682370477,0.693973342 0.799340382,0.641430593,0.73287523 </code></pre> <...
python|numpy|csv
0
12,725
72,493,368
Calculating multiple for an input in a stranded time period dataset
<p>Original table (or Dataframe)</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Start</th> <th>End</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2020-09-01</td> <td>2021-12-31</td> </tr> <tr> <td>2</td> <td>2019-07-01</td> <td>2021-07-31</td> </tr> <tr> <td>...</td> <td>...</...
<p>You can try</p> <pre class="lang-py prettyprint-override"><code>start = pd.to_datetime(df['List'], format='%Y') end = start + pd.offsets.YearEnd() df['Days'] = (pd.concat([end-start, end-df['Start'], df['End']-start, df['End']-df['Start']], axis=1).min(axis=1) ...
python|pandas|dataframe|date|days
1
12,726
40,517,328
Implementing logistic regression -- why does this not converge?
<p>I am adapting existing implementations of logistic regression, but I can't figure out what I am doing wrong.</p> <p>Here is my implementation:</p> <pre><code>from scipy.optimize import fmin_bfgs import numpy as np import pandas as pd # With help from http://stackoverflow.com/questions/13794754/logistic-regression-...
<p>The problem is that somehow this line:</p> <pre><code>error = (labels - sigma(features, weights)) </code></pre> <p>Converts <code>error</code> from a 3 x 1 vector into a 3 x 3 matrix. </p> <p>Note that if you print <code>error</code> and run <code>gradient_log_likelihood(weights, features, labels)</code>, you get...
python|numpy|logistic-regression
0
12,727
40,726,490
Overflow Error in Python's numpy.exp function
<p>I want to use <code>numpy.exp</code> like this:</p> <pre><code>cc = np.array([ [0.120,0.34,-1234.1] ]) print 1/(1+np.exp(-cc)) </code></pre> <p>But this gives me error:</p> <pre><code>/usr/local/lib/python2.7/site-packages/ipykernel/__main__.py:5: RuntimeWarning: overflow encountered in exp </code></pre> <p...
<p>As fuglede says, the issue here is that <code>np.float64</code> can't handle a number as large as <code>exp(1234.1)</code>. Try using <code>np.float128</code> instead:</p> <pre><code>&gt;&gt;&gt; cc = np.array([[0.120,0.34,-1234.1]], dtype=np.float128) &gt;&gt;&gt; cc array([[ 0.12, 0.34, -1234.1]], dtype=float128...
python|numpy|scipy
46
12,728
40,546,462
Conditional counting across a row in pandas when matching a string
<p>I have pandas dataframe of the form,df= </p> <pre><code>index,result1,result2,result3 0 s u s 1 u s u 2 s 3 s s u </code></pre> <p>i would like to add another column that contains a list of the number of times s occurs in th...
<p>For me works cast to <code>string</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html" rel="nofollow noreferrer"><code>astype</code></a> numeric and <code>NaN</code> columns return your <code>error</code>:</p> <pre><code>print (df) index result1 result2 result3 ...
python|pandas|count|conditional
2
12,729
40,492,515
Tensorflow Split Using Feed Dict Input Dimension
<p>I'm trying to tf.split a tensor based on the dimension of an input fed in using feed_dict (dimension of input changes with each batch). Currently I keep getting an error saying that a tensor cannot be split with a "Dimension". Is there a way to get the value of the dimension and split using it?</p> <p>Thanks!</p> ...
<p><code>tf.split</code> takes a python integer for the <code>num_split</code> argument. However, <code>document_embedding.get_shape()</code> returns a <code>TensorShape</code>, and <code>document_embedding.get_shape()[1]</code> gives a <code>Dimension</code> instance, hence you get an error says "can't split with a Di...
python|nlp|tensorflow|recurrent-neural-network|word-embedding
0
12,730
40,685,659
Feeding all combinations of x and y array into function f(x,y)
<p>New to python and trying to teach myself the language. I understand the basics from R and SAS however I am still learning how to manipulate arrays and learn basic python in spyder. </p> <p>I would really love your help with feed both x and y into a function f(x,y) (e.g sin(xy) for simplicity). </p> <p>Typically in...
<p>You need to use <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow noreferrer"><code>itertools.product</code></a> in this case. It can be used to generate a list having all possible combinations.</p> <p>For example, if <code>A = [1, 2]</code> and <code>B = [3, 4]</code></p> ...
python|numpy|spyder
1
12,731
40,775,982
PANDAS count consecutive dates in a row from start position
<p>This is an example of the data frame i'm working with:</p> <pre><code> d = {'item_number':['bdsm1000', 'bdsm1000', 'bdsm1000', 'ZZRWB18','ZZRWB18', 'ZZRWB18', 'ZZRWB18', 'ZZHP1427BLK', 'ZZHP1427', 'ZZHP1427', 'ZZHP1427', 'ZZHP1427', 'ZZHP1427', 'ZZHP1427', 'ZZHP1427', 'ZZHP1427', 'ZZHP1427', 'ZZHP1427', 'ZZHP1427',...
<p><strong><em>setup</em></strong><br> fixed your data</p> <pre><code>d = {'item_number':['KIN005','KIN005','KIN005','KIN005','KIN005'], 'Comp_ID':['1395','1395','1395','1395','1395'], 'date':['2016-11-22','2016-11-21','2016-11-20','2016-11-14','2016-11-13']} df = pd.DataFrame(data=d) df.date = pd.to_datetime(df.d...
python|pandas
3
12,732
61,901,013
Python - Pandas Max Range Betwen two Values in a column that is not a max and min of column
<p>I have a challenge that i think is a little bit complex to explain.</p> <p>I have a dataframe below.</p> <p><a href="https://i.stack.imgur.com/OPwmi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OPwmi.jpg" alt="enter image description here"></a></p> <p>Here i need to get the min and max datet...
<p>As @JQadrad replied, <code>.first(), .last()</code> should be used to aggregate and calculate the difference. I didn't understand the formula for 'Max_rage_between_2_times', so I didn't write the code.</p> <pre><code>df = pd.DataFrame({'User':user, 'Time':time}) df['Time'] = pd.to_datetime(df['Time']) first = df.gr...
python|pandas
1
12,733
61,835,494
Access elements of a Tensor
<p>I have the following TensorFlow tensors. </p> <pre><code>tensor1 = tf.constant(np.random.randint(0,255, (2,512,512,1)), dtype='int32') #All elements in range [0,255] tensor2 = tf.constant(np.random.randint(0,255, (2,512,512,1)), dtype='int32') #All elements in range [0,255] tensor3 = tf.keras.backend.flatten(tenso...
<p>I have managed to get something working in Tensorflow v 1.12, but do let me know if it is the expected code:</p> <pre><code>import tensorflow as tf print(tf.__version__) import numpy as np tensor1 = tf.constant(np.random.randint(0,255, (2,512,512,1)), dtype='int32') #All elements in range [0,255] tensor2 = tf.cons...
python|tensorflow|keras|tensor|array-broadcasting
2
12,734
57,746,090
how to map original value instead of True and False in python
<p>i am trying to get all the value which contain (/) in another column which doesn't contain (/) should be marked zero</p> <p>i tried this </p> <pre><code> splits2 = df.COLUMN_2.str.contains('/') </code></pre> <p>but it just find true and false value. can i map true value with original value present in column_2<...
<p>You can try this:</p> <pre><code>splits2 = df.COLUMN_2.where(df.COLUMN_2.str.contains('/')) </code></pre>
python|pandas
2
12,735
57,944,012
How to write a fast code in C++ compared to numpy.logspace() function?
<p>This is the code in Python that generates log-spaces values at a very quick time:</p> <pre><code>import numpy print(numpy.logspace(0,1,num=10000000)) </code></pre> <p>My try to simulate its output in C++, is the following:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; #include &lt;vector&gt; std...
<p>Interesting question! My answer has the different versions of the functions at the top. Below is only the benchmarking code. Use google-benchmark as the library.</p> <ul> <li>My intermediate result can also be found here: <a href="http://quick-bench.com/Hs39BWQf5kr5Gjnv6zQkLXMrsDw" rel="nofollow noreferrer">1</a> Q...
python|c++|numpy
3
12,736
57,978,812
Compare a value from one dataframe column to values in the other columns from the same df?
<p>Not a native english speaker, I have got a df. Lets say in df 'a' column get 'apple' compare to other 'apple' in c column and make a combined df. </p> <p>Compare value(apple) from column 'a' and compare it with the same value (apple) in 'c' column and make a combined df</p> <p>df</p> <pre><code> ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer">boolean indexing</a>:</p> <pre><code>resultant_df=df[df[['a','c']].eq('apple').any(axis=1)] resultant_df.reset_index(drop=True,inplace=True) print(resultant_df) a b ...
python|pandas
1
12,737
58,161,255
Error in Python Pandas when Reading CSV File
<p>I am trying to read a CSV File, but its throwing an error. I am not able to understand whats the problem with my syntax or do I need to add more attributes to my read_csv.</p> <p>I tried the solution on </p> <blockquote> <p>UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 21: invalid start ...
<p>if your csv file not suit then you can get this error. You should try another dataset.</p>
python-3.x|pandas
0
12,738
57,847,716
How to select rows that have missing values in columns depending on conditions for dataframes?
<p>I have a dataframe extracted from excel sheet.</p> <p>I am looking for NOT legit rows.</p> <p>A legit row is such that it meets ANY of the following conditions:</p> <ol> <li>exactly 1 column filled in but the other columns are empty or null</li> <li>exactly 2 columns are filled in but the other columns are empty ...
<p>If you already have populated your dataframe then you can do it like this</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd ## Generate Random Data raw_data=np.random.choice([None,1], (50,8)) raw_data= np.r_[raw_data, np.random.choice([None, 1,2,3], (50,8))] ## Create data...
pandas
0
12,739
34,208,273
Concat values from columns depends on particular condition
<p>I have a following dataframe:</p> <pre><code># EPISODE PROGRAM TITLE IS_EPIS IS_MOVIE IS_SHOW 1 E_N1 P_N1 T1 1 0 0 2 E_N2 P_N2 T2 0 0 1 3 E_N3 P_N3 T3 0 1 0 </code></pre> <p>I am trying to get new column as:</p> <pre><code>#...
<p>You can use <code>loc</code>:</p> <pre><code>df.loc[df.IS_MOVIE == 1 ,'title'] = df.PROGRAM df.loc[df.IS_SHOW == 1, 'title'] = df.TITLE df.loc[df.IS_EPIS == 1, 'episode_title'] = df.EPISODE print df EPISODE PROGRAM TITLE IS_EPIS IS_MOVIE IS_SHOW title episode_title # ...
python|python-2.7|python-3.x|pandas|dataframe
2
12,740
34,093,917
how to convert mongoDB document into python?
<p>I have a mongoDB document which I want to convert it in pandas dataframe</p> <pre><code> db.dataset2.insert( { "user_id" : "user_3", "order_id" : "order_3", "order_lat " : -73.9557413, ## Order location "order_long" : 40.7720266, "order_time" : datetime.utcnow(), "dish" : [ ...
<p>You can just create a temporary <code>DataFrame</code> from the records in <code>df.dish</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#joining-on-index" rel="nofollow">join it</a> back to original <code>df</code>.</p> <p>Like this:</p> <pre><code>df = pd.DataFrame(list(db.dataset2.fi...
python|mongodb|pandas|pymongo
0
12,741
34,152,325
Is there a way to add multiple elements in one line to a python set?
<p>I am iterating over a pandas dataframe and would like to add unique elements to a set from multiple columns of the dataframe. Currently I do it like this:</p> <pre><code>list_a = set([]) for i, row in df.iterrows(): list_a.add(row.a) list_a.add(row.b) </code></pre> <p>I tried this:</p> <pre><code>list_a =...
<p>You can use the union functionality - <code>list_a = list_a.union([row.a, row.b])</code></p> <p>See more on the python sets documentation - <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">https://docs.python.org/2/library/sets.html</a></p>
python|pandas|set
1
12,742
55,122,680
Shuffle part of array in numpy
<p>I have a numpy array, and I would like to shuffle parts of it. For example, with the following array:</p> <pre><code>import numpy as np import random a = np.arange(15) # =&gt; array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) </code></pre> <p>I want to do:</p> <pre><code>shuffle_parts(a, [(0, 3...
<p>It can be done directly:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import random &gt;&gt;&gt; a = np.arange(15) &gt;&gt;&gt; s=3 &gt;&gt;&gt; f=7 &gt;&gt;&gt; random.shuffle(a[s:f]) &gt;&gt;&gt; a array([ 0, 1, 2, 5, 4, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14]) </code></pre> <p>Indexing direct...
python|arrays|numpy|shuffle
3
12,743
54,796,983
What to assign to a variable to act like ":" in pandas dataframe .loc method?
<p>I'm trying to create a function that takes in list and results a subsetted index. If there is no index provided I want it to give me back the entire index.</p> <p>I thought that <code>None</code> works for this in <code>pandas</code> but apparently not... I'm using <code>pandas '0.23.4'</code></p> <p><strong>Is th...
<p>Use <code>slice(None)</code>:</p> <pre><code>df sepal_length sepal_width petal_length petal_width iris_0 x x x x iris_1 x x x x iris_2 x x x x iris_3 x x ...
python|pandas|dataframe|slice
1
12,744
54,809,890
Pandas df error - "The truth value of a Series is ambiguous." in if else loop
<p>I have a pandas df with a column called <em>group</em> consisting of three values which are 1,2 and 3.</p> <p>I am trying to do the following if else statement:</p> <pre><code>if df.group == 1: (code here) elif df.group ==2: (code here) else: (code here) </code></pre> <p>When I try to run my if else loop...
<p>You can iterate like this:</p> <pre><code>for idx, val in enumerate(df.itertuples()): if df.loc[idx, 'group'] == 1: print('1') elif df.loc[idx, 'group'] ==2: print('2') else: print('3') </code></pre> <hr> <p>Using <code>np.where</code> refer <a href="https://stackoverflow.com/a/54...
python|pandas
3
12,745
49,632,641
Pandas parsing csv error - expected 1 fields found 9
<p>I'm trying to parse from a .csv file:</p> <pre><code>planets = pd.read_csv("planets.csv", sep=',') </code></pre> <p>But I always end up with this error:</p> <pre><code>ParserError: Error tokenizing data. C error: Expected 1 fields in line 13, saw 9 </code></pre> <p>This is how the first few lines of my csv file ...
<p>The function <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="noreferrer"><code>pandas.read_csv()</code></a> gets the number of columns and their names from the first line. By default it does not consider the option of the first lines being comments. </p> <p>What is happeni...
python|python-3.x|pandas|csv|data-analysis
5
12,746
28,210,757
Select subset of Data Frame rows based on a list in Pandas
<p>I have a data frame <code>df1</code> and list <code>x</code>:</p> <pre><code>In [22] : import pandas as pd In [23]: df1 = pd.DataFrame({'C': range(5), "B":range(10,20,2), "A":list('abcde')}) In [24]: df1 Out[24]: A B C 0 a 10 0 1 b 12 1 2 c 14 2 3 d 16 3 4 e 18 4 In [25]: x = ["b","c","g","h",...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html#pandas.Series.isin" rel="noreferrer"><code>isin</code></a> to return a boolean index for you to index into your df:</p> <pre><code>In [152]: df1[df1['A'].isin(x)] Out[152]: A B C 1 b 12 1 2 c 14 2 </code></pre> ...
python|pandas
10
12,747
27,969,432
Efficient insertion of row into sorted DataFrame
<p>My problem requires the incremental addition of rows into a sorted <code>DataFrame</code> (with a <code>DateTimeIndex</code>), but I'm currently unable to find an efficient way to do this. There doesn't seem to be any concept of an "insort".</p> <p>I've tried appending the row and resorting in place, and I've also ...
<p><code>pandas</code> is built on <code>numpy</code>. numpy arrays are fixed sized objects. While there are numpy append and insert functions, in practice they construct new arrays from the old and new data.</p> <p>There are 2 practical approaches to incrementally defining these arrays:</p> <ul> <li><p>initialize ...
python|numpy|pandas
3
12,748
28,362,355
OpenCV: What is the dimension of the array representing a BGR image?
<p>According to <a href="https://docs.opencv.org/2.4/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html#how-the-image-matrix-is-stored-in-the-memory" rel="nofollow noreferrer">documentation</a>, a BGR image is represented this way in OpenCV:</p> <p><a href="https://i.stack.imgur.com/buuZr.png" rel="nofollo...
<p>From <a href="http://docs.opencv.org/trunk/doc/py_tutorials/py_core/py_basic_ops/py_basic_ops.html#accessing-image-properties" rel="nofollow">the docs</a></p> <p>Image properties include number of rows, columns and channels, type of image data, number of pixels etc.</p> <p>Shape of image is accessed by img.shape. ...
python|arrays|opencv|numpy|multidimensional-array
1
12,749
73,510,699
How to fill nan value in pandas dataframe from value in another column and above row?
<p>I have df as follows:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({&quot;A&quot;:[0,np.nan,0,0,np.nan,1,np.nan,1,0,np.nan], &quot;B&quot;:[0,1,0,0,1,1,1,0,0,0]}) </code></pre> <p>Now, I need to replace nan values in column A with values from column B and one above row. fo...
<pre class="lang-py prettyprint-override"><code>df['A'] = df['A'].fillna(df['B'].shift()) A B 0 0.0 0 1 0.0 1 2 0.0 0 3 0.0 0 4 0.0 1 5 1.0 1 6 1.0 1 7 1.0 0 8 0.0 0 9 0.0 0 </code></pre>
python|pandas|dataframe|nan|fillna
1
12,750
73,186,044
How would I turn this for loop output into a Pandas dataframe?
<p>I have this code and I am having trouble figuring out how to put the for loop output into a dataframe. How could I take the for loop data and put it into a Pandas DataFrame?</p> <p>Rows look like ('tag', 34)</p> <pre><code>select_stmt = select(Tag.tag, func.count('Tag.tag').label('CCount')).group_by(Tag.tag) with Se...
<p>I solved this by turning data into a dict since I only have two columns. Note this gives you a column for each pair and not a row. You can fix that with <code>dd.transpose()</code>.</p> <pre><code>select_stmt = select(Tag.tag, func.count('Tag.tag').label('CCount')).group_by(Tag.tag) with Session(config.connect()) as...
python|pandas|sqlalchemy
1
12,751
35,297,771
WRF netcdf file - subset smaller array out of dataset based on coordinate boundaries in python
<p>I have two netcdf files from WRF runs, one with hourly data and the other smaller file has the coordinates (XLAT and XLONG). I am trying to retrieve a subset of the data based on certain coordinates. </p> <p>An example of one of the variables is temperature 'T2' which has the dimensions (1,1015,1359) being the (t...
<p>I see an obvious problem with <code>lat_inds</code> as it has max shape <code>1015*1359</code>, but You try to use it as an index for latitude, which has size <code>1015</code>. So IMO You should first find similar values for <code>lat_inds</code> and <code>lon_inds</code>, points which satisfy both lon and lat limi...
python|arrays|numpy|netcdf|weather
1
12,752
35,152,181
Unable to import pandas in ipython notebook even after installing correctly on MAC OSX El Capitan
<p>I have installed pandas through conda install pandas and still receiving this error while importing the pandas library through ipython jupyter notebook. </p> <p>I have also tried to check the version mismatch through </p> <pre><code>print ('version:' + np.__version__) </code></pre> <p>and have traced the path to ...
<p>Try adding the following parameters to your <code>~/.bash_profile</code> (by typing the below into <code>terminal</code>):</p> <pre><code>export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 </code></pre>
python|macos|numpy|pandas|scipy
1
12,753
34,978,694
How can I format this array of arrays into a pandas data frame?
<p><a href="http://cryptocoincharts.info/fast/period.php?pair=ETH-USDT&amp;market=poloniex&amp;time=alltime&amp;resolution=1d" rel="nofollow">Here is the data</a> </p> <p>Originally I was using openpyxl and the .split() method to separate the arrays of data. This still leaves some formatting, but most of all I would r...
<p>There are several ways. Based on the format of the text to which you linked, here is the one I think is easiest:</p> <pre><code># Import the JSON parser import json # and pandas import pandas as pd # Assuming the data is in stuff.txt data = json.load(open('stuff.txt')) pd.DataFrame(data) </code></pre>
python|csv|pandas
1
12,754
35,112,601
Scipy: speed up integration when doing it for the whole surface?
<p>I have a <strong>probability density function (pdf)</strong> <code>f(x,y)</code>. And to get its <strong>cumulative distribution function (cdf)</strong><code>F(x,y)</code> at point (x,y), you need to integrate the <code>f(x,y)</code>, like this: <a href="https://i.stack.imgur.com/KbcQu.png" rel="nofollow noreferrer"...
<p>In the end, this is what I've done:</p> <p>F is cdf, f is pdf</p> <p>F(5,5) = F(5,4) + F(4,5) - 2 *F(4,4) + f(5,5)</p> <p>And loop through the whole surface, you can get the result.</p> <p>The code would look like this:</p> <pre><code>def cdf_from_pdf(pdf): if not isinstance(pdf[0], np.ndarray): ori...
python|numpy|recursion|scipy
0
12,755
30,786,284
Python Pandas not reading DataFrame
<p>I am trying to read in a csv file into a pandas dataframe and then set the column to the specified columns in columns=[ ... ]</p> <p>Would anyone now why its not reading in all of my data? p</p> <pre><code>fp = '/Users/USERNAME/Development/file.csv' file1 = open(fp, 'rb').read() reader = pd.DataFrame.from_csv(fp, ...
<p>Here is a version to load only certain colunns. set <code>usecols</code>in <code>pd.read_csv()</code>.</p> <pre><code>import pandas as pd fp = '/Users/USERNAME/Development/file.csv' usecols = ['VIN', 'Reg City','First Name','Last Name','MGVW','Nat Flt Ind','MGVW', 'Reg Name','Phone...
python|pandas
1
12,756
31,038,890
How to construct a new numpy array from a set of existing arrays?
<p>I have 12 numpy arrays, 5 of size (3, 121) and 7 of size (3, 120), ordered 0-11; call them a0, a1, ..., a11. I would like to construct a single new array built specifically in the following way:</p> <pre><code>newArray = [a0_00, a1_00, a2_00, ..., a11_00, a0_01, a1_01, ..., a11_01, a0_02...] </code></pre> <p>that ...
<p>You basically have a jagged array that is 12 x 3 x (120 or 121). If the last column of the a05 through a11 were filled this would be a bit easier. Instead, you can iterate through the columns from 0 to 120; and iterate through the arrays; and add the column to the new array only if it exists. </p> <p>Here is som...
python|arrays|loops|numpy|indexing
0
12,757
67,431,105
during filtering of a pandas dataframe: ValueError: Buffer has wrong number of dimensions (expected 1, got 2)
<p>I can't get a hold of what is going wrong here.</p> <pre><code>d = {'x' : [1,4,6,9], 'y' : [1,4,6,8]} df = pd.DataFrame(d) #filter columns based on value in specific row df_VIP = df.iloc[:,df.iloc[1:2,:]&lt;3] </code></pre> <p>I get the error. An this also happens with my real dataframe...</p> <blockquote> <p>...
<p>If possible, select by one row, e.g. second by <code>1</code> with convert to numpy array, because used <code>iloc</code>:</p> <pre><code>d = {'x' : [1,4,6,9], 'y' : [1,2,6,8]} df = pd.DataFrame(d) df_VIP = df.iloc[:,df.iloc[1,:].to_numpy()&lt;3] print (df_VIP) y 0 1 1 2 2 6 3 8 </code></pre> <p>If use ...
python-3.x|pandas|valueerror
1
12,758
67,572,655
Nested dictionary to pandas
<p>I'm struggling to get my nested dictionary (that's created by a for-loop) into pandas.</p> <pre><code>list_of_instruments = [&quot;Gold&quot;, &quot;Nasdaq&quot;, &quot;Dow Jones&quot;, &quot;SP500&quot;] instruments = {} for instrument in list_of_instruments: instruments[instrument] = {'ig_name': &quot;&quot;, ...
<p>The <em>first column</em> as you said, idn't one, it's the <code>index</code>, you can name it, or set the index to a numeric one, and your instrument names becomes a real column like the others</p> <ul> <li><p>set index name</p> <pre><code>df = pd.DataFrame(instruments).T df.index.name = 'instrument' ig...
python|pandas
1
12,759
59,914,010
Predictions of Autoencoder are all NaNs because of using custom loss function
<p>I am building an Autoencoder for gene expression data. Some genes are not expressed and have NaN in the input. My output (prediction) is all NaN. Here is my loss function:</p> <pre><code>def nan_mse(y_actual, y_predicted): per_instance = tf.where(tf.is_nan(y_actual), tf.zeros_like(y_actual), tf.square(t...
<p>x=pd.read_csv(&quot;C:/Users/10.csv&quot;,index_col=False).groupby(['Column_name_optional']).mean().reset_index()</p> <p>x = x.replace(np.nan, 0)</p> <h1>this will replace all NaN with Zeros</h1>
python|tensorflow|keras|autoencoder|loss-function
-1
12,760
65,404,671
What does calling self within a class do?
<p>I noticed in the documentation for Pytorch Lightning, it was mentioned you can call the forward method from another method in the same class just by calling <code>self(x)</code>. I haven't been able to find any info about how this works. I always thought you would call the method using <code>self.forward</code></p> ...
<p>Generally speaking, in python, when &quot;calling&quot; an object, you are invoking its <code>__call__</code> method. That is,</p> <pre class="lang-py prettyprint-override"><code> self(x) </code></pre> <p>is equivalent to</p> <pre class="lang-py prettyprint-override"><code> self.__call__(x) </code></pre> <p>For py...
python|pytorch|pytorch-lightning
4
12,761
65,425,954
How to add trailing zeroes to floating point value and export to excel as float(number)?
<p>I had read a file from excel and read as pandas dataframe.</p> <p>I have to make few transformation in floating data type values.</p> <p>I want to add trailing zeroes or change decimal places of the values. For example: 25 to 25.0000 23.3 to 23.3000 24.55 to 24.5500</p> <p>I have tried changing the values to str and...
<pre><code>import pandas as pd s = pd.Series([25, 23.3, 24.55]) s.map('{:.4f}'.format) Out[1]: 0 25.0000 1 23.3000 2 24.5500 dtype: object </code></pre>
python|excel|pandas|dataframe|numpy
1
12,762
50,212,175
How can i check similarity between the rows in a dataframe and add a column as a counter and inc. it when the rows matches?
<p>Somewhat new to python (Pandas), Please help me resolve this</p> <p>This is how my dataframe looks like:- Device_id is the id of a device which is showing a (Msg) at Time (1524724677), The time is in epoch.</p> <pre><code> Device_Id Msg Time 0 ABC123 connected 1524724677 1 ABC123 ...
<p>You can use groupby and <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Grouper.html" rel="nofollow noreferrer"><code>grouper</code></a> function to solve this problem easily:</p> <pre><code># convert time df['Time'] = pd.to_datetime(df['Time'], unit='s') # get output df['count'] = df.groupb...
python|pandas|dataframe|machine-learning
1
12,763
50,201,244
Dot product broadcasting on a 3D grid with numpy
<p>I am trying to get a clue on how to do broadcast a systematic dot product operation on a 10x10x10 3D grid. I formulated the following arrays:</p> <pre><code>A.shape=(5,5,10,10,10) b.shape=(5,10,10,10) </code></pre> <p>I want to obtain an array like the following</p> <pre><code>c.shape=(5,10,10,10) </code></pre> ...
<p>We need to keep the last four axes aligned and have those in the output as well except the second axis (axis=1), which is to be sum-reduced. For such a case <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>np.einsum</code></a> is the way to go, a...
python|numpy|3d|array-broadcasting
3
12,764
49,999,636
Create grouped/stacked bar plots from multiple categories containing several labels inside a pandas dataframe
<p>I have the following <code>pandas</code> dataframe (<code>df</code>) [<em>only an excerpt of the full dataframe</em>]:</p> <pre><code> Name Cat_1 Cat_2 0 foo P Apples, Pears, Cats 1 bar R, M Apples 2 bla E Pears 3 blu F Cats, Pears 4 boo G Apples, Pea...
<p>This should get you pretty close if I understand correctly.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame(columns=['Name', 'Cat_1', 'Cat_2']) df['Name'] = ['foo', 'bar', 'bla', 'blu', 'boo', 'faa'] df['Cat_1'] = ['P', 'R, M', 'E', 'F', 'G', 'P, E'] df['Cat...
python|pandas|dataframe|plot
1
12,765
49,881,468
Efficient way of computing the cross products between two sets of vectors numpy
<p>I have two sets of 2000 3D vectors each, and I need to compute the cross product between each possible pair. I currently do it like this</p> <pre><code>for tx in tangents_x: for ty in tangents_y: cross = np.cross(tx, ty) (... do something with the cross variable...) </code></pre> <p>This work...
<p>Like many numpy functions <code>cross</code> supports broadcasting, therefore you can simply do:</p> <pre><code>np.cross(tangents_x[:, None, :], tangents_y) </code></pre> <p>or - more verbose but maybe easier to read</p> <pre><code>np.cross(tangents_x[:, None, :], tangents_y[None, :, :]) </code></pre> <p>This re...
python|numpy
6
12,766
63,899,753
Calculating the distance between two points using pandas and geopy
<p>I have a pandas dataframe like below including four columns but two points(lat1,lon1) and (lat2,lon2) per row:</p> <pre><code> lat1 lon1 lat2 lon2 ========= ========= ========= ========= 30.172705 31.126725 30.188281 31.132326 30.272805 31.226725 30.288281 31.232326 30.37290...
<p>Even if you not seem to have done any research yourself here you go: Short googling yielded: <a href="https://geopy.readthedocs.io/en/stable/#module-geopy.distance" rel="nofollow noreferrer">https://geopy.readthedocs.io/en/stable/#module-geopy.distance</a></p> <p>With the hands on that you can now find out relativel...
python|pandas|distance|geopy
1
12,767
63,802,911
Element-wise product of dataframe and a series alongwith rolling sum within the group
<p>I have a big dataframe <code>df</code> of len <code>n</code> (<code>n</code> ~ 2 million rows) with columns <code>name</code> and <code>qty</code> and series <code>wt</code> of size <code>m</code>(<code>m</code> ~ 70). Within each group as defined by values in column <code>name</code>, I want to multiply <code>qty<...
<p>Here it goes, it's done in <a href="/questions/tagged/python-3.x" class="post-tag" title="show questions tagged &#39;python-3.x&#39;" rel="tag">python-3.x</a>, I hope it will not be a problem. It's a little bit tedious, but I will try to explain:</p> <ul> <li><p>First we create a variable <code>&quot;indicator&quot;...
python-2.7|dataframe|pandas-groupby|rolling-computation
1
12,768
63,773,087
In pandas, how do you make a correlation matrix between 3 separate dataframes with matching rows and columns?
<p>Each dataframe has a row index of gene name and column index of cell line, with expression levels filling each cell. The 3 dataframes have identical corresponding gene names and cell lines, and I want to find correlation between just the triplets of corresponding rows (i.e. how cell lines affect expression for each ...
<p>If I understand correctly you can do the following:</p> <pre><code>DATAFRAME1 = pd.DataFrame({&quot;GENENAME&quot;:['GENE1','GENE2','GENE3','GENE4','GENE5'],&quot;CELLLINE1&quot;:[34,12,78,84,26], &quot;CELLLINE2&quot;:[54,87,35,25,82], &quot;CELLLINE3&quot;:[56,78,0,14,13], &quot;CELLLINE4&quot;:[0,23,72,56,14], &q...
pandas|dataframe|seaborn|correlation
1
12,769
46,724,228
Is the sum behavior in pandas expected?
<p><strong>EDIT2</strong> I checked it in python2.7 and python3.6, with the same result.</p> <p>Add a more copy-paste friendly version:</p> <pre><code>In [1]: import pandas as pd In [2]: from io import StringIO In [3]: csv = u""" ...: Index,SH600000,SZ002222 ...: 0,2145799.0,282838.0 ...: 1,2104693.0,70510...
<p>I guess you have some variables over-written as the same dataset gives me right result.</p> <pre><code>import pandas as pd import datetime val1 = [(datetime.datetime(2013, 8, 9, 9, 35), 2145799., 282838.), (datetime.datetime(2013, 8, 9, 9, 40), 2104693., 705100.), (datetime.datetime(2013, 8, 9, 9...
python|pandas|floating-point
1
12,770
32,737,710
How create dataframe with
<p>I have dataframe with three columns date1, date2 and some_float; I need to create dataframe with two columns: date_subtract(date1-date2) and some_int. Question is how to convert date (1.7.2015 17:26:23) into number of the day in year (188)?</p> <p>My code:</p> <pre><code> date1 date2 s...
<p>If you haven't already, convert your columns representing dates to datetimes.</p> <pre><code>In [12]: df['date1'] = pd.to_datetime(df['date1'], dayfirst=True) In [13]: df['date2'] = pd.to_datetime(df['date2'], dayfirst=True) </code></pre> <p>Then you can subtract the two columns directly to get a <a href="http://...
python|pandas
0
12,771
38,546,275
Dividing data-frame columns and getting ZeroDivisionError: float division by zero
<p>I have a data frame <code>dayData</code> which includes the columns the following columns <code>'ratio'</code> and <code>'first_power'</code> with the following types:</p> <pre><code>Name: ratio, dtype: float64 first power Name: first_power, dtype: object average power ratio average_power 0 5 8...
<p>You can initially set all values to zero, then create a mask locating all rows with a valid denominator, i.e. where <code>power</code> is greater than zero (<code>gt(0)</code>). Finally, use the mask together with <code>loc</code> to calculate <code>second_step_power</code>.</p> <pre><code>df['second_step_power'] ...
python|pandas
4
12,772
62,915,854
Python Pandas - Select multiple rows if the ID is the same and one of the rows is equal to a number
<p>I am trying to solve the issue of getting all the rows if an ID has a score equal to 1.0 and has more than one row in the database.</p> <p>Dataframe:</p> <pre><code>INDEX ORG_ID Score 1 5467 1.0 2 5467 .897 3 5467 .50 4 8979 1.0 </code></pre> <p>Expected Outcome:</p> <pre><code>INDE...
<p>To get the desired output, you can use the following syntax</p> <pre><code>&gt;&gt;&gt; df[df.ORG_ID.isin(df.ORG_ID.value_counts()[df.ORG_ID.value_counts() &gt; 1].keys())] ORG_ID Score 0 5467 1.000 1 5467 0.897 2 5467 0.500 </code></pre> <p>But the example you gave doesn't have any instances of mul...
python|pandas
0
12,773
63,235,786
How to give file or image to model.predict as a parameter in a Keras model?
<p>I've watched a tutorial about image recognition in Python, and used written code for training a network. It compiles and learning fine, but how to use it for prediction on new images? Maybe something like: <code>model.predict(y)</code>?</p> <p>Here is the code:</p> <pre><code>import numpy from keras.datasets import ...
<p><em>Note: if you are using <code>keras</code> package instead of <code>tf.keras</code>, replace <code>tf.keras</code> with <code>keras</code> in all the following code snippets.</em></p> <hr /> <p>To load a single image, you can use <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/loa...
python|tensorflow|machine-learning|keras|classification
3
12,774
31,995,109
4 x 4 Floats to numpy Matrix
<p>Following numpy command: </p> <pre><code>c = np.matrix('1,0,0,0;0,1,0,0;0,0,1,0;-6.6,1.0,-2.8, 1.0') </code></pre> <p>creates a matrix Outupt:</p> <pre><code>[[ 1. 0. 0. 0. ] [ 0. 1. 0. 0. ] [ 0. 0. 1. 0. ] [-6.6 1. -2.8 1. ]] </code></pre> <p>However my Input is a comma-separated array o...
<pre><code>np.array([1.0, 0.0,..., -2.81542864114781, 1.0]).reshape((4, 4)) </code></pre>
python|arrays|numpy
1
12,775
41,592,537
Tensorflow multiplication broadcasting within batches
<p>We know that tf.multiply can broadcast like this:</p> <pre><code>import tensorflow as tf import numpy as np a = tf.Variable(np.arange(12).reshape(3, 4)) b = tf.Variable(np.arange(4)) sess = tf.InteractiveSession() sess.run(tf.global_variables_initializer()) sess.run(tf.multiply(a, b)) </code></pre> <p>This will gi...
<p>Broadcasting first adds singleton dimensions to the left until rank is matched. In first case that adds batch dimension. But in second case you already have batch dimension so you need to insert singleton dimension manually in the second position:</p> <pre><code>a = tf.reshape(tf.range(24), (2, 3, 4)) b = tf.reshap...
tensorflow
2
12,776
41,618,224
How to search all data frame rows for values outside a defined range of numbers?
<p>So I have a data frame that's 50 columns and 400 rows consisting of all numbers. I'm trying to display only the columns that have values that fall outside a pre-defined range (i.e. only show values that aren't between -1 to +3). </p> <p>So far I have: </p> <pre><code>df[(df.T &gt; 3).all()] </code></pre> <p>to d...
<p>you can use <code>pd.DataFrame.mask</code></p> <pre><code>np.random.seed([3,1415]) df = pd.DataFrame(np.random.randint(-2, 4, (5, 3)), columns=list('abc')) print(df) a b c 0 -2 1 0 1 1 0 0 2 3 1 3 3 0 1 -2 4 0 -2 -2 </code></pre> <p>Mask makes cells that evaluate to <code>True</code> <code>NaN</co...
python|pandas|dataframe
4
12,777
41,584,312
TensorFlow: Specify number of Ops run in parallel
<p>As I understand, TF invokes multiple operators in parallel as long as they are independent. (<a href="https://stackoverflow.com/q/40008117/582967">link</a>)</p> <p>And the parallelism can be controlled by <code>inter_op_parallelism_threads</code> and <code>intra_op_parallelism_threads</code> if operators ar e runni...
<p>Here's a way to profile execution that avoids common pitfalls:</p> <pre><code># Turn off graph-rewriting optimizations config = tf.ConfigProto(graph_options=tf.GraphOptions(optimizer_options=tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L0))) # throw error if explicit device placement can't be satisfied config...
tensorflow
2
12,778
27,851,051
Python numpy array indexing. How is this working?
<p>I came across this python code (which works) and to me it seems amazing. However, I am unable to figure out what this code is doing. To replicate it, I sort of wrote a test code:</p> <pre><code>import numpy as np # Create a random array which represent the 6 unique coeff. # of a symmetric 3x3 matrix x = np.random...
<p>From the advanced indexing documentation - bi rico's link.</p> <blockquote> <p>Example</p> <p>SupposeΒ x.shapeΒ is (10,20,30) andΒ indΒ is a (2,3,4)-shaped indexingΒ intpΒ array, thenresultΒ =Β x[...,ind,:]Β has shape (10,2,3,4,30) because the (20,)-shaped subspace has been replaced with a (2,3,4)-shaped broadcasted indexing...
python|numpy|matrix-indexing
1
12,779
61,408,304
Make few values onto a different column in Pandas
<p>I have a week level data which i would like make into a column. This is the input <a href="https://i.stack.imgur.com/rZVWG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rZVWG.png" alt="enter image description here"></a></p> <p>Here is how i want the output to look like: <a href="https://i.stack...
<p>You can use modulo and integer division for extract <code>year</code>s and <code>week</code>, create MultiIndex by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> and last reshape by <a href="http://pan...
python|pandas|pivot
5
12,780
61,352,886
combine year and quarter into DateTime using Pandas
<p>My data consists of<br> <code>Year</code> and <code>Quarter</code>. I would like to make it into the DateTime index. such as YYY-MM-DD. thanks</p>
<p>Data</p> <pre><code>df=pd.DataFrame({'q':['2020-Q1', '2030-Q3']}) df </code></pre> <p>Coerce to datetime</p> <pre><code>df['q']=pd.to_datetime(df['q']) df </code></pre>
pandas|time-series
0
12,781
61,567,766
How to input an array of n items and output an array of size k in a neural network using keras?
<p>I am new to machine learning and using neural networks with keras. I am trying to use reinforcement learning along with the help of a neural network, which may eventually predict the correct actions for a robot to take in a monopoly game, if it were to play against humans. </p> <p>For this I am trying to use a neur...
<p>I quite not so familiar with keras, but in pytorch everything is expected to work in batches, and that's why you're getting more dimensions than you want.</p> <p>The input for your first linear layer should has dimensions <code>(batch_size,23)</code>. If you want to see how a single example runs throgh the network ...
python|tensorflow
0
12,782
61,599,963
Split dates to create various time series
<p>I have some dates like this: </p> <blockquote> <p>2015-02-02 14:19:00 </p> </blockquote> <p>I have 20000 records and 14 different days, i would like to split the dataset into 14 different part to have 14 different time series, one every day.</p> <p><a href="https://i.stack.imgur.com/cTBt1.png" rel="nofollow n...
<p>IIUC</p> <pre><code># sample data df = pd.DataFrame(pd.date_range('2020-01-01', '2020-01-14', freq='5T'), columns=['date']) # list comprehension to spit groups into separate frames dfs = [g for _,g in df.groupby(df['date'].dt.date)] </code></pre> <p>or you can use dict comprehension if you want the key to be the d...
python|pandas|split|time-series
0
12,783
61,281,163
Compare two dataframes and returns difference based on the first df
<p>I have two sample dfs as below:</p> <pre><code>df1 Name DOB 0 AMY 20100101 1 AMANDA 19990213 2 LEO 19920103 3 RIO 20200109 4 JEFF 20050314 df2 Name DOB 0 AMY 20100101 1 LEO 19920103 2 SEAN 19971123 3 BEN 20170119 4 SAM 20020615 5 YI 199302...
<p>This is also known as an "anti-join".</p> <pre class="lang-py prettyprint-override"><code>(pd.merge(df1, df2[['Name']], on='Name', how='left', indicator=True) .loc[lambda df: df['_merge'] == 'left_only'] .drop(columns='_merge')) # Name DOB # 1 AMANDA 19990213 # 3 RIO 20200109 # 4 JEFF ...
python-3.x|pandas
0
12,784
68,716,867
How to set a value from a column to another value from another column using Python
<p>I am currently working on a simple project where I am trying to have two sets of column each containing a certain amount of integer numbers. Ex. A column - [ 1, 2, 3, 4] and B column - [.1,.2,.3,.4]. What I am trying to accomplish is,</p> <ul> <li>Convert all the integer from column A to string ex. [str(num)]</li> <...
<p>Not sure what you're driving at here as simply replacing column A with column B as string seems odd. But since that seems to be what you want:</p> <pre><code> import pandas as pd import numpy as np a = [ 1, 2, 3, 4] b = [.1,.2,.3,.4] df = pd.DataFrame(data = np.array([a,b]).T, columns = ['A', 'B']) df['A'] = d...
python|pandas|list
0
12,785
36,283,029
Joining/Merging two Pandas dataframes. Match the levels of one to the index of the other
<p>I am trying to join two pandas dataframes; The left one, has a multiindex and the right one is just a plain vanilla dataframe. I would like to join the index of the right dataframe on one of the levels of the left dataframe. For example if we have the following example:</p> <pre><code> Age Boys ...
<p>Name your indexes - it will help Pandas to understand how to join your data frames:</p> <pre><code>In [72]: df1 Out[72]: Age sex name Boys Sam 21 John 22 Girls Lisa 23 In [73]: df1.index.names=['sex','name'] In [74]: df2.index.name = 'name' </code></pre> <p>Joining can be prett...
python|join|pandas|merge|dataframe
2
12,786
36,589,020
Conversion of dates in the dataframe column into MM/DD/YYYY
<p>I have 4 dataframes named <code>df1</code>,<code>df2</code>,<code>df3</code>,<code>df4</code> with one column <code>Date</code>. The column consist of dates with different format. <code>df1</code> has date column of type int64, <code>df2</code> has date column of type object, <code>df3</code> has date column has typ...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="noreferrer"><code>to_datetime</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="noreferrer"><code>dt.strftime</code></a>, but <code>type</c...
python|date|pandas|dataframe
10
12,787
4,863,404
Difference between data sets
<p><br> I have a two data sets as lists, for example: </p> <pre><code>xa = [1, 2, 3, 10, 1383, 0, 12, 9229, 2, 494, 10, 49] xb = [1, 1, 4, 12, 1100, 43, 9, 4848, 2, 454, 6, 9] </code></pre> <p>Series are market data that may contain tens of thousands numbers, their length is same.</p> <p>I need to find "differe...
<p>Well if you want a similarity metric for comparing two 1D vectors and that preferably returns a value between 0 and 1 (or 0 and 100%), <strong><em>cosine similarity</em></strong> satisfies those criteria (subject to the proviso at the end). (Whether it's appropriate given the context of your problem, i don't know, b...
python|math|dataset|numpy|scipy
5
12,788
53,121,996
How to tokenize a 'Python Pandas' 'Series' of strings
<p>hello I am trying to convert into tokens of every content of "Chat" which is a column in my pandas dataframe having a length of 1000 </p> <pre><code>text=df["Chat"] words=text.split() tokens=word_tokenize(text) tokens=[i.lower() for i in words] table=str.maketrans("","",string.punctuation) stripped=[i.translate(...
<p>your dataframe is called df, this is a dataframe object.</p> <p>when you do <code>df["Chat"]</code> you are indexing into the pandas series object Chat.</p> <p>You are then applying a python function <code>.split()</code>, but a pandas series has no such attribute, therefore you are getting an attribute error.</p>...
python|pandas
0
12,789
53,106,467
Pandas: Find and print all floats in column
<p>I have tried to use</p> <pre><code>if df.loc[df['col_1']] == float: print(df.loc[df['col_1']]) </code></pre> <p>But that doesn't work. I basically just want to find everything of the datatype <code>float</code> in a column and see what it is and where. How do I go about doing that?</p> <p>I need to do this be...
<p>So I assuming you have <code>column</code> <code>type</code> is <code>object</code> , usually <code>pandas</code> only have one data type per columns </p> <pre><code>df.col_1.map(type)==float# will return bool </code></pre>
python|pandas
4
12,790
52,983,942
im reading the excel file in python-pandas using the below code in centos but im getting error
<p><strong>pyxel.py</strong></p> <pre><code>import pandas as pd from pandas import ExcelFile data = pd.read_excel("path/dat.xlsx",sheet_name="sheet") print(data) </code></pre> <p>In the above code, I'm just reading the excel file and printing the data. I'm getting the below error as in the image <a href="https://i.s...
<p>try this command, use 2 forward slashes instead of one or u can try with an r'</p> <p>option1</p> <pre><code>data = pd.read_excel("path//dat.xlsx",sheet_name="sheet") </code></pre> <p>option2</p> <pre><code>data = pd.read_excel(r'path/dat.xlsx',sheet_name="sheet") </code></pre> <p>Hope this works!!</p>
python|excel|pandas|centos7
0
12,791
65,706,490
Changing numpy array size on the fly
<p>I have a numpy array that starts out empty and over the course of a loop is supposed to receive a number of entries, though I don't know how many entries there will be prior to execution.</p> <p>I've tried different things to varying success and currently my code looks something like this:</p> <pre><code>pi = np.emp...
<p>You are not assigning the new array to pi.</p> <pre><code>pi = np.empty((0)) for... if... pi = np.concatenate([pi, np.array([0])]) </code></pre>
python|numpy
0
12,792
65,601,380
I can't subset rows in pandas this way: df[0] (or with any integer)
<p>I loaded a csv and then tried to get the first row with the row index number</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd pkm = pd.read_csv('datasets/pokemon_data.csv') pkm[0] </code></pre> <p>But for some reason I get this error, as far as I know, you can subset the way I did.</p> <pre><...
<p><code>pkm[0]</code> calls for the column named <code>0</code> in <code>pkm</code>. That's why it's not working. Try <code>pkm['HP']</code> or using a column name and it will be clear.</p>
python|pandas|dataframe|data-science
1
12,793
65,507,899
Python, Four-bar linkage angle-time plot
<p>I'm trying to plot the angle vs. time plot for the output angle of a four-bar linkage (angle <code>fi4</code> in the image below). This angle is calculated using the solution from the <a href="https://scholar.cu.edu.eg/?q=anis/files/week04-mdp206-position_analysis-draft.pdf" rel="nofollow noreferrer">https://scholar...
<p>The <code>linespace(0, 50, 100)</code> is too fast. Replacing it with:</p> <pre><code>t = np.linspace(0, 5, 100) </code></pre> <p>Second, all the calculations involving the bare <code>np.arctan()</code> are incorrect. You should use <a href="https://numpy.org/doc/stable/reference/generated/numpy.arctan2.html" rel="n...
python|numpy|matplotlib
3
12,794
21,275,018
Python size() and len() for list of list
<p>I have a list:</p> <pre><code>a = [[1, 0], 'apple', 5] </code></pre> <p>Why does <code>size(a[0])</code> work even though <code>a</code> isn't a <code>numpy array</code>? </p> <p>I thought size worked only on arrays?</p> <p>Thanks!</p>
<p><code>size[a[0]]</code> shouldn't work, but <code>size(a[0])</code> should. You can simply look at the source for <code>np.size</code>:</p> <pre><code>def size(a, axis=None): [docstring removed] if axis is None: try: return a.size except AttributeError: return asarr...
python|numpy
3
12,795
63,587,227
create a new column in pandas and assign value from existing column if condition is true
<p>I have 15 minutes candles of stock data and have a short signal - I want to create a new column stop-loss if signal=0 then stop-loss = high of the second next candle ie( df['high'].shift(-2) )</p> <pre><code> open high low close signal date ...
<p>Let us try <code>np.where(condition, answer if condition is true, answer if condition is false)</code></p> <pre><code>df['stop-loss']=np.where(df.signal==0,df.high.shift(-2),'') </code></pre> <p>In this case, you didnt specify what the condition should be if false so I put there <code>''</code></p> <pre><code> ...
python|pandas|time-series|stock
0
12,796
63,518,021
How to find A img tag url inside a column of CSV File which has a lot of links and compare that link with the same present in other CSV file
<pre><code>import csv # Read input Topic or Reply file csvfile = open('rad.csv', newline='') reader = csv.reader(csvfile) csvfile1 = open('new.csv', newline='') reader1 = csv.reader(csvfile1) # Extract image sources for row in reader: content = row[8] imageExists = &quot;&lt;img&quot; in content and &quot;src=\...
<p>Rather than try to parse the HTML as strings, I recommend using BeautifulSoup. In the example below I assume there are no commas in the HTML entries</p> <pre><code>from bs4 import BeautifulSoup with open('example.txt','r') as file_handle: example_file_content = file_handle.read().split(&quot;\n&quot;) list_of_...
python|pandas|csv
0
12,797
63,635,603
How to scan characters in strings to match to another string in different column
<p>I have 2 columns of strings and I'd like to match the strings based on the first 3 characters in each string. Basically code that goes over every character of column 1 row 1 and compares it with rows in column 2 to find the best match.</p> <p>IE: Row 1 Column 1 scans &quot;p&quot;&quot;a&quot;&quot;s&quot; and looks...
<p>Probably not the fastest and cleanest solution, but will return what you're asking for:</p> <pre><code>df['Col3'] = df.Col1.apply(lambda x: [i for i in df.Col2 if i.startswith(x[:3])][0]) </code></pre>
python|pandas|knime
0
12,798
63,729,209
extend() not producing a list
<p>I am working with a list of strings and a dataframe containing strings. Imagine the scenario:<br /> <pre>A = ['the', 'a', 'with', 'from', 'on']</pre> and a dataframe: <pre>df = {'col1':['string', 'string'], 'col2':['the man from a town', 'the man on a bus']}</pre></p> <p>I am trying to now create a new column in my ...
<p>Your code just needed a little indentation adjustment and use <code>append</code> instead of <code>extend</code>. If you extend then the string <code>'the'</code> will be taken as a list and each letter will be appended to the collecting list.</p> <pre><code>def words_in_A(row): lst = [] for item in A: ...
python|pandas
3
12,799
53,420,008
Why do we need parentheses or new variable when calculating sum of inverted Series of booleans?
<p>Given some data:</p> <pre><code>&gt;&gt; s = pd.Series([True, False, True, False, True]) </code></pre> <hr> <pre><code>&gt;&gt; ~s.values == (~s).values array([True, True, True, True, True]) </code></pre> <p>But</p> <pre><code>&gt;&gt; ~s.values.sum() -4 &gt;&gt; (~s).values.sum() 2 </code></pre> <p>And</p>...
<p>Because the <a href="https://docs.python.org/3/reference/expressions.html#operator-precedence" rel="nofollow noreferrer">precedence</a> of attribute access is higher than the precedence of the <code>~</code> operator. So it is summed before it is negated.</p> <p>A lot of the numpy/pandas objects override the bitwis...
python|pandas|numpy
4