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
369,900
68,067,705
Broadcasting over two arrays with different shapes (Numpy-Python)
<p>Suppose I have the following arrays:</p> <pre><code>first_array = array([[1, 8, 3, 9, 2], [2, 6, 4, 1, 9], [4, 2, 12, 8, 16], [5, 3, 7, 18, 21], [6, 20, 4, 8, 24]]) </code></pre> <p>So an array with shape <code>(5, 5)</code></p> <p>N...
<p>Does this code do what you meant you needed done?<br /> You are welcomed to test it on your test case and update me if you need more help.</p> <pre><code>import numpy as np arr = np.arange(50).reshape(10, 5) arr_slice = arr[:2, :] # &quot;outer&quot; tensor subtraction arr_sub = arr_slice[:, None, :] - arr[None, :,...
python|numpy|array-broadcasting
3
369,901
68,270,640
failed: Network error while downloading Excel file generated by jupyter notebook
<p>my jupyter notebook is saving a dataframe(having styles) to an excel file. then I have created a link to download this excel file:</p> <pre><code>df=df.to_excel('ABC.xlsx', index=True) filename ='ABC.xlsx' file_link = &quot;&lt;a href='{href}' download='ABC.xlsx'&gt; Download ABC.xlsx&lt;/a&gt;&quot; html = HTML(fil...
<p>In you csv code, you use <code>csv=df.to_csv(index=True)</code>, according to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer">docs</a></p> <blockquote> <p>If path_or_buf is None, returns the resulting csv format as a string. Otherwise return...
python|excel|pandas|dataframe|jupyter-notebook
0
369,902
59,141,899
How to transfer a list of elements to a pandas dataframe by every three elements?
<p>I have a list of people's info and I want to transfer it to a pandas dataframe. My list:</p> <pre><code>My_lst = ['Name1','Title1','Company1','Name2','Title2','Company2','Name3','Title3','Company3', 'Name4','Title4','Company4','Name5','Title5','Company5','Name6','Title6','Company6'...] </code></pre> <p>Expected ou...
<p>IIUC <code>reshape</code></p> <pre><code>pd.DataFrame(np.array(My_lst).reshape((-1,3)),columns=['name','title','company']) name title company 0 Name1 Title1 Company1 1 Name2 Title2 Company2 2 Name3 Title3 Company3 3 Name4 Title4 Company4 4 Name5 Title5 Company5 5 Name6 Title6 Company6 </co...
python-3.x|pandas|list
2
369,903
59,450,739
Create multiple new columns based multiple conditions in Pandas
<p>I try to get new columns <code>a</code> and <code>b</code> based on the following dataframe:</p> <pre><code> a_x b_x a_y b_y 0 13.67 0.0 13.67 0.0 1 13.42 0.0 13.42 0.0 2 13.52 1.0 13.17 1.0 3 13.61 1.0 13.11 1.0 4 12.68 1.0 13.06 1.0 5 12.70 1.0 12.93 1.0 6 13.60 1.0 N...
<p>Use:</p> <pre><code>#filter all a and b columns b = df.filter(like='b') a = df.filter(like='a') #test if at least one 0 or 1 value m1 = b.eq(0).any(axis=1) m2 = b.eq(1).any(axis=1) #get means of a columns a1 = a.mean(axis=1) #forward filling mising values and select last column b1 = b.ffill(axis=1).iloc[:, -1] a2...
python-3.x|pandas|dataframe
1
369,904
59,131,295
New dataframe column for count of rows with certain value in a column , with same customer ID column and less than date and time
<p> EDITED <br><br> I want to add a new column called prev_message_left which counts the no. of messages_left per ID less than the date prior the given time. Basically I want to have a column which says how many times we had left message on call to that customer prior to the current time and date. This is how my data ...
<p>IIUC <code>cumcount</code> after <code>sort_values</code></p> <pre><code>df['pervious']=df.sort_values(['date','call_time']).groupby('ID').cumcount() df date ID call_time message_left pervious 0 20191101 1 8:00 0 2 1 20191102 2 9:00 1 0 2 20191030 ...
python|pandas|dataframe|group-by
1
369,905
59,091,196
Checking the type of relationship between columns in python/pandas? (one-to-one, one-to-many, or many-to-many)
<p>Let's say I have 5 columns.</p> <pre><code>pd.DataFrame({ 'Column1': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'Column2': [4, 3, 6, 8, 3, 4, 1, 4, 3], 'Column3': [7, 3, 3, 1, 2, 2, 3, 2, 7], 'Column4': [9, 8, 7, 6, 5, 4, 3, 2, 1], 'Column5': [1, 1, 1, 1, 1, 1, 1, 1, 1]}) </code></pre> <p>Is there a function to know the type of r...
<p>This should work for you:</p> <pre><code>df = pd.DataFrame({ 'Column1': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'Column2': [4, 3, 6, 8, 3, 4, 1, 4, 3], 'Column3': [7, 3, 3, 1, 2, 2, 3, 2, 7], 'Column4': [9, 8, 7, 6, 5, 4, 3, 2, 1], 'Column5': [1, 1, 1, 1, 1, 1, 1, 1, 1]}) def get_relation(df, col1, col2): first_m...
python|python-3.x|pandas|many-to-many|relational-database
12
369,906
59,278,120
How to pass a sparse tensor to the Dense Layer in TF 2.0?
<p>I am using TF 2.0.</p> <p><strong>WORKING:</strong></p> <pre><code>from tensorflow.keras import layers inputs = layers.Input(shape=(256,), sparse=False, name='name_sparse') x = layers.Dense(32, name="my_layer")(inputs) print(x) </code></pre> <p>Output: <code>Tensor("my_layer/Identity:0", shape=(None, 32), dtype=...
<p>This happens because when input tensor is sparse shape of this tensor evaluates to <code>(None,None)</code> instead of <code>(256,)</code></p> <pre><code>inputs = layers.Input(shape=(256,), sparse=True, name='name_sparse') print(inputs.shape) # output: (?, ?) </code></pre> <p>This also seems to be an open <a href...
python|tensorflow|keras|tensorflow2.0|valueerror
3
369,907
59,277,317
Conditional Column Values In Pandas For Each Row in Group
<p>I asked a similar question on conditional columns in pandas, but got a little stuck at work with a new issue. A sample dataset is below:</p> <pre><code> Name Date Type Currency 0 John *2017-07-06 BTC USD 1 John *2017-07-06 Paypal USD 2 John *2017-07-06 Fasts...
<p>You can first check if the <code>Type</code> is <code>BTC</code> and use <code>groupby().transform</code>:</p> <pre><code>df['Covered'] = np.where(df['Type'].eq('BTC') .groupby(df['Date']) .transform('any'), # 'max' also works 'Yes'...
python-3.x|pandas|numpy|conditional-statements|pandas-groupby
1
369,908
59,330,757
why need to turn tensor into a list in tensorflow run.session()
<p>I am quite a newbie to tensorflow, but I just can't simply let go of my concern. Could anyone provide some explanation to help me understand why we need to turn the tensor into a list in session.run(fetches, feed_dict) in the following code? The code is from <a href="https://github.com/Kulbear/deep-learning-coursera...
<p>It's because of the way tensorflow works. </p> <p>When you say </p> <pre><code>out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0}) </code></pre> <p>you're essentially saying run the computation associated with <code>A</code>, and assign the result to <code>out</code></p> <hr> <p>Why a list? Tensor...
python|tensorflow
1
369,909
59,288,049
Plotting a plot with an additional y axis on the right and an additional x axis on the top, linked to the bottom one
<p>I am trying to make a figure that has two plots, that share the same x axis on the bottom, one is linked to the left y axis, the other to the right y axis, and also have the top x-axis, which is a function of the bottom x-axis (current divided by area). Basically what I would like to have in the end is something lik...
<p>The right axis would be a <strong>twin</strong> axes, using the same x axis, but a different y axis as the original one.<br> The top axis would be a <strong>secondary axis</strong>, being linked to the original x axis by a functional dependence.</p> <p>In total:</p> <pre><code>import matplotlib.pyplot as plt fig,...
python|numpy|matplotlib|plot
2
369,910
59,434,979
KeyError: "None of ['minute'] are in the columns" when setting index
<p>I have the following code:</p> <pre><code>import pandas as pd from pandas import datetime from pandas import DataFrame as df import matplotlib import datetime import fxcmpy import numpy as np print(con.get_instruments()) symbols = con.get_instruments() ticker = 'NGAS' start = datetime.datetime(2015,1,1) end = da...
<p>Instead of using <em>fxcmpy</em> I read <em>data</em> from a source CSV file, such that it contained initially:</p> <pre><code> C1 C2 2019-05-02 12:33 22 Xxxx1 Yyyy1 2019-05-04 10:12 00 Xxxx2 Yyyy2 2019-05-05 16:54 13 Xxxx3 Yyyy3 </code></pre> <p>(the index with no name, as <strong...
python-3.x|pandas
1
369,911
59,268,618
IDataView for Keras Converted ONNX model for ImageClassification
<p>I have a Trained Model with Keras and Tensorflow Backend (Keras 2.2.4 Tensorflow 1.13.1) and i want to use that Model in Visual Studio with ML.Net.</p> <p>Therefore i converted my Model to ONNX with winmltools.convert_keras (I tired it with a Tensorflow 2.0 model but i got the <code>No module named 'tensorflow.tools...
<p>If you look at the <a href="https://github.com/dotnet/machinelearning-samples/blob/3c38284ed183a1d56fda86c300a7774964e19988/samples/csharp/getting-started/DeepLearning_TensorFlowEstimator/ImageClassification.Train/Model/ModelBuilder.cs#L65" rel="nofollow noreferrer">samples</a>, you can see that the output column in...
c#|tensorflow|keras|ml.net|onnx
1
369,912
59,239,174
How do I fill a Pyplot Line plot and change the fill depended on the value
<p>I have a pd DataFrame which holds a Depth column and a number of other columns for variables at those depth points. Plotting line graphs is fine. What i want to do is plot Depth against category (integer, 1-6) and have the bar or fill change based on category. I also want to be able to sharey=true with adjoining lin...
<p>After a lot of blind alleys, I have come up with the following code. I have ordered the fills (with no alpha) so they sit on top of each other, effectively masking the underlying fill. Possibly not elegant, but go the job done.</p> <pre><code>axs[1].fill_betweenx(df['Depth'],0,df['SBTn'], where=(df['SBTn'])&gt;=1,...
python|pandas|dataframe|matplotlib
0
369,913
59,121,220
read_excel that creates index when index_col=none using pandas
<p>I'm trying to read an excel file into a data frame and I want set the index later, so I don't want pandas to use column 0 for the index values.</p> <p>By default (index_col=None), it shouldn't use column 0 of my data for the index.</p> <p>How can i solve this please?</p> <pre><code>data = pd.read_excel(r'Indicato...
<p>Try setting the header=None</p> <pre><code>data = pd.read_excel(r'Indicators.xls', Header = None, index_col=None) </code></pre>
excel|python-3.x|pandas|csv|dataframe
0
369,914
59,425,902
named entity recognition using seq2seq model such as transformer?
<p>Can we use neural machine translation (like seq2seq) for named entity recognition?such as USING TRANSFORMER nerual network FOR NER TASK. SOURCE IS WORD SEQUENCE, TARGET IS TAG sequence LIKE "o o o PERSON o o o location",is it possible? </p>
<p>Yes, you can use transformer-based models for NER task. You can check this paper <a href="https://arxiv.org/abs/1810.04805" rel="nofollow noreferrer">BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding</a>. The method can be employing a pre-trained BERT model by fine-tuning it to NER tas...
tensorflow|pytorch
0
369,915
59,091,003
Scipy null_space does not give me the correct answer
<p>I have a problem with Scipy null_space. Take the following example:</p> <pre><code>A = np.array([[7,3,2],[3,9,4],[2,4,5]]) eigen = np.linalg.eig(A) </code></pre> <p>with output eigen =</p> <pre><code>(array([13.477, 5. , 2.523]), array([[ 0.486, 0.873, -0.041], [ 0.74 , -0.436, -0.511], [ 0.46...
<p>From the documentation of <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.null_space.html" rel="nofollow noreferrer"><code>null_space</code></a>,</p> <blockquote> <p><code>rcond</code> : Relative condition number. Singular values s smaller than <code>rcond * max(s)</code> are considered...
python|numpy|scipy
2
369,916
59,188,415
Pandas dataframe apply lambda to selected rows only (based on a condition) within the dataframe
<p>In the line of code below, I'm trying to apply a lambda formula only to selected rows based on a condition. I don't want the formula to apply to every row in the dataset. The code seems to be working correctly but I'm getting a warning that says "SettingWithCopyWarning: A value is trying to be set on a copy of a sli...
<p>Update: This solution works:</p> <p>df['GlobalName'] = np.where(df['GlobalName']=='', df['IsPerson'].apply(lambda x: x if x==True else ''), df['GlobalName'])</p>
python|pandas|dataframe
0
369,917
59,070,760
Value Error while applying conditions to a loop (pandas)
<pre><code>while (i&lt; len(df)): if (df['ID'][i] == df['ID'][i+1]) &amp; (df['Week_start'] == df['Week_end']): if (df['ship'][i] &gt; df['ship'][i+1] ): df['radar'][i] =df['radar'][i+1] + df['parked'][i] - df['parked'][i+1] else: df['radar'][i] =df['radar'][i+1] else: ...
<p>You are getting the error in this line:</p> <pre class="lang-py prettyprint-override"><code>df['Week_start'] == df['Week_end'] </code></pre> <p>specify some index like</p> <pre><code>df['Week_start'][i]== df['Week_end'][i+1] </code></pre> <p>Hope this will help!</p>
python|pandas|loops|dataframe|conditional-statements
2
369,918
59,131,197
How to Get Certain Data Within a Pandas Column?
<p>I am making a table and grouping it by a variable called 'passer_player_name'</p> <pre><code>data.loc[(data['play_type'] == 'pass') &amp; (data['down'] &lt;= 4)].groupby(by='passer_player_name')[['epa']].mean() passer_index = data.loc[(data['play_type'] == 'pass') &amp; (data['down'] &lt;= 4)].groupby(by='passer_pl...
<p>Create a map for the team names like this:</p> <pre><code>r = {'K.Murray': 'ARI', 'M.Ryan': 'ATL', 'L.Jackson': 'BAL', 'J.Allen': 'BUF', 'K.Allen': 'CAR', 'M.Trubisky': 'CHI', 'A.Dalton': 'CIN', 'B.Mayfield': 'CLE', 'D.Prescott': 'DAL', 'D.Lock': 'DEN', 'D.Blough': 'DET', 'A.Rodgers': 'GRE', 'D.Watson': ...
python|pandas
0
369,919
59,475,971
How to merge similar rows and split column into rows by values?
<p>I have this data set for example:</p> <pre><code> Name Number Is true 0 Dani 2 yes 1 Dani 2 no 2 Jack 5 no 3 Jack 5 maybe 4 Dani 2 maybe </code></pre> <p>I want to create a new data set that combines similar rows and adds columns by column different values. T...
<p>You can try this:</p> <pre><code>df2 = df.drop_duplicates(subset=['Name', 'Number Is']) df2 = df2.reset_index(drop=True).assign(true= df.groupby('Number Is')['true'].agg(list).reset_index(drop=True) ) temp = df2['true'].apply(pd.Series).T temp.index = temp.index+1 temp = temp.T df2 = df2.assign(**temp.add_prefix('...
pandas|dataframe
0
369,920
59,123,853
python3: how to print groupby.last()?
<pre><code>$ cat n2.txt apn,date 3704-156,11/04/2019 3704-156,11/22/2019 5515-004,10/23/2019 3732-231,10/07/2019 3732-231,11/15/2019 $ python3 Python 3.7.5 (default, Oct 25 2019, 10:52:18) [Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin Type "help", "copyright", "credits" or "license" for more info...
<pre><code>df = pd.read_csv("n2.txt") g = df.groupby('apn').last() print(g.to_csv()) </code></pre> <p>Should work as you wish.</p> <p>If you type <code>g.to_csv()</code> into your console, it returns a string starts with <code>'apn,data,\r\n...'</code>. And <code>print</code> function will start a new line when come ...
python|pandas|dataframe|group-by|python-3.7
1
369,921
59,310,769
Python Error: AttributeError: __enter__ Here
<pre class="lang-py prettyprint-override"><code>I = mpimg.imread(FACE_INPUT_PATH + picname) I_np = np.array(I) </code></pre> <pre><code>Traceback (most recent call last): File "pretrain_load_test.py", line 67, in &lt;module&gt; I = mpimg.imread(FACE_INPUT_PATH + picname) File "/home/avicky/env/lib/pyth...
<p>Try to update your libs, its seems like version conflicts</p> <p><code>pip install -U pillow</code></p>
python|tensorflow|matplotlib|keras|virtualenv
0
369,922
59,400,855
pandas create a DataFrame by multiplying every element in a list with every other element
<p>I need to populate a dataframe with a matrix built from a single list, but the math and python syntax are beyond me. I essentially need to perform some math operations as if the same list were both the rows and the columns.</p> <p>So it should look something like this....</p> <pre><code>#Input list = [1,2,3,4] c...
<p>Broadcasted multiplication will work here:</p> <pre><code>arr = np.array([1, 2, 3, 4]) pd.DataFrame(arr * arr[:,None]) 0 1 2 3 0 1 2 3 4 1 2 4 6 8 2 3 6 9 12 3 4 8 12 16 </code></pre> <p>Alternatively, most numpy arithmetic functions define an <code>.outer</code> unfunc:</p> <pre...
python|pandas|dataframe
2
369,923
59,276,899
Pandas set index or reindex without changing the order of the data frame
<p>Hello I have a dataframe I sorted so the index is not in order so I want to reorder the index so that sorted values have an index that is sequential I have not been able to figure this out should I remove the index or is there a way to set the index? When I reindex it should sorts by the index which unsorts by index...
<h1>Solution</h1> <p>I made some dummy data to show this. I hope this answers your question. Leave comments if you have any questions.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({'x': [1,2,3], 'y': [120, 8, 32]}) df = df.reset_index(drop=False).rename(columns={'index': ...
python|pandas
0
369,924
59,069,660
Check if dataframe value +/- 1 exists anywhere else in a given column
<p>Let's say I have a dataframe df that looks like this:</p> <pre><code> irrelevant location 0 1 0 1 2 0 2 3 1 3 4 3 </code></pre> <p>How do I create a new true/false column "neighbor" to indicate if the value in "location" +/- 1 (pl...
<p>To find a neighbor anywhere in the column, create a list of all neighbor values then check <code>isin</code>.</p> <pre><code>import numpy as np vals = np.unique([df.location+1, df.location-1]) #array([-1, 0, 1, 2, 4], dtype=int64) df['neighbor'] = df['location'].isin(vals) # irrelevant location neighbor #...
python|pandas|numpy|dataframe
3
369,925
59,306,481
Convert Nx1 pandas dataframe with single 1xM array-containing column to M columns in Pandas dataframe
<p>This is the current dataframe I have: It is Nx1 with each cell containing a numpy array.</p> <pre><code>print (df) age 0 [35, 34, 55, 56] 1 [25, 34, 35, 66] 2 [45, 35, 53, 16] . . . N [45, 35, 53, 16] </code></pre> <p>I would like somehow to ravel each value of each cell to a new column.</p> ...
<p>You can reconstruct the dataframe from the lists, and customize the column names with:</p> <pre><code>df = pd.DataFrame(df.age.values.tolist()) df.columns += 1 df = df.add_prefix('age') print(df) age1 age2 age3 age4 0 35 34 55 56 1 25 34 35 66 ... </code></pre>
python|pandas|dataframe
2
369,926
59,464,346
How do I use scipy.ndimage.interpolate to randomly rotate a numpy array in 3d?
<p>I made a square in 3 dimensions that is essentially a 3d version of this:</p> <pre><code> [[0., 0., 0., 0., 1., 1., 1., 0.], [0., 0., 0., 0., 1., 1., 1., 0.], [0., 0., 0., 0., 1., 1., 1., 0.], [0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0.], [0....
<blockquote> <p>the cube being rotated 45 degrees with respects to the x and z axes </p> </blockquote> <pre><code># ... coords = np.where(square == 1) coords = np.transpose(coords) # get coordinates into a proper shape rot = Rotation.from_euler('xz', [45, 45], degrees=True) # create a rotation coords = ro...
python|numpy|scipy
2
369,927
59,070,802
pandas df[df["A"]==None] is not the same as df["A"].values==None
<p>Assume I have a dataframe <code>df</code> where the column <code>A</code> consists of 10 <code>None</code> and the rest is something else.</p> <p>If I do the slicing <code>df=df[df["A"]==None]</code> I get a wrong result. I figured out that <code>df["A"]==None</code> returns <code>False</code> (even when the elemen...
<p>You should use <code>isna()</code> method over the serie.</p> <p>For your case:</p> <pre><code>df = df.loc[df['A'].isna()] </code></pre>
python|pandas|slice
1
369,928
59,198,615
Combine multiple matplotlib figures into one
<p>I have a function that takes an enhanced dicom file and does the following:</p> <ol> <li>Use a for loop that creates a single slice from the dicom file and then index it into a smaller array around a set of six specks.</li> <li>A second for loop that draws circles around the six specks and one for the background</l...
<p>In the following we'll use the <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots.html" rel="nofollow noreferrer"><code>plt.subplots</code></a> method to produce a figure and a grid of <code>axes</code>, the Matplotlib objects that someone understands as <em>subplots</em>...</p> <p>Iteration on ...
python|numpy|matplotlib|dicom
1
369,929
59,421,407
(MySQLdb._exceptions.ProgrammingError) not enough arguments for format string
<p>I'm using following query to read data from a mysql db:<br> setup:</p> <pre><code>conn = MySQLdb.connect(host='127.0.0.1', port=3306, user='**', passwd='**', db='***') engine = create_engine('mysql+mysqldb://***') sql = 'show tables like "{}"'.format('aTable_' + '%') </code></pre> <p>option-1: this is OK</p> <pr...
<p>Instead of passing values to SQL using string formatting, use placeholders:</p> <pre><code>from sqlalchemy import text engine = create_engine('mysql+mysqldb://***') sql = text('SHOW TABLES LIKE :pattern') a1 = pd.read_sql_query(sql, engine, params={'pattern': 'aTable_%'}) </code></pre> <p>Using <a href="https://do...
python|pandas|sqlalchemy|mysql-python
4
369,930
59,180,942
Pandas : Mapping one column values using other dataframe column
<p>I have two dataframes as described above</p> <p>I would like to create in the second table an additional feature (Col_to_create) related to the value of feature A. </p> <p>Table 2 has more than 800 000 samples so that I ask for a faster way to do that. </p> <p>First table:</p> <pre><code>a b 1 100 2...
<p>You can use the method <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html#//apple_ref/Method/pandas.Series.map" rel="nofollow noreferrer"><code>map</code></a>:</p> <pre><code>df2['Col_to_create'] = df2['Refer_to_A'].map(df1.set_index('a')['b']) </code></pre> <p>Output:</p> <...
python|pandas
3
369,931
59,200,593
How do I add a blank cell inside a column of a Pandas dataframe?
<p>I'm a beginner to Python and using dataframes thorugh Pandas. I'm trying to extract a table from an XML file using <code>xml.dom.minidom</code> into an Excel file. This is what the original table should look like (notice the black entry under 'Bike'):</p> <pre><code>VEHICLE BRAND Car Mercedes Bike Kawa...
<p>See below. </p> <p>The idea is to create a csv file which is usually associated with Excel. The XML parsing is done by builtin python XML parsing library 'ElementTree'. When you double click the csv file it will usually will be opened by Excel and you will get the table you are looking for. </p> <p><strong>Note</s...
python|xml|pandas|dataframe|xml-parsing
0
369,932
59,466,393
How to find the top n minimum values in a two dimensional numpy matrix
<p>I have a simple two dimensional numpy matrix and I need to find the n minimum values in the matrix. I have found some functions which are doing that for a numpy array (argpartition), but I am not sure if it would work on a matrix and won't change the matrix itself. Also I found for a list matrix the use of heapmin b...
<p>You can flatten that matrix, use <code>np.ravel</code>, and sort it afterwards:</p> <pre><code>&gt;&gt;&gt; v array([[2, 2, 3, 3, 4], [4, 5, 5, 5, 6], [6, 7, 7, 8, 8], [9, 9, 9, 9, 9]]) &gt;&gt;&gt; v1 = v.ravel() #flattened the array &gt;&gt;&gt; v1.sort() # sorted that. &gt;&gt;&gt...
python|python-3.x|numpy
3
369,933
59,444,555
Predicting from a trained LSTM model
<p>I have trained a model using LSTM, on some data I have collected. I wanted to categorise as either Canine or Feline. </p> <p>I am attempting to predict a string of text like so</p> <pre><code>json_file = open('model.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(l...
<p>From your question, I understand that the <code>Model</code> is predicting correctly after <code>Training</code> but it is <code>Training</code> Same <code>Class</code> after Loading the <code>Saved Model</code>.</p> <p>I recently faced the same issue and the solution to this problem is to Save the <code>Tokenizer<...
python|tensorflow|machine-learning|keras|lstm
0
369,934
59,210,988
Call a Python function from C and consume a 2D Numpy array in C
<p>I'm trying to figure out, how I could achieve this: </p> <p>I'm having a Python script, which in the end produces a Numpy array, an array of arrays of floats, to be more specific. I have all properly set: I can pass parameters from C to Python, launch Py functions from C, and process returned scalar values in C. </...
<p>What you need to look at is Inter Process communication (IPC). There are several ways to perform it.</p> <p>You can use one of:</p> <ul> <li>Files (Easy to use)</li> <li>Shared memory (really fast)</li> <li>Named pipes</li> <li>Sockets (slow)</li> </ul> <p>See <a href="https://en.wikipedia.org/wiki/Inter-process_...
python|c|arrays|numpy
0
369,935
59,296,693
Converting a SavedModel to TFLite
<p>I've downloaded a FasterRCNN SavedModel from <a href="http://download.tensorflow.org/models/object_detection/faster_rcnn_resnet101_coco_2018_01_28.tar.gz" rel="nofollow noreferrer">here</a>. I'd like to convert it to a TFLite model. This seems like something simple to do with the <a href="https://www.tensorflow.org/...
<p>You can use the following code snippet to do that.</p> <pre><code>saved_model_dir = 'Path_to_saved_model_dir' # Convert the model. converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir) tflite_model = converter.convert() # Save the TF Lite model. with tf.io.gfile.GFile('model.tflite', 'wb') as f: ...
tensorflow|tensorflow-lite
2
369,936
59,432,324
How to mask image with binary mask?
<p>Suppose I have a greyscale image here:</p> <p><a href="https://i.stack.imgur.com/RuXCZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RuXCZ.png" alt="enter image description here" /></a></p> <p>And a binary masked image here:</p> <p><a href="https://i.stack.imgur.com/SyD9T.png" rel="nofollow nore...
<p>Use <a href="https://docs.opencv.org/2.4.8/modules/core/doc/operations_on_arrays.html#bitwise-and" rel="noreferrer"><code>cv2.bitwise_and</code></a> to mask an image with a binary mask. Any white pixels on the mask (values with 1) will be kept while black pixels (value with 0) will be ignored. Here's a example:</p> ...
python|image|numpy|opencv|image-processing
6
369,937
59,343,844
Iterating on value counts of a column in dataframe
<p>I have this dataframe:</p> <pre><code>power = [0,1,2,9,9,9,9,9,9,9,8,3] df_p = pd.DataFrame(power, columns = ['power']) power 0 0 1 1 2 2 3 9 4 9 5 9 6 9 7 9 8 9 9 9 10 8 11 3 </code></pre> <p>Here I took the value count of power column and then again make a df of this where power and re...
<p>Considering threshold as <code>0.5</code> , you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pct_change.html" rel="nofollow noreferrer"><code>pct_change()</code></a> to see percentage change across a series and apply your logic:</p> <pre><code>df_p.power.value_counts(...
python|pandas|loops
0
369,938
59,077,311
Joining two different columns in one (oretation is name )
<p>I have question how can I connect two diferent columns in one for example: A , B, C are existing df. The column D is finale df.</p> <pre><code> A B C 1 Pattern B3341 Description 7 18774 18.11.2019 63 8 18775 18.11.2019 ...
<p>You can use the function <a href="http://docs.scipy.org/doc/numpy-1.17.0/reference/generated/numpy.where.html#numpy.where" rel="nofollow noreferrer"><code>np.where</code></a>:</p> <pre><code>df['D'] = np.where(df['C'] == ' Description', df['B'], df['C']) </code></pre> <p>Or the method <a href="http://pandas.pydata...
python|pandas
2
369,939
59,148,994
How to get N random integer numbers whose sum is equal to M
<p>I want to make a list of N random INTEGER numbers whose sum is equal to M number.</p> <p>I have used numpy and dirichlet function in Python, but this generate double random number array, I would like to generate integer random number.</p> <pre><code>import numpy as np np.random.dirichlet(np.ones(n))*m </code></pr...
<p>The problem with using <code>dirichlet</code> for this is that it is a distribution over real numbers. It will yield a vector of numbers in the range <code>(0,1)</code>, which sum to 1, but truncating or rounding them may remove the guarantee of a specific sum. Following <a href="http://sunny.today/generate-random...
javascript|python|numpy|dirichlet
6
369,940
59,253,381
How to load tensorflow lite model on Xamarin Android app
<p>I want to load a <code>.tflite</code> model on my Xamarin Android app.</p> <p>I've tried loading it with TensorFlow <code>Interpreter</code></p> <pre><code>var file = new Java.IO.File("C:\\Users\\Jaime\\source\\repos\\IdentificadorImagenesSolution\\IdentificadorImagenes\\IdentificadorImagenes.Android\\Assets\\dete...
<p>Got help from this <a href="https://stackoverflow.com/questions/52889099/xamarin-tf-lite-input-objects">question</a></p> <pre><code>{ var assets = Application.Context.Assets; AssetFileDescriptor fileDescriptor = assets.OpenFd("detect.tflite"); FileInputStream inputStream = new FileInputStream(fileDescri...
tensorflow|xamarin.forms|xamarin.android|tensorflow-lite
1
369,941
59,132,001
populating a new column based on certain conditions and shift operation and group by
<p>I have a dataframe that looks something like </p> <pre><code>LastName Date ObjectCol1 ObjectCol2 NumCol1 NumCol2 CurrentState ExpectedState ABC March A1 A2 ABC June A1 A2 XYZ March ...
<pre><code>df['Pre-result'] = df.groupby(['LastName'])['CurrentState '].shift(-1) df['Result'] = np.where(df['Pre-result'] == df['ExpectedState'], "Hit", "Miss") df['Result'] = np.where(df['Pre-result'].isna(), "Yet to be seen", df['Result']) del df['Pre-result'] LastName Date ObjectCol1 ObjectCol2 NumCol1 NumCol2...
python|pandas
0
369,942
59,160,337
How to extract only the pixels of an image where it is masked? (Python numpy array operation)
<p>I have an image and its corresponding mask for the cob as numpy arrays:</p> <p><a href="https://i.stack.imgur.com/KDryM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KDryM.jpg" alt="image"></a></p> <p><a href="https://i.stack.imgur.com/9dxsT.jpg" rel="nofollow noreferrer"><img src="https://i.s...
<p>Thanks to the useful comment of M.Setchell, I was able to find the answer myself.</p> <p>Basically, I had to expand the dimensions of the mask array (2D) to the same dimension of the image (3D with 3 color channels).</p> <pre><code>y=np.expand_dims(mask,axis=2) newmask=np.concatenate((y,y,y),axis=2) </code></pre> ...
python|image|numpy|mask
5
369,943
59,404,101
Error trying to train the neural network - 'Namespace' object has no attribute 'steps_for_validation'
<p>I am following a tutorial called "Object Detection on Custom Dataset with TensorFlow 2 and Keras using Python" </p> <p>I'm working on colab at this <a href="https://colab.research.google.com/drive/1ldnii3sGJaUHPV6TWImykbeE_O-8VIIN" rel="nofollow noreferrer">link</a> <a href="https://colab.research.google.com/drive/...
<p>There is a problem with <code>train.py</code> file of <code>keras-retinanet</code> library.</p> <p>If you look at its code, while parsing the arguments in <code>parse_args</code> function, they have added default values for all the parameters using <code>parser.add_argument()</code> function except for <code>steps_...
python|python-3.x|tensorflow|keras|object-detection
0
369,944
59,043,604
Python - Converting dollar values to float
<p>I have sales data that is stored as a string. i'm trying to convert to a float so that I can aggregate the data but I'm receiving the following error "ValueError: could not convert string to float: 'revenue'. </p> <p>I also tried to replace the dollar signs and commas but the type is still string. </p> <pre><code...
<p>You have to use <code>regex=True</code> and <code>\$</code> because <code>$</code> has special meaning in <code>regex</code>.<br> You have to also remove <code>,</code>. </p> <pre><code>import pandas as pd df = pd.DataFrame({'revenue': ["$1,557.97 "]}) df['revenue'] = df['revenue'].replace('\$|,', '', regex=True)...
python|string|pandas|floating-point
5
369,945
59,065,339
Vectorization of nested for loop in Python
<p>I have the following nested for loop (randoms for simplicity):</p> <pre><code>import numpy as np lat_idx = np.random.randint(121, size = 4800) lon_idx = np.random.randint(201, size = (4800,4800)) sum_cell = np.zeros((121,201)) data = np.random.rand(4800,4800) for j in range(4800): for i in range(4800): ...
<p>This is how you can do that in a vectorized way:</p> <pre><code>import numpy as np # Make input data np.random.seed(0) data = np.random.rand(4800, 4800) # Add some negative values in indices lat_idx = np.random.randint(-20, 121, size=4800) lon_idx = np.random.randint(-50, 201, size=(4800, 4800)) # Output array sum...
python|numpy|for-loop|vectorization
1
369,946
59,340,022
Efficient way of running Django query over list of dates
<p>I am working on an investment app in Django which requires calculating portfolio balances and values over time. The database is currently set up this way: </p> <pre class="lang-py prettyprint-override"><code>class Ledger(models.Model): asset = models.ForeignKey('Asset', ....) amount = models.FloatField(...)...
<p>I think this might take some back and forth. I think the best approach is to do this in a couple steps.</p> <p>Let's start with getting asset balances daily and then we will merge the prices together. The transaction amount is a cumulative total. Does this look correct? I don't have your data so it is a little ...
django|pandas
1
369,947
59,305,639
Improve performance of exponentiation
<p>I have a rather simple function (see code below) which is employed by an MCMC, meaning it is called millions of times. For what I can tell, most of the time is consumed exponentiating arrays and I can't think of a way to improve its performance. It currently eats up ~15% of the total MCMC runtime, so every bit of im...
<p>You could Numba for improving performance. With quite simple changes to the code (writing simple loops, avoiding lists,...) you could easily get a significant speedup.</p> <p><strong>Example</strong></p> <pre><code>import numba as nb import numpy as np emax = np.array([.05, .1, .17]) abc = np.array([ [0.01068...
python|performance|numpy
1
369,948
14,187,335
python to cython - eliminate python calls
<p>I'm currently trying to convert the following loops to cython:</p> <pre><code>cimport numpy as np cimport cython @cython.boundscheck(False) # turn of bounds-checking for entire function def Interpolation(cells, int nmbcellsx): cdef np.ndarray[float, ndim=1] x,y,z cdef int i,j,len for i in range(nmbcells...
<p>You aren't telling <strong>Cython</strong> the type of your <code>cells</code> argument and thus it will use the <strong>Python</strong> look up methods. Try changing the definition to the following:</p> <p><code>def Interpolation(np.ndarray cells, int nmbcellsx):</code></p> <p>This will tell <strong>Cython</stron...
python|numpy|cython
2
369,949
14,197,088
Spilt value from a column in a DataFrame using Python
<p>I have a data frame with 4 columns..</p> <pre><code>A B C D e 2 = &lt;0.1 e 2 = &lt;0.11 e 2 = 0.1 e 2 = 0.1 e 2 = 0.1 e 2 = &lt;0.14 </code></pre> <p>Column D has some float values starting with '&lt;' and some are without '&lt;'.</p...
<p>Something like this should do it, if I understand you correctly. This is very quick and dirty, untested. Reads the named file, prints to stdout:</p> <pre><code>for l in open("file.txt").readlines(): l = l.strip() fields = l.split(" ") if len(fields) != 4: continue if fields[3][0] == "&lt;": fields[2] = ...
python|numpy|python-2.7|dataframe|pandas
0
369,950
14,110,721
How to change Pandas dataframe index value?
<p>I have a <code>df</code>:</p> <pre><code>&gt;&gt;&gt; df sales cash STK_ID RPT_Date 000568 20120930 80.093 57.488 000596 20120930 32.585 26.177 000799 20120930 14.784 8.157 </code></pre> <p>And want to change first row's index value from <code>('000568','201209...
<p>With this setup:</p> <pre><code>import pandas as pd import io text = '''\ STK_ID RPT_Date sales cash 000568 20120930 80.093 57.488 000596 20120930 32.585 26.177 000799 20120930 14.784 8.157 ''' df = pd.read_csv(io.BytesIO(text), delimiter = ' ', converters = {0:str}) df.set_index(['STK_ID','RPT_...
python|pandas
22
369,951
45,031,500
Simply changing dimention of input layer from 2 to 10
<p>This is my first code which works well.</p> <p>Inputs are 2 dimensions and outputs are 2 dimensions</p> <p>First Code:</p> <pre><code>w = tf.Variable(tf.zeros([2,1])) b = tf.Variable(tf.zeros([1])) x = tf.placeholder(tf.float32,shape=[None,2]) t = tf.placeholder(tf.float32,shape=[None,1]) y = tf.nn.sigmoid(tf.m...
<p>You are feeding the wrong shapes as inputs to the <code>placeholders</code>. You have changed your dimension of <code>x</code> in the placeholder but feeding it the wrong input <code>X</code> (which you have not changed) but instead of <code>y</code> (which you have changed). So either swap X, y or change the approp...
tensorflow
1
369,952
45,170,391
Combining multiple dataframes side by side and renaming them
<p>I have multiple data frames in my analysis. For example dataframe 1 where this is the number of people by activity in China</p> <pre><code>Activity No of people Activity 1 100 Activity 2 200 Activity 3 300 </code></pre> <p>and data frame 2 where this is the number...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>.</p> <p>If <code>Activity</code> are indexes in both dataframes use:</p> <pre><code>df = pd.concat([df1, df2], axis=1, keys=('China Analysis','America Analysis')) </code></pre> ...
python|pandas
3
369,953
45,070,233
The mechanism of auto inserting in Pandas Dataframe when selecting rows by index
<p>I noticed a mechanism of auto inserting when selecting rows by index. To illustrate, I use the following code:</p> <p><a href="https://i.stack.imgur.com/s8R7R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s8R7R.png" alt="enter image description here"></a></p> <p>Then my questions are 2 (may be...
<p>I have not seen any documentation. It looks like an unintended artifact. I can think of some clever things to do with it but I wouldn't trust it. </p> <p>Work around</p> <pre><code>df1.loc[pd.Index([1, 'a']).intersection(df1.index), :] </code></pre>
pandas|dataframe
2
369,954
45,035,628
list of files available in hdfs recursive directory and sub directory lookup using python and generating pandas dataframe
<p>Is there any way to list all <strong>Files</strong> (only) from given directory (which may contain sub-directories too) under <strong>HDFS</strong> using python function? and finally, generate pandas data frame with a list of all those available files? </p> <p>I have tried using <strong>pywebhdfs</strong> but it on...
<p>There are many client libraries like hdfs3 and hdfsCLI that can be used for the purpose. A sample on how you can achieve it through hdfsCLI</p> <pre><code>from hdfs import Config import posixpath as psp client = Config().get_client('dev') fnames = client.list('/cdc') print(fnames) fpaths = [ psp.join(dpath, fn...
python|pandas|hdfs
1
369,955
44,942,236
Not initialized variable in tensorflow
<p>I am trying to write a machine learning program. The idea was to train a model (defined in <em>q_model</em>) which could be trained with RMSProp. I report here a really simplified version of my code, which is not working. </p> <pre><code>import tensorflow as tf import numpy as np #---------------------------------...
<p>You need to put this piece of code:</p> <pre><code>init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) </code></pre> <p>after having created these tensors:</p> <pre><code>y_batch , x_batch, a_batch = tf.placeholder("float64",shape=(None,1), name='y'), tf.placeholder("float64",shape=(None,2), ...
machine-learning|tensorflow|training-data
2
369,956
45,219,736
Tensorflow - batch_normalizaiton layers
<p>I try to build some neural networks and I would like to use batch_normalization before activation functions but I have some problems. I'm not sure if I use these layers correctly.</p> <pre><code>graph = tf.Graph() with graph.as_default(): x = tf.placeholder(tf.float32, shape=(batch_size, image_width, image_hei...
<p>In a line you're defining <code>x</code> as a placeholder</p> <pre><code>x = tf.placeholder(tf.float32, shape=(batch_size, image_width, image_height, image_depth), name='x') </code></pre> <p>some line next, you override the <code>x</code> variable with the result of the <code>batch_normalization</code> function ca...
python|machine-learning|tensorflow
2
369,957
44,937,007
Tensorflow LinearClassifier() always guesses negative class
<p>I'm currently implementing a logistic regressor using tensorflow according to their 'wide' tutorial: <a href="https://www.tensorflow.org/tutorials/wide" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/wide</a><br> My code pretty much matches the tutorial, however, when I run predict() on the model, it...
<p>I guess, you need to add cross_columns to make our linear model works better.</p>
python|flask|machine-learning|tensorflow|logistic-regression
0
369,958
44,942,285
My Double DQN algorithm for 2048 game never learns
<p>I am trying to make Double-DQN algorithm to learn play 2048 game. My implementation is available in GitHub if you want to check the code. (<a href="https://github.com/codetiger/MachineLearning-2048" rel="nofollow noreferrer">https://github.com/codetiger/MachineLearning-2048</a>)</p> <p>My code is not learning after...
<p>My two cents,</p> <ul> <li><p>RL algorithms don't learn randomly. I suggest you take a look at 'Sutton and Barto (Second Edition)' for a detailed description of the wide variety of algorithms. Having said that I don't think the git code that you linked does what you expect (Why do you have an ES module? Are you tra...
machine-learning|tensorflow|artificial-intelligence|keras|reinforcement-learning
2
369,959
45,157,589
Can we explicitly specify what feature to be extracted from an image while using CNN
<p>Last day I learned about the convolution neural network, And went through some implementations of CNN using Tensorflow, All the implementation only specify the size, number of filters and strides for the filter. But when I learned about the filter it says that filter on each layer extracts different feature like edg...
<blockquote> <p>can we explicitly specify filter which all feature we should extract, Or which portion for the image is more important etc</p> </blockquote> <p>Sure, this could be done. But the advantage of CNNs is that they learn the best features themselves (or at least very good ones; better ones than we can come up...
machine-learning|tensorflow|computer-vision|deep-learning|conv-neural-network
4
369,960
45,031,524
Pandas - unstack/pivot with multiple index
<p>I have a melted DataFrame I would like to pivot but cannot manage to do so using 2 columns as index.</p> <pre><code>import pandas as pd df = pd.DataFrame({'A': {0: 'XYZ', 1: 'XYZ', 2: 'XYZ', 3: 'XYZ', 4: 'XYZ', 5: 'XYZ', 6: 'XYZ', 7: 'XYZ', 8: 'XYZ', 9: 'XYZ', 10: 'ABC', 11: 'ABC', 12: 'ABC', 13: 'ABC', 14: 'ABC', ...
<p>Is that what you want?</p> <pre><code>In [23]: df.pivot_table(index=['A','B'], columns='C', values='D', aggfunc='first') Out[23]: C Price Trading A B ABC 01/01/2017 50 Yes 02/01/2017 NaN No 03/01/2017 48 Yes 04/01/2017 47 Yes 05/01/2017 46 Yes XYZ 01...
python|pandas|pivot
2
369,961
45,090,567
Pandas: Parsing dates in different columns with read_csv
<p>I have an ascii file where the dates are formatted as follows:</p> <pre><code>Jan 20 2015 00:00:00.000 Jan 20 2015 00:10:00.000 Jan 20 2015 00:20:00.000 Jan 20 2015 00:30:00.000 Jan 20 2015 00:40:00.000 </code></pre> <p>When loading the file into pandas, each column above gets its own column in a pandas dataframe....
<p>Have a go to this simpler approach:</p> <pre><code>df = pandas.read_csv('file.txt') df.columns = ['date'] </code></pre> <p><code>df</code> should be a dataframe with a single column. After that try casting that column to datetime</p> <pre><code>df['date'] = pd.to_datetime(df['date']) </code></pre>
python|pandas|parsing|datetime|dataframe
5
369,962
45,069,761
Tensorflow Convolution with Different Filter Sizes
<p>I would like to convolve over my data feed with filters of different sizes and was wondering how I can achieve the following setup using Tensorflow <a href="https://i.stack.imgur.com/X14SR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X14SR.png" alt="enter image description here"></a></p> <p>In...
<p>Assume batch size 100 and image data of size 28x28x1. </p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf inp = tf.placeholder(tf.float32, shape=[100, 28, 28, 1]) left_branch = tf.layers.conv2d(input=inp, filters=N, kernel_size=[L, M]) right_branch = tf.layers.conv2d(input=inp, filters=...
python|tensorflow|conv-neural-network|convolution
2
369,963
44,917,319
TypeError: an integer is required in pd.merge python
<p>I'm trying to combine two panda dataframes as shown below</p> <p>df_aviris</p> <pre><code> 0 1 2 3 4 0 0.0 0.0 0.0 482636.5 4155009.5 1 0.0 0.0 0.0 482637.5 4155009.5 2 0.0 0.0 0.0 482638.5 4155009.5 3 0.0 0.0 0.0 482639.5 4155009.5 ...
<p>There is problem no <code>x</code> and <code>y</code> column in <code>df_aviris</code>.</p> <p>So need for <code>outer</code> join:</p> <pre><code>DFinal = pd.merge(df_aviris,df_geomap,how='outer',left_on=[3,4], right_on=['x','y']) </code></pre> <hr> <pre><code>#default outer join, join='outer' can be omit DFina...
python|arrays|pandas|merge
1
369,964
44,888,415
How to set k-Means clustering labels from highest to lowest with Python?
<p>I have a dataset of 38 apartments and their electricity consumption in the morning, afternoon and evening. I am trying to clusterize this dataset using the k-Means implementation from scikit-learn, and am getting some interesting results.</p> <p>First clustering results: <img src="https://i.stack.imgur.com/NRPvx.pn...
<p>Transforming the labels through a <strong>lookup table</strong> is a straightforward way to achieve what you want. </p> <p>To begin with I generate some mock data:</p> <pre><code>import numpy as np np.random.seed(1000) n = 38 X_morning = np.random.uniform(low=.02, high=.18, size=38) X_afternoon = np.random.unifo...
python|sorting|numpy|scikit-learn|k-means
21
369,965
44,973,184
Train Tensorflow Object Detection on own dataset
<p>After spending a couple days trying to achieve this task, I would like to share my experience of how I went about answering the question:</p> <p><em>How do I use <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="noreferrer">TS Object Detection</a> to train using my own datase...
<p>This assumes the module is already installed. Please refer to their <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md" rel="noreferrer">documentation</a> if not.</p> <p><strong>Disclaimer</strong></p> <p>This answer is not meant to be the <em>right</em> or <e...
machine-learning|tensorflow|object-detection
54
369,966
44,864,655
Pandas difference between apply() and aggregate() functions
<p>is there any difference in the (type) of the return value between the DataFrame.aggregate() and the DataFrame.apply() function if I just pass a function like </p> <pre><code>func=lambda x: x**2 </code></pre> <p>because the return values seems to be pretty the same. And the documentation only tells:</p> <blockquot...
<p>There are two versions of agg (short for aggregate) and apply: The first is defined on groupby objects and the second one is defined on DataFrames. </p> <p>If you consider <code>groupby.agg</code> and <code>groupby.apply</code>, the main difference would be that the apply is flexible (<a href="http://pandas.pydata...
python|pandas
11
369,967
45,068,853
How does this one-hot vector conversion work?
<p>When I was working on my machine learning project, I was looking for a line of code to turn my labels into one-hot vectors. I came across this nifty line of code from u/benanne on Reddit. </p> <pre><code>np.eye(n_labels)[target_vector] </code></pre> <p>For example, for a <code>target_vector = np.array([1, 4, 2, 1,...
<p>It's rather simple. <code>np.eye(n_labels)</code> creates an identity matrix of size <code>n_labels</code> then you use your <code>target_vector</code> to select rows, corresponding to the value of the current target, from that matrix. Since each row in an identity matrix contains exactly one <code>1</code> element ...
python|numpy|matrix|vector
9
369,968
44,918,756
Send html table in outlook mail via Python
<p>I have a code which uses win32com to open Outlook and send mail. I am trying to send a table which is in myexample.html file to a recipient. However when I use </p> <pre><code>msg.body=open('myexample.html').read() </code></pre> <p>This is what comes in the mail that I've sent </p> <pre><code>table border="1" c...
<p>Figured out the answer to it. Just need to alter </p> <pre><code>msg.body = body </code></pre> <p>to </p> <pre><code>msg.HTMLBody = body </code></pre>
html|python-2.7|pandas|outlook|win32com
0
369,969
44,959,435
How to make the weights of an RNN cell untrainable in Tensorflow?
<p>I'm trying to make a Tensorflow graph where part of the graph is already pre-trained and running in prediction mode, while the rest trains. I've defined my pre-trained cell like so:</p> <pre><code>rnn_cell = tf.contrib.rnn.BasicLSTMCell(100) state0 = tf.Variable(pretrained_state0,trainable=False) state1 = tf.Varia...
<p>You can use either <code>tf.stop_gradient()</code> to prevent the <code>pretrained</code> parts of the graph from updating its weights or you can use the <code>optimiser()</code> where you can specify which parts of the graph should be trained. The second method would involve:</p> <pre><code> #Create variable scope...
machine-learning|tensorflow|deep-learning|recurrent-neural-network
3
369,970
44,997,208
Concatenate CSV files with pandas
<p>l have csv files to concatenate. l have three files l want to concatenate. The number of columns is the same so the desired output will have also the same columns </p> <p>file1.csv </p> <pre><code>id ocr raw_value manual_raw_value 2a909d6e-5eb2-49a1-b6e8-171bf01dafdc A...
<p>Your csv has uneven spacing. This can be handled easily. When reading in your data, set <code>delim_whitespace=True</code>. </p> <pre><code>In [1335]: list_ = [] ...: for file in glob.glob('*.csv'): ...: df = pd.read_csv(file, index_col=None, header=0, delim_whitespace=True) ...: print('Si...
python|pandas|csv|dataframe|concatenation
1
369,971
45,008,562
Custom groupby query in Pandas, Python in which the constrains depend on multiple rows
<p>I have 2 fields Phone number and Email. I want to group rows which are from the same person, that is, either the Phone number or Email must be the same.</p> <p>Can I use groupby for this? I have already made a looping algorithm which uses dictionary etc.</p> <p>Example: </p> <pre><code>index phone email 0 ...
<p>Load the data into a graph. For example, using <a href="https://networkx.github.io/" rel="nofollow noreferrer">networkx</a>,</p> <pre><code>G = nx.from_pandas_dataframe(df, 'email', 'phone', 'index') </code></pre> <p>creates a graph with an edge between each <code>email</code> and <code>phone</code> listed in the ...
python|pandas
3
369,972
45,133,276
Passing C++ vector to Numpy through Cython without copying and taking care of memory management automatically
<p>Dealing with processing large matrices (NxM with 1K &lt;= N &lt;= 20K &amp; 10K &lt;= M &lt;= 200K), I often need to pass Numpy matrices to C++ through Cython to get the job done and this works as expected &amp; without copying. </p> <p><strong>However</strong>, there are times when I need to initiate and preproces...
<p>I think @FlorianWeimer's answer provides a decent solution (allocate a <code>vector</code> and pass that into your C++ function) but it should be possible to return a vector from <code>doit</code> and avoid copies by using the move constructor.</p> <pre><code>from libcpp.vector cimport vector cdef extern from "&lt...
python|c++|numpy|cython
13
369,973
45,119,592
calculating length of several files in pandas using for loop
<p>I have five data frames <code>(df1, df2, df3, df4, df5)</code>, and I am going to calculate their lengths using the following code: </p> <pre><code>df1 = pd.read_excel("/Users/us/Desktop/cymbalta_rated_1.xlsx") df2 = pd.read_excel("/Users/us/Desktop/cymbalta_rated_2.xlsx") df3 = pd.read_excel("/Users/us/Desktop/cym...
<p>There are no dynamic variable names in Python - so <code>dfi</code> refers to a variable explicitly called <code>dfi</code>. It doesn't change to <code>df1</code> just because <code>i</code> is <code>1</code> (or something else).</p> <p>In your case you could simply iterate over a sequence of the dataframes:</p> <...
python|pandas
3
369,974
45,207,488
How to get data from multiple columns and save it in a list using pandas?
<p>I need help to get data from some columns into a list.</p> <p>Lets say I have this <code>test.txt</code> file</p> <pre><code>30012 820202 999201 81910 882101 100291 88271 003300 221920 93929 719300 </code></pre> <p>I want to save data from even and odd columns in a seperate list.</p> <p>I tr...
<p>You can convert <code>df</code> to <code>arrays</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html" rel="nofollow noreferrer"><code>values</code></a>, then select columns and use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html" rel="no...
python|pandas
1
369,975
45,112,856
Numpy Array, Data must be 1-dimensional
<p>I am attempting to reproduce MatLab code in Python and am stumbling with a MatLab matrix. The block of code in MatLab is below:</p> <pre><code>for i = 1:Np y = returns(:,i); sgn = modified_sign(y); X = [ones(Tp,1) sgn.*log(prices(:,i).*volumes(:,i))]; </code></pre> <p>I am having a hard time creating...
<p>The problem is that numpy can have 1D array (vectors) while MATLAB cannot. So when you create the <code>np.ones([Tp,1])</code> array, it is creating a 2D array where one dimension has a size of 1. In MATLAB, that is considered a "vector", but in numpy it isn't.</p> <p>So what you need to do is give <code>np.ones</c...
python|matlab|pandas|numpy
5
369,976
56,934,392
Selecting all columns in DataFrame.set_index except one
<p>As the title says, I'm trying to select all columns except one in <code>DataFrame.set_index</code>.</p> <p>I tried the following way:</p> <pre><code>df = df.set_index(list(df.columns != 'cus_name')) </code></pre> <p>The <code>cus_name</code> Series is the one I want to exclude. The above code raise a <code>KeyEr...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.Index.difference.html" rel="noreferrer"><code>pd.Index.difference()</code></a> here with <code>sort=False</code> if order is important:</p> <pre><code>df=df.set_index(df.columns.difference(['cus_name'],sort=False).tolist())...
python|pandas
5
369,977
57,083,474
When adding a DataFrame column default value, how do I limit it to specific rows?
<p>I am using a combination of beautifulsoup and pandas to try and get sports reference data by looping through boxscore pages, obtaining the dataframes for each team and concatenating them all together. I noticed that the way the table is formatted on each page, there are row dividers separating the starters from the ...
<p>You can do this in three steps:</p> <ol> <li>Set the default value 'N' for the entire column using <code>away_team_stats['Starter']='N'</code></li> <li>Set the value for the first x rows to be 'Y' using the <code>iloc</code> method with <code>away_team_stats.iloc[:x, 2]='Y'</code> (I believe the 'Starter' column wi...
python|pandas|beautifulsoup
0
369,978
57,284,097
Expand/create pandas columns from grouped rows by concatenating subid value and other column names
<p>I would like to create new columns from a panda dataframe by grouping based on a column and concatenating a subindex (in another column) with two other column names. This is best illustrated with an example. Say this is my input dataframe:</p> <pre><code> filename sub_id x y 0 2019-07-29...
<p>Yet another method:</p> <pre><code># create the columns for x0, x1, y0, y1 df_unstacked= df.set_index(['filename', 'sub_id']).unstack(-1) # rename the column df_unstacked.columns= [''.join(map(str, c_tup)) for c_tup in df_unstacked.columns] </code></pre> <p>The result is</p> <pre><code> x...
pandas|join|pandas-groupby
2
369,979
57,119,310
How to calculate kendall's tau for a large spark dataframe in python?
<p>I would like to calculate the pairwise kendall's tau rank correlation for a large spark dataframe. It's large (say 10m rows with 10k columns) that can't be converted to pandas dataframe and then calculate using pandas.DataFrame.corr.</p> <p>Also, each column may have null values, thus when calculating the pairwise ...
<p>Kendalls's rank is not yet supported in Spark. However, if this is not too late for you, I found the following <a href="https://github.com/guy4261/spark_operators_hw" rel="nofollow noreferrer">code </a> that you can use to calculate it. </p> <p>Here an example:</p> <pre><code>from operator import add #sample da...
python|pandas|apache-spark|pyspark|correlation
1
369,980
57,283,395
How I can fix this statement, my code does not work with tensorflow?
<p>I have some problems in my code, but I can not know how to fix it. I have target: y = x/3 - 8. Input: X_train: an array of floats from -10 to 10, Y_train: an array is created from target and a little bit noise I added. I used gradient descent for optimization of loss function.</p> <pre><code>import tensorflow as tf...
<p>if you move the <code>print()</code> line in the for-loop you can get a better idea of what's going on:</p> <pre><code>W: [18.353216] b: [-16.890762] loss: 1247183.4 W: [-1346.8429] b: [24.758984] loss: 6829195000.0 W: [99991.945] b: [-1827.1696] loss: 37613004000000.0 W: [-7420763.] b: [134402.12] loss: 2.0716051e...
python|python-3.x|tensorflow|linear-regression
1
369,981
57,048,064
saved_model.prune() in TF2.0
<p>I am trying to prune nodes of a <code>SavedModel</code> that was generated with tf.keras. The pruning script is as follows:</p> <pre><code>svmod = tf.saved_model.load(fn) #version 1 #svmod = tfk.experimental.load_from_saved_model(fn) #version 2 feeds = ['foo:0'] fetches = ['bar:0'] svmod2 = svmod.prune(feeds=feeds,...
<p>It looks like the way you are pruning the model in version 1 is fine; according to your error message, the resulting pruned model cannot be saved because it is not "trackable", which is a necessary condition for saving a model with <code>tf.saved_model.save</code>. One way to make a trackable object is to inherit fr...
python|tensorflow|tf.keras
3
369,982
57,142,876
Trying to create a facet graph from aggregated data using a pandas Dataframe using Plotly
<p>I want to use Plotly to create a facet graph, however the code I'm using keeps returning an attribute error and I am not sure how to address the Dataframe in the code</p> <p>So I have been able to aggregate the data for specific details and I can use a loop to print out several graphs using Matplotlib.</p> <p>The ...
<p>You misinterpreted the <a href="https://plot.ly/python/facet-plots/" rel="nofollow noreferrer">facet plot docs</a> as <em>tips</em> is a built-in dataset maintained inside the <code>plotly_express</code> module, likely included for demo purposes. </p> <pre><code>import plotly.express as px tips = px.data.tips() ...
python|pandas|plotly|facet
0
369,983
57,177,605
Dataframe pivot without sorting the column names?
<p>Original data :-</p> <pre><code>date variable value 2017 A 1 2017 C 1 2017 B 2 2018 A 1 2018 C 1 2018 B 2 </code></pre> <p>My pivot Result :-</p> <pre><code>date A B C 2017 1 2 1 2018 1...
<p>You can achieve this with <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.Categorical.html" rel="nofollow noreferrer"><code>pd.Categorical</code></a>:</p> <pre><code>df.variable=pd.Categorical(df.variable,categories=df.variable.unique(),ordered=True) df.pivot_table(index='date',column...
python|pandas|dataframe
2
369,984
57,098,084
Pandas combine VLOOKUP and HLOOKUP or how to pick a value in a matrix
<p>In my <a href="https://stackoverflow.com/questions/56987731/compare-values-in-a-matrix-with-a-threshold-and-create-a-list-of-exceeding-it">previous task</a> I needed to create a list based on threshold and it was solved. I then needed to complete it with next steps but I thought it would be helpful to create a separ...
<p>Use:</p> <p>@Erfan suggests:</p> <pre><code>df['new_col'] = matrix.set_index('id').lookup(df['id'], df['class']) </code></pre> <p>Which is better than my original statement below:</p> <pre><code>matrix = matrix.set_index('id') df['new_col'] = matrix.lookup(df['id'], df['class']) df </code></pre> <p>OUtput:</p...
python|pandas
2
369,985
57,182,358
Iterate over integers in Bayesian Optimization package Python
<p>I use Bayesian Optimization package (<a href="https://github.com/fmfn/BayesianOptimization" rel="nofollow noreferrer">https://github.com/fmfn/BayesianOptimization</a>) for parameter optimization. By default this library iterate over float points number but i neet iterate over integers, how can i perform that?</p> ...
<p>You may read part 2 of the <a href="https://github.com/fmfn/BayesianOptimization/blob/master/examples/advanced-tour.ipynb" rel="nofollow noreferrer">advanced tour</a> for this.</p>
python|numpy|bayesian
2
369,986
56,888,491
TensorFlow "Please provide as model inputs a single array or a list of arrays"
<p><a href="https://i.stack.imgur.com/Kga7B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kga7B.png" alt="enter image description here"></a></p> <p>This is the error and data I entered into my model. I just can't figure out why it won't work since the dimensions are okay and it literally prints a ...
<p>You need an input layer to your model:</p> <pre><code>... model = Sequential() model.add(Dense(15, activation='linear', input_shape=( len(training_inputs[0]),))) model.add(Dense(15, activation='linear')) ... </code></pre>
python|tensorflow|keras
1
369,987
57,238,583
How to clean up text data type in a numeric column in Pandas?
<p>I have a data set with numeric data column which contains some text. </p> <p>For example let's say I have a column of numbers from 1 to 10 but instead of 10 I have it in text as "ten". </p> <p>I was trying to use unique() method on the column to identify the inconsistent data and clean the same. </p> <p>The curre...
<p>Programming languages have no inherent concept that certain strings correspond to certain numbers, so you would have to programmatically parse each string and determine the corresponding number. </p> <p>The best answer I could find for this part was here: <a href="https://stackoverflow.com/questions/493174/is-there...
sklearn-pandas
1
369,988
57,161,576
PyTorch Binary Classification - same network structure, 'simpler' data, but worse performance?
<p>To get to grips with PyTorch (and deep learning in general) I started by working through some basic classification examples. One such example was classifying a non-linear dataset created using sklearn (full code available as notebook <a href="https://github.com/philipobrien/colab-notebooks/blob/master/Non_Linear_Dat...
<h3>TL;DR</h3> <p>Your input data is not normalized.</p> <ol> <li>use <code>x_data = (x_data - x_data.mean()) / x_data.std() </code></li> <li>increase the learning rate <code>optimizer = torch.optim.Adam(model.parameters(), lr=0.01)</code></li> </ol> <p>You'll get<br /> <a href="https://i.stack.imgur.com/vt4VK.png" rel...
python|machine-learning|deep-learning|artificial-intelligence|pytorch
17
369,989
57,041,305
Keras : Shuffling dataset while using LSTM
<p>Correct me if I am wrong but according to the official <a href="https://keras.io/models/sequential/" rel="noreferrer">Keras documentation</a>, by default, the fit function has the argument 'shuffle=True', hence it shuffles the whole training dataset on each epoch.</p> <p>However, the point of using recurrent neural...
<blockquote> <p>If we shuffle all the data, all the logical sequences are broken.</p> </blockquote> <p>No, the shuffling happens on the batches axis, not on the time axis. Usually, your data for an RNN has a shape like this: <code>(batch_size, timesteps, features)</code></p> <p>Usually, you give your network not on...
tensorflow|keras|lstm|shuffle|recurrent-neural-network
16
369,990
57,291,826
Using an or statement in a conditional list comprehension to filter columns in a dataframe
<p>I'm trying to filter my columns in dataframe that contain the letters "R" or "H". </p> <p>The code works when I only search for 1 of the letters but it's returning all the columns when I add an <code>or</code> statement. </p> <p>I was wondering if it was possible to use the or in a list comprehension. Here is my c...
<p>How about:</p> <pre><code>cols = df.columns[df.columns.str.contains('RB|H')] </code></pre>
python|pandas|list|conditional-statements
3
369,991
56,898,239
PyTroch, Gradient calculations
<p><a href="https://colab.research.google.com/github/pytorch/tutorials/blob/gh-pages/_downloads/neural_networks_tutorial.ipynb" rel="nofollow noreferrer">https://colab.research.google.com/github/pytorch/tutorials/blob/gh-pages/_downloads/neural_networks_tutorial.ipynb</a></p> <p>Hi I am trying to understand the NN wit...
<p>When you created the optimizer in this line</p> <pre><code>optimizer = optim.SGD(net.parameters(), lr=0.01) </code></pre> <p>You provided <code>net.parameters()</code> with all learnable parameters that will be updated, based on gradients.</p> <p>The model and the optimizer are connected only because they share t...
pytorch|gradient
2
369,992
57,217,927
How to output html table with merged cells from pandas DataFrame
<p>I have a pandas.DataFrame df as:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame([[1,2,2,2,3], [1,2,3,3,3],[1,3,2,3,5],[7,9,9,3,2]], columns=list("ABCDE")) </code></pre> <p><a href="https://i.stack.imgur.com/8TNpH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8TNpH.png" alt="dataframe presented ...
<p>UPDATE: I've managed to find <a href="https://stackoverflow.com/questions/49533330/pandas-data-frame-how-to-merge-columns">similar question</a>, with extensive answer (see <strong>jpp</strong>'s answer), yet unfortunately negating possibility of simple solution to my problem. As <a href="https://stackoverflow.com/us...
python|html|pandas|dataframe
3
369,993
56,955,037
PyTorch broadcasting: how this worked?
<p>I'm new to Deep Learning. I'm studying from Udacity.</p> <p>I came across one of the codes to build up a neural network, where 2 tensors are being added, specifically the 'bias' tensor with the output of the tensor-multiplication product.</p> <p>It was kind of...</p> <pre><code>def activation(x): return (1/(1+tor...
<p>64 is your batch size, meaning that the bias tensor will be added to each of the 64 examples inside of your batch. Basically it's like if you took 64 tensor of size 256 and added the bias to each of them. Pytorch will naturally broadcast the 256 tensor to a 64*256 size that can be added to the 64*256 output of your ...
python|machine-learning|pytorch
1
369,994
57,266,132
Create common columns and transform time series like data
<p>I have an excel sheet which contains more than 30 sheets for different parameters like BP, Heart rate etc. </p> <p>One of the dataframe (df1 - created from one sheet of excel) looks like as shown below</p> <pre><code>df1= pd.DataFrame({'person_id':[1,1,1,1,2,2,2,2,3,3,3,3,3,3],'level_1': ['H1Date','H1','H2Date','H...
<p>Here is one way using <code>unstack()</code> with a little modification:</p> <p>Assign a dummy column using ,<code>df1.groupby(['person_id',df1.level_1.str[:2]]).cumcount()</code></p> <p>Change <code>level_1</code> to <code>level_1=df1.level_1.str[:2]</code></p> <p>Set index as <code>['person_id','level_1','k']</...
python|python-3.x|pandas|list|dataframe
1
369,995
57,180,937
How to flatten a 3 dimensional array
<p>I use Pyaudio to record multichannel signal (2 for example) by appending each 2-dimensional list together. Now I would like to find an efficient way to flatten the signal to one single 2 dimensional array:</p> <p>For example, input is :</p> <pre><code>i = [[[ 1, 2], [ 1, 2], [ 1, 2]], [[ 3, ...
<p>Use <code>np.concatenate</code>:</p> <pre><code>print(np.concatenate(i, 0)) </code></pre> <p>Output:</p> <pre><code> [[1 2] [1 2] [1 2] [3 4] [3 4] [3 4]] </code></pre>
python|numpy
2
369,996
57,225,782
Converting a string representation of dicts to an actual dict
<p>I have a CSV file with 100K+ lines of data in this format:</p> <pre><code>"{'foo':'bar' , 'foo1':'bar1', 'foo3':'bar3'}" "{'foo':'bar' , 'foo1':'bar1', 'foo4':'bar4'}" </code></pre> <p>The quotes are there before the curly braces because my data came in a CSV file.</p> <p>I want to extract the key value pairs i...
<p>You can turn a dictionary into a pandas dataframe using pd.DataFrame.from_dict, but it will expect each value in the dictionary to be in a list. </p> <pre class="lang-py prettyprint-override"><code>for key, value in parsed.items(): parsed[key] = [value] df = pd.DataFrame.from_dict(parsed) </code></pre> <p>You ...
python|python-3.x|pandas
0
369,997
56,985,321
how to split a column by another column in pandas dataframe
<p>I am cleaning data in pandas dataframe, I want split a column by another column.</p> <p>I want split column 'id' by column 'eNBID',but don't know how to split</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd id_list = ['4600375067649','4600375077246','460037495681','460037495694'] eNBID_lis...
<p>considering the <code>46003</code> will remain same for all ids</p> <pre><code>df['id'] = df.apply(lambda x: '-'.join([i[:3]+'-'+i[3:] if '460' in i else i for i in list(re.findall('(\w*)'+'('+x.eNBID+')'+'(\w*)',x.id)[0])]), axis=1) </code></pre> <p><strong>Output</strong></p> <pre><code> id eN...
python|pandas|dataframe|split|data-cleaning
1
369,998
56,951,679
Issues creating custom keras layer
<p>I am trying to create a custom keras layer to do a particular task</p> <p>I have input of shape=(batch_size, M, N, p) I want my output to be of shape=(batch_size, M, N, f)</p> <p>So, I set up a trainable conv_weight of shape=(M, N, p, f)</p> <p>Below is my code</p> <pre class="lang-py prettyprint-override"><code...
<p>You cannot assign to tensors, because they are immutable. What you can do is create a new tensor with copied from another with some values replaced.You can try like <a href="https://github.com/tensorflow/tensorflow/issues/18383#issuecomment-439459312" rel="nofollow noreferrer">this</a>.</p>
python|tensorflow|keras
2
369,999
57,062,104
Simulating 10,000 Coinflips in Python Very Slow
<p>I am writing a simulation that creates 10,000 periods of 25 sets, with each set consisting of 48 coin tosses. Something in this code is making it run very slowly. It has been running for at least 20 minutes and it is still working. A similar simulation in R runs in under 10 seconds.</p> <p>Here is the python code I...
<p>Why don't you generate the whole big set</p> <pre><code>idx = pd.MultiIndex.from_product((range(10000), range(25)), names=('period', 'set')) df = pd.DataFrame(data=np.random.choice([1,-1], (10000*25, 48)), index=idx) </code></pre> <p>Took about 120ms on my computer. And then the ot...
python-3.x|pandas|dataframe|simulation|coin-flipping
3