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
372,700
60,120,290
Building Neural Networks [TensorFlow 2.0] Model sub-classing - ValueError/TypeError
<p>I am using TensorFlow 2.0 with Python 3.7.5 to build a neural network for Iris classification using Model sub-classing approach.</p> <p>The code I have is as follows:</p> <pre><code>import tensorflow as tf from tensorflow.keras import Sequential, Model from tensorflow.keras.layers import Dense, Input import pandas...
<p>Your problem stems from the way you preprocess your data, before you fit it to your model.</p> <p>It is highly likely that you pass the entire csv-dataset from iris, including your column headers, hence your issue. You can verify this from </p> <blockquote> <p>"You passed: inputs= sepallength sepalwidth petallen...
python-3.x|keras|neural-network|tensorflow2.0
1
372,701
59,991,146
Filter dataframe based on the quantile per group of values
<p>Let's suppose that I have a dataframe like that:</p> <pre><code>import pandas as pd df = pd.DataFrame({'col1':['A','A', 'A', 'B','B'], 'col2':[2, 4, 6, 3, 4]}) </code></pre> <p>I want to keep from it only the rows which have values at <code>col2</code> which are less than the x-th quantile of the values for each o...
<p>We have <code>transform</code> with <code>quantile</code> </p> <pre><code>df[df.col2.lt(df.groupby('col1').col2.transform(lambda x : x.quantile(0.6)))] col1 col2 0 A 2 1 A 4 3 B 3 </code></pre>
pandas|group-by|quantile
3
372,702
60,064,351
One-hot encoding using tf.data mixes up columns
<h3>Minimum working examples</h3> <p>Consider the following CSV file (<code>example.csv</code>)</p> <pre><code>animal,size,weight,category lion,large,200,mammal ostrich,large,150,bird sparrow,small,0.1,bird whale,large,3000,mammal bat,small,0.2,mammal snake,small,1,reptile condor,medium,12,bird </code></pre> <p>The ...
<h1>Where is the sorting?</h1> <p>The sorting isn't occuring at <code>tf.feature_column.categorical_column_with_vocabulary_list()</code>. If you print <code>categorical_columns</code>, you will see that the columns are still in the order you added them to the feature_column:</p> <pre><code>[ IndicatorColumn(categor...
python|tensorflow|tensorflow2.0|one-hot-encoding
2
372,703
60,083,433
What´s the difference between idxmax() and max() inside a groupby pandas
<p>I have a dataframe with data from many players of different teams. What I wanted was to groupby 'team' and only keep the rows with the max value from height.</p> <p>When I used this code, I just got the 'Team' label and peoples heights:</p> <p>Code:</p> <pre><code>df.groupby(['team'], sort=True)['height'].max() <...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.max.html" rel="noreferrer"><code>max()</code></a> simply returns the maximum value.</p> <p><a href="https://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.idxmax.html" rel="noreferrer"><code>idmax()</code><...
python|pandas|pandas-groupby
5
372,704
59,995,964
How to make pandas work for cross multiplication
<p>I have 3 data frame:</p> <p>df1</p> <pre><code>id,k,a,b,c 1,2,1,5,1 2,3,0,1,0 3,6,1,1,0 4,1,0,5,0 5,1,1,5,0 </code></pre> <p>df2</p> <pre><code>name,a,b,c p,4,6,8 q,1,2,3 </code></pre> <p>df3</p> <pre><code>type,w_ave,vac,yak n,3,5,6 v,2,1,4 </code></pre> <p>from the multiplication, using pandas and numpy, I ...
<p>Ok, so this will in no way resemble your desired output, but vectorizing the formula you provided:</p> <pre class="lang-py prettyprint-override"><code>df2=df2.set_index("name") df3=df3.set_index("type") df1["w_ave"] = df3.loc["v", "w_ave"]+ df1["a"].mul(df2.loc["q", "a"])+df1["b"].mul(df2.loc["q", "b"])+df1["c"].mu...
pandas|numpy|multiplication
0
372,705
60,326,744
time series decomposition error in python
<p>I have the following dataframe</p> <pre><code>data = pd.DataFrame({ 'date': [1988, 1988, 2000, 2005], 'value': [11558522, 12323552, 13770958, 18412280] }) </code></pre> <p>i then make the date column into a datetime dtype</p> <pre><code>data['date'] = pd.to_datetime(data['date'],format = '%Y') </code></pre> <p>...
<p>You need to set <code>date</code> as index in data frame:</p> <pre><code>data = data.set_index('date') </code></pre>
python|pandas|dataframe|time-series
0
372,706
60,248,148
Apply Function to MultiIndex DataFrame by Groupby
<p>I want to groupby('Ticker') this multiIndex Dataframe and then Apply a function that returns a Series for each ticker and add the result to a new column on the df. </p> <pre><code>def Indicator(dataf): df = dataf.copy() df['TR1'] = df.High.sub(df.Low) df['TR2'] = abs(df.High.sub(df.Close.shift(1))) ...
<p>In order to fix that error, you just need to add the following line in the <code>Indicator</code> function, after the <code>copy</code> operation:</p> <pre><code>df.index = df.index.get_level_values(0) </code></pre> <p>The problem indeed is due to the fact you pass a MultiIndex instead of a DateTime index to the <...
python|pandas|group-by
1
372,707
60,161,588
Tensorflow EPOCH how to grab information
<p>So if I run my tensorflow 2.0 code through my python UI, I can see the epochs printing out to the command line. How can I 'get or access' that information (preferably while its running) so I can put the string in a text field.</p> <p>I know its the what is making the output</p> <pre><code>model.fit(......) </code>...
<p>To access the loss at each epoch, you can use <code>history = model.fit(...)</code> instead of <code>model.fit(...)</code>. This saves the loss information at each epoch into a <code>keras.callbacks.callbacks.History</code> object, where the loss can be retrieved and printed. You can further add more information to ...
python-3.x|string|tensorflow|command-line
1
372,708
60,186,843
How to find the most frequent value in a column using np.histogram()
<p>I have a DataFrame in which one column contains different numerical values. <strong>I would like to find the most frequently occurring value specifically using the np.histogram() function.</strong></p> <p>I know that this task can be achieved using functions such as column.value_counts().nlargest(1), however, I am ...
<p>This is one way to do it:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd # Make data np.random.seed(0) data = pd.Series(np.random.randint(1, 10, size=100)) # Make bins bins = np.arange(data.min(), data.max() + 2) # Compute histogram h, _ = np.histogram(data, bins) # Find...
python|pandas|numpy|histogram
1
372,709
60,293,250
How to group and calculate in pandas
<p>I have df like below</p> <pre><code>customer class score A a 10 A b 20 B a 40 B b 50 </code></pre> <p>I would like to group, transform and calculate like this. </p> <pre><code>customer score(b-a) A 10 B 10 </code></pre> <p>I couldnt fi...
<p>You can use @HenryYik's comment, or you can use <code>pivot</code>:</p> <pre><code>(df.pivot(index='customer', columns='class', values='score') .assign(score=lambda x: x['b']-x['a']) ) </code></pre> <p>Output:</p> <pre><code>class a b score customer A 10 20 10 B 40 ...
python|python-3.x|pandas|pandas-groupby
4
372,710
60,115,911
Tensorflow autocomplete in pycharm
<p>I started to user tensorflow on pycharm and i discovered that there is not auto completion is it possible to add it </p>
<p>i think you might want to use this format to import it:</p> <pre><code>import tensorflow as tf .... #usage tf.keras.callbacks.— tf.keras.optimizers.— </code></pre> <p>The above should fix it for you.</p>
python|tensorflow
1
372,711
59,949,126
how to create and rearrange a new csv file based on existing file meeting certain conditions?
<p>I have a CSV file with tweets having 4 columns (user_Id, status, tweet_Id, tweet_text) and more than 50,000 rows. The first column user_id has 4 unique Id's which are repeated throughout the column. The second column status is binary classification having either 0 or 1 for each tweet. The third column is tweet Id an...
<p>Here's a way to do using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html" rel="nofollow noreferrer"><code>pivot_table</code></a>:</p> <pre><code>newdf = (pd .pivot_table(df, index=['tweet_id','tweet_text'], columns=['user_id'], ...
python|pandas|csv|twitter
0
372,712
60,297,356
Not matching sample in y axis for knn
<p>Im trying to make my way to a sligthly more flexible knn input script than the tutorials based of the iris dataset but Im having some trouble (I think) to add the matching 2nd dimension to the numpy array in #6 and when I come to #11. the fitting.</p> <blockquote> <p>File "G:\PROGRAMMERING\Anaconda\lib\site-packa...
<p>This is how I used the <code>scikit-learn KNeighborsClassifier</code> to fit the <code>knn</code> model:</p> <pre><code>import numpy as np import pandas as pd from sklearn import datasets from sklearn.neighbors import KNeighborsClassifier df = datasets.load_iris() X = pd.DataFrame(df.data) y = df.target knn = ...
python|scikit-learn|numpy-ndarray|knn
1
372,713
59,950,660
pandas not showing output in pyCharm but showing in google colab
<pre class="lang-py prettyprint-override"><code>import pandas as pd kulfi=['Chocolate','Mango','Vanilla','Kesar'] pd.Series(kulfi) </code></pre> <p>When I run this program in pyCharm it doesn't show any output in console whereas it shows output in Google Colab Please note that I have already pip3 installed python-tk f...
<p>Try adding <code>print(pd.Series(kulfi))</code>. They are different environments. Google Colab has an interactive Jupyter notebook like interface while pycharm is an IDE.</p>
python|pandas|machine-learning|pycharm
2
372,714
60,036,009
Matching multiple column and add to dataframe
<p>supposed data set,</p> <p><strong>df1</strong></p> <pre><code>num1 num2 27 1 973 3 1410 3 724 1 346 5 </code></pre> <p><strong>df2</strong></p> <pre><code> a1 a2 c1 c2 27.0 1 red apple 131.0 1 blue banana 2124.0 3 green apple 1345.0 1 red orange 346.0 5 blue gra...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.zfill.html" rel="nofollow noreferrer"><code>Series.str.zfill</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>DataFrame.assign</code...
python|pandas|dataframe|match|multiple-columns
2
372,715
59,954,696
Creating new columns with pandas .loc
<p>My dataset looks like this:</p> <pre><code>ex = pd.DataFrame.from_dict({'grp1': np.random.choice('A B'.split(), 20), 'grp2': np.random.choice([1, 2], 20), 'var1': np.random.rand(20), 'var2': np.random.randint(20)}) </code></pre> <p>I want to create new columns with the next value within the groups, but the followi...
<p>With <code>loc</code> you can't create new columns. But you could do:</p> <pre class="lang-py prettyprint-override"><code>ex['next_var1'], ex['next_var2'] = None, None ex.loc[:, ['next_var1', 'next_var2']] = ex.groupby(['grp1', 'grp2'])[['var1', 'var2']].shift(-1).values </code></pre> <p>However you could also do...
pandas
1
372,716
59,935,095
How to get a new column in pandas based on the value of another column?
<p>I have a multi-class data set with columns:</p> <pre><code>File_name Label Value. abcd A 74 bwld B 72 </code></pre> <p>I have 4 unique labels and I want to create a new column called 'is_valid' which is a boolean, which assigns a true value to 10% of the data from each lab...
<pre><code>val_split = 0.1 df['is_valid'] = False for label in df['Label'].unique(): indexes = df[df['Label']==label].sample(frac=val_split) df.loc[(indexes.index.values), 'is_valid'] = True </code></pre>
python|pandas
0
372,717
60,048,658
pandas merge indicator with dataframe name instead of 'right_only'
<p>Is there any way to make the <code>indicator</code> option of <code>pd.merge</code> display dataframe names instead of "left_only" and "right_only"? i.e. display "df1_only" instead of "left_only"? I know it can be done with the code below but I'm wondering if there's an easier way.</p> <pre><code>df = pd.merge(df1,...
<p>A python object can be bound to many names. In fact, the names of the references to your dataframes within the function is likely something like <code>left</code> and <code>right</code>, not <code>df1</code> and <code>df2</code>. Pandas has no way of knowing what name you want to use because it can't look into the c...
python|pandas
2
372,718
60,133,669
Looking for specific value with if statement
<p>Hi I have a large dataset in excel (and it will keep growing) of products' orders. </p> <p>The dataset look like this </p> <pre><code>Product Date Lsat24 Next24 Summary Buyer *day1* AX1 | 2/1/2019 |Checking inventory |Invoicing |The product...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.endswith.html" rel="nofollow noreferrer"><code>Series.str.endswith</code></a> for looking for string in 3 columns with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.any.html" re...
python|pandas
4
372,719
59,948,919
Different Q1 and Q3 values in python calculation from TI-nspire
<p>I calculated the upper quartile (Q3 or 75%-tile) and lower quartile (Q1 or 25%-tile) using Numpy/Pandas and TI-nspire. But I get different values. Why does this happen? </p> <p>From (5+8)/2=6.5 and (18+21)/2=19.5, Numpy/Pandas Q1 and Q3 are wrong. Why does Numpy/Pandas return wrong numbers?</p> <pre><code>import n...
<p>This <a href="https://stackoverflow.com/questions/45926230/how-to-calculate-1st-and-3rd-quartiles/45926291">post</a> and this <a href="https://stackoverflow.com/questions/41744275/which-method-does-pandas-use-for-percentile">post</a> helped me understand it.</p> <p>So if you have [7, 15, 36, 39, 40, 41], then 7 -> ...
pandas|numpy|ti-nspire|iqr
1
372,720
59,932,245
Plotly: How to use for loop or list for name attribute in bar charts?
<p><strong>This is how my bar chart looks like currently:</strong></p> <p><a href="https://i.stack.imgur.com/Sh9wV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Sh9wV.png" alt="enter image description here"></a></p> <p><strong>This is how my data looks like:</strong></p> <p><a href="https://gith...
<blockquote> <p>Expected graph is like the legends(ie the name attribute 'Domain A' ,'Domain B', 'Domain C' etc should come in x-axis</p> <p>and the status such as 'Completed' , 'Not completed' etc should come in the legends or the name attribute for the bar chart.</p> </blockquote> <p>Like this?</p> <p><a href="https:...
python|pandas|plotly
3
372,721
60,139,225
What's the name of this operation in Pandas?
<p>whats the name of below operation in Pandas?</p> <pre><code>import numpy as np import pandas as pd x=np.linspace(10,15,64) y=np.random.permutation(64) z=x[y] </code></pre> <p>ndarray "x" is (I assume) shuffled using ndarray "y" and then result ndarray is assigned to "z".</p> <p>What is the name of this operatio...
<p>This is called <strong>indexing</strong>, both in Pandas and NumPy</p> <hr> <p>This code is basically shuffling an array using an array of indices. Using pandas you could shuffle a <code>Series</code> containing <code>x</code> using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFra...
python|pandas|numpy
0
372,722
60,213,434
Pandas - How to form groups then plot distribution (barplot) for each group based on two columns?
<p><code>----| col_1 | col_2 | col_3 (...) row_1| "A" "Yes" "Yes" row_2| "B" "Yes" "No" row_3| "A" "Yes" "Yes" row_4| "A" "No" "Yes" </code> Result for "A": <code> 2 | 1 | | ("Yes", "Yes") ("No", "Yes") ("Yes", "No") ("No", "No")</code></p> <p>How do I group a ...
<pre><code>import matplotlib.pyplot as plt df = pd.DataFrame( [['A', 'Yes', 'Yes'], ['B', 'Yes', 'No'], ['A', 'Yes', 'Yes'], ['A', 'No', 'Yes']], columns= ['col_1', 'col_2', 'col_3'] ) for key, grp in df.groupby(['col_2', 'col_3']): grp['col_1'].hist() plt.show() </code></pre> <p>You ...
python|pandas|plot|group-by
0
372,723
60,288,732
Pandas read_excel returns PendingDeprecationWarning
<p>I have been importing Excel files as Pandas data frames using the <code>read_excel</code> function with no apparent issues so far. However, I just realized that after some recent updates I'm getting the below warning:</p> <blockquote> <p>/usr/local/lib/python3.7/site-packages/xlrd/xlsx.py:266: PendingDeprecationW...
<p>Your data import is "safe" at the moment. To get rid of the warning and future-proof your code, try:</p> <pre><code>pd.read_excel(filename, engine="openpyxl") </code></pre> <p>or put this at the start of your script:</p> <pre><code>import pandas as pd pd.set_option("xlsx", "openpyxl") </code></pre>
python|pandas|import|openpyxl|xlrd
7
372,724
60,175,436
Estimating Dataframe memory usage from file sizes
<p>If I have a list of files in a directory is it possible to estimate a memory use number that would be taken up by reading or concatenating the files using <code>pd.read_csv(file)</code> or <code>pd.concat([df1, df2])</code>?</p> <p>I would like to break these files up into concatenation 'batches' where each batch w...
<p>You could open each CSV, read first 1000 lines only into DataFrame, and then check memory usage. Then scale estimated memory usage by number of lines in the file.</p> <p>Note that <code>memory_usage()</code> isn't accurate with default arguments, because it won't count strings' memory usage. You need <code>memory_u...
python|python-3.x|pandas|dataframe|operating-system
0
372,725
60,287,941
groupby - aggregate - groupby
<pre><code>Category | Unit | ID | Time | isReq 1 A x1 t1 0 1 A x1 t2 0 1 A x1 t3 0 1 A x1 t4 0 1 B x2 t5 1 1 B x2 t6 0 1 B x2 t7 0 </code></pre> <p>I am trying...
<p>You could try this - </p> <pre><code>df.groupby(['Category', 'Unit']).agg(ID_count=('ID','nunique'), time_diff=('Time', 'mean')) </code></pre>
pandas|pandas-groupby
0
372,726
60,293,049
Generate random probability based on the data size in Numpy
<p>I want to generate a non-uniform random sample using a range and specific size using Numpy as follows:</p> <p><code>np.random.choice(m=5, n, p=[0.1, 0, 0.3, 0.6, 0])</code>,</p> <p>However, I want to obtain <code>p</code> randomly based on the size of <code>m</code> automatically without manually writing <code>p=[...
<p>A way to get a list of random <code>float</code> values, of length <code>m</code>, that sums to <code>1</code>:</p> <pre><code>m = 5 values = [np.random.rand() for _ in range(m)] p = [v/sum(values) for v in values] </code></pre> <p>However, since <code>values</code> are all in the range 0-1, the weighting is more ...
python|numpy
1
372,727
59,969,590
Pandas: Groupby and aggregate multiple columns of type json, float
<p>I am using python3 and pandas version 0.25. I have a JSON datatype in postgresql table. I am using pandas.io.sql to fetch the data from the table.</p> <pre><code>import pandas.io.sql as psql df = psql.read_sql(sql,con,params=params) </code></pre> <p>So I am getting the dataframe from DB call as above.</p> <p>When...
<p>Here's a way you can try:</p> <pre><code>import numpy as np f = (df .groupby('col1_data')['col2_data'] .apply(lambda x: np.concatenate(x).tolist()) .reset_index()) col1_data col2_data 0 A1 [{'scenario': 1, 'scenario_name': 'Test', 'val... </code></p...
python|python-3.x|pandas
1
372,728
59,998,468
Columns Values are getting changed to date format in pandas dataframe
<p>This is my DataFrame called as Data</p> <pre><code>Column A Column B 1 A 2 B 3 C </code></pre> <p>I use Dictionery to map column A</p> <pre><code>Dict = {'1':'0', '2':'1-9','3':'10-29','4':'30-49','5':'50+'} Data['Column A'] = Data['Column A'].astype(str).map(Dict ) </co...
<p>what you want to prevent in Column A I am getting the same values which you are expecting,</p> <pre><code>import datetime Data=pd.DataFrame(data={'Column A':[1,2,3],'Column B':['A','B','C']}) Dict = {'1':'0', '2':'1-9','3':'10-29','4':'30-49','5':'50+'} Data['Column A'] = Data['Column A'].astype(str).map(Dict ) <...
python-3.x|pandas
1
372,729
60,118,212
Efficient way to slice a 2D array and skip indices; extract small segments repeatedly
<p>I have a 2D numpy array D, which has Dimensions (1000, 800). I want to extract small segments of length 20 from the array:</p> <p>Assume D[0][:] is [1, 2, 3, 4, 5, 6, ...] and I want segments of length 3, I'd like the first three numbers (1, 2, 3), then skip some indices (say 60), extract 3, skip 60, and so on.</p>...
<p>With no use of any special methods, it's possible to generate a mask of indexes needed like this:</p> <pre><code>D = np.random.random((1000,800)) step = 3 skip = 60 idx = np.arange(800) needed_indexes = idx%(skip+step)&lt;step </code></pre> <p>Then you can return a copy of your array in a standard way:</p> <pre><...
python|arrays|numpy|slice
1
372,730
60,251,790
Convert a list of strings containing list-of-integers into an array
<p>I have a series that is a list of lists that contain integers that I am attempting to turn into an array. This is a small snip-it of the list I am trying to convert into an array.</p> <pre><code>['[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]', '[0, 0, 0, 0, 0, 0, 0, 0, 1, 0]', '[0, 0, 0, 0, 0, 0, 0, 1, 0, 0]', '[0, 0, 0, 0, 0...
<p>You can use <code>ast.literal_eval</code> to change the string to list of lists of ints</p> <pre><code>sequence = [literal_eval(i) for i in sequence] # [[0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1]] </...
python|pandas
2
372,731
60,022,040
Calculate corresponding time interval based on other condition in Python
<p>I have dataset <code>df</code> as below:</p> <pre><code> Time Temperature 17:29:33 18 8:23:04 18.5 8:23:04 19 9:12:57 19 9:12:57 20 9:12:58 20 9:12:58 21 9:12:59 21 9:12:59 23 9:13:00 23 9:13:00 25 9:13:01 25 9:13:01 27 9:13:02 27 9:13:02 28 9:13:03 ...
<p>Since the temperature can be between 25 and 40 and out of range we probably need to calculate the duration of different intervals, so I use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>DataFrame.groupby</code></a> here</p> <pre><c...
python|pandas|dataframe
2
372,732
60,310,202
Creating new column based on if statement of another column grabbing data from yet two different columns
<p>I have data that looks like this:</p> <pre><code>A B C D 3 1 4 0.5 4 2 6 0.25 2 1 3 -0.4 3 3 6 -0.8 </code></pre> <p>And I'd like to add a column E which is the result of either A divided by C or B divided by C based on if D &lt; 0. I figured I should use apply in this si...
<p>np.where might help here: <a href="https://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column">Pandas conditional creation of a series/dataframe column</a></p> <pre><code>df['E'] = np.where(df['D'] &lt; 0, df['A']/df['C'], df['B']/df['C']) </code></pre>
python|pandas|dataframe
2
372,733
60,039,982
numpy python: vectorize distance function to calculate pairwise distance of 2 matrix with a dimension of (m, 3)
<p>I have two numpy arrays A and B. Shape of A is (m,3) and shape of B is (n, 3).</p> <p>Those matrix look like this:</p> <pre><code>A #output array([[ 9.227, -4.698, -95.607], [ 10.294, -4.659, -94.606], [ 11.184, -5.906, -94.675], ..., [ 19.538, -91.572, -45.361], [ 20.001, -92.655, -45.009], ...
<p>You can use <code>np.newaxis</code> to <em>expand</em> the dimensions of your two arrays <code>A</code> and <code>B</code> to enable broadcasting and then do your calculations.</p> <p>Pairwise distance means every point in <code>A (m, 3)</code> should be compared to every point in <code>B (n, 3)</code>. This results...
python|python-3.x|numpy|distance
7
372,734
60,172,564
tf.data.Dataset - Why is the performance of my data pipeline not increasing when I cache examples?
<p>I'm currently trying to learn more about building efficient preprocessing pipelines with tf.data. As per <a href="https://www.tensorflow.org/tutorials/load_data/images#performance" rel="nofollow noreferrer">this tutorial</a> there should be a non negligible effect on performance when the data is cached.</p> <p>I re...
<p>This statement does nothing:</p> <pre><code>if cache: self.train_ds.cache() </code></pre> <p>It should be:</p> <pre><code>if cache: train_hr_ds = train_hr_ds.cache() </code></pre> <p>Like other dataset transformations, <code>cache</code> returns a new dataset instead of modifying an existing dataset.</p>
python|tensorflow|caching
3
372,735
60,190,873
Python : How to set dataframe as parameter to a function in python?
<p>I have 4 columns in CSV and I want to set CSV as parameter to a function in python. The 'key' should be my first column in CSV.</p> <pre><code>df = pd.DataFrame({'Country': ['US','France','Germany'],'daycount':['Actual360','Actual365','ActaulFixed'],'frequency':['Annual','Semi','Quart'], 'calendar':['United','FRA',...
<p>If I understood correctly:</p> <pre><code>def retrieve_value(attribute, country, df): #input attribute and country as str return df.loc[df['Country'] == country, attribute].iloc[0] </code></pre> <p>Ex:</p> <pre><code>retrieve_value('daycount', 'Germany', df) -&gt; 'ActualFixed' </code></pre>
python|pandas
1
372,736
60,277,387
Skipping the first column while renaming column using for loop in python
<p>The ask is simple, for renaming multiple dataframe's with a single code I have written the below but when I am using the code the column which contains the primary key is also getting renamed what I want my code to do is to skip the first column and rename the rest.</p> <p>Codes have been provided below for better ...
<p>This will work for you</p> <pre><code>for name, df in df_dict.items(): new_col = {c:c+"_"+name for c in df.columns[1:]} df.rename(columns=new_col, inplace = True) </code></pre>
python|pandas|for-loop
2
372,737
59,956,257
Find the index of duplicated values in dataframe column
<p>I have the duplicated values of dataframe column with counts but I need to find the index of particular duplicated value in whole column. <strong>Look for the index of the sample dataframe as the index is not unique</strong></p> <pre><code>In[1]: data = [['Center for epidemiological studies depression (CESD)','a'],...
<p>It seems you want the positions for each unique value in <code>'Column1'</code>. When performing a <code>groupby</code>, Pandas tracks exactly those indices in the <code>groups</code> attribute. However, you need to reset the index first.</p> <pre><code>grp = df.reset_index(drop=True).groupby('Column1') print(grp...
python|pandas|dataframe
2
372,738
60,298,061
Parsing csv with changing timezone (due to daylight saving time) with pandas
<p>I'm trying to parse a csv that looks like this</p> <pre><code>time val 28.10.2007 00:00:00.000 GMT+0100 1 28.10.2007 00:01:00.000 GMT+0100 2 28.10.2007 01:00:00.000 GMT-0000 3 28.10.2007 01:01:00.000 GMT-0000 4 </code></pre> <p>To do so, I use</p> <pre><code>pd.read_csv(...
<p>I tried this and somehow it works but I don't know if this is something that you want.</p> <pre><code>df = pd.read_csv('data.csv') df['time'] = pd.to_datetime(df['time'], format='%d.%m.%Y %H:%M:%S.%f GMT%z') df['time_'] = pd.to_datetime(df['time'], utc=True) </code></pre>
python|pandas|datetime
4
372,739
60,189,016
using principal component analysis to visualize data
<p>I am trying to use pca to visualize my data. I have a dataset with 4 variables (date, groundwater level, rainfall, temperature) <a href="https://i.stack.imgur.com/DEBZ4.jpg" rel="nofollow noreferrer">Here is an example of my dataset</a>. I want to see if there is a relationship between rainfall and gwl and temp and ...
<pre><code>targets = ['gwl'] colors = ['r', 'g', 'b'] for target, color in zip(targets,colors): indicesToKeep = finalDf['gwl'] == target </code></pre> <p>In this line why are you comparing finalDf['gwl'] a list of float with a target a string</p> <p>Although, if you want to see if there's any correlation between...
python|pandas|pca
0
372,740
60,047,878
Access first list items in a pandas series
<p>Is there any way to access the first element of the python series object that may contain a list in some entries</p> <p>Example input</p> <pre><code>JUNE 0.1591 JULY 0.004 AUG 0.000 SEPT NaN OCT [1.004, 0.000] dtype: object </code></pre> <p>Desired output</p> <pre><code>JUNE 0.1591 JU...
<p>Here's one way using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mask.html" rel="nofollow noreferrer"><code>Series.mask</code></a>:</p> <pre><code>s.mask(s.str.len().gt(1), s.str[0]) JUNE 0.1591 JULY 0.004 AUG 0 SEPT NaN OCT 1.004 </code></pre>
python|pandas|numpy-ndarray
1
372,741
59,985,042
An issue with np.nan when using it to replace all elements of an array
<p>Here is an 1D array:</p> <pre><code>a = np.array([1, 2, 3]) </code></pre> <p>I am trying to replace all elements with <code>np.nan</code>. Naturally, I would try:</p> <pre><code>a[:] = np.nan </code></pre> <p>which ended up returning:</p> <pre><code>array([-9223372036854775808, -9223372036854775808, -9223372036...
<p>Your array is being created with <code>dtype='int64'</code>. If you create you array as an array of floats it will work.</p> <pre><code>a = np.array([1, 2, 3], dtype=float) a[:] = np.nan print(a) </code></pre> <p>will give</p> <pre><code>[nan nan nan] </code></pre> <p>alternatively you could create your array us...
python|arrays|numpy|nan
3
372,742
60,228,604
memory address of numpy elements
<p>See the code snip below</p> <pre><code>a = [[1, 2], [3, 4], [5, 6]] b = a[1] id(a[1]) == id(b) # True </code></pre> <p>it is easy to understand because address of <code>b</code> and address of <code>a[1]</code> is the same. So if I change element in a <code>a += 1</code>, element in b will changed as well <code>b ...
<p>Every time the inner <code>ndarray</code> of an <code>ndarray</code> is accessed via indexing like you did with <code>c[1]</code>, a new <code>ndarray</code> is created on the fly as a memory (buffer) view. In this line <code>id(c[1]) == id(d)</code>, <code>c[1]</code> and <code>d</code> are two individual <code>nda...
python|numpy|memory-address
1
372,743
60,195,719
Deleting numbers that cancel each other out in a DataFrame in pandas
<p>I have this huge database in which there are some budget transfers that, when looking at the grand total, cancel each other out. Problem is, I can't seem to understand how I can delete all the rows that cancel each other out. The dataframe below works as an example:</p> <p><code>test = pd.DataFrame(data = [1050.77,...
<p>You should avoid modifying lists while iterating through them. Instead create a list of indexes to drop and drop them after you have found them all. Also to avoid double dropping you need to break when you find a match and continue past things you have already marked to be dropped.</p> <pre><code>import pandas as p...
python|pandas|dataframe
1
372,744
59,918,407
create a file containing both printouts and plots
<p>I have a list of dataframes and a list of jsons, I want to get the df plots and jsons into one nice file (pdf or jpeg), so far I added the json as the title of the plot and this works well enough for short strings (see below) but it gets problematic with longer jsons and I would like to add them as simple prints and...
<p>One approach would be to use a <code>LaTex</code> <code>tabular</code> environment to control the wrapping, something like this</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np from matplotlib import rcParams rcParams["text.usetex"] = True figsize = [10, 6] plt...
python|pandas|matplotlib
1
372,745
65,095,292
How to use the value of one column as part of a string to fill NaNs in another column?
<p>Let's say I have the following df:</p> <pre><code> year date_until 1 2010 - 2 2011 30.06.13 3 2011 NaN 4 2015 30.06.18 5 2020 - </code></pre> <p>I'd like to fill all <code>-</code> and <code>NaN</code>s in the <code>date_until</code> column with 30/06/{year +1}. I tried the following but it uses the who...
<p>We can use <code>pd.to_datetime</code> here with <code>errors='coerce'</code> to ignore the faulty dates. Then use the <code>dt.year</code> to calculate the difference:</p> <pre><code>df['date_until'] = pd.to_datetime(df['date_until'], format='%d.%m.%y', errors='coerce') df['diff_year'] = df['date_until'].dt.year - ...
pandas|replace|fillna
1
372,746
65,126,329
I want to merge all the entries of column and put it in one row each for each column as in the picture
<p>I want to merge all the entries of the column and put it in one row each for each column as in the picture</p> <p><a href="https://i.stack.imgur.com/RJnTw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RJnTw.png" alt="enter image description here" /></a></p>
<p>Convert values to strings join with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.agg.html" rel="nofollow noreferrer"><code>DataFrame.agg</code></a> and convert <code>Series</code> to one row <code>DataFrame</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/refere...
pandas
2
372,747
65,234,450
Reorder pandas DataFrame based on repetitive set of integer in index
<p>I have a pandas dataframe contains some columns, I didn't find a way to order rows as follows:</p> <p>I need to order the dataframe by the field <code>label</code> but in sequential order (like groups)</p> <h3>Input</h3> <pre><code>I category tags 1 A #25-74 1 B #26-170 0 C #29-106 2 A #18-109 3 B...
<p>One idea with helper column by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofol...
pandas|sorting
2
372,748
65,266,053
Python Panda Graph change value in top right
<p>I have a dataframe I plot using:</p> <pre><code>scoreDF.plot(title=&quot;Scores&quot;) plt.xlabel(&quot;Number of Games&quot;) plt.ylabel(&quot;Scores&quot;) plt.show() </code></pre> <p>When it's plotted, there is a value in the top right that show's 0. How do I set this? I would like to have it show the highest val...
<p>From the answers above, I used this and it gave me the max value in the top right.</p> <pre><code>plt.legend(scoreDF.max()) </code></pre> <p>Thanks everyone for their help!</p>
python|pandas
0
372,749
65,342,685
Pandas - apply truth value is ambiguous when parameter is entered
<p><strong>Why does this work?</strong></p> <pre><code>import numpy as np from datetime import datetime, timedelta master = pd.read_csv( &quot;C:/Users/grego/Downloads/Specific Drug monitoring.csv&quot; , skiprows=11, na_values=[&quot;no info&quot;, &quot;.&quot;]) pd.to_datetime, errors='coerce') if s[...
<p>You should maybe try to replace 'and' by '&amp;'</p>
python|pandas
0
372,750
65,317,040
Copy above row values below
<p>Probably easy, but couldn't find it.</p> <p>Want to copy large chunk of data in row where concat data wasn't properly filled in so NaN is below values.</p> <p>Small example:</p> <pre><code>df1 = {'col1': ['a', 'b','c','d','e','f','g',np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]} df1 = pd.DataFrame(data=df1) </c...
<p>Try 1) not to chain index, 2) passing numpy array on assignment:</p> <pre><code>df.loc[7:14, 'col1'] = df.loc[:7,'col1'].values </code></pre> <p>Output:</p> <pre><code> col1 0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 a 8 b 9 c 10 d 11 e 12 f 13 g </code></pre>
python|pandas|dataframe
1
372,751
65,085,722
ONNX runtime is throwing TypeError when loading an onnx model
<p>I have converted a savedModel format to onnx model but when loading it via onnxruntime</p> <pre><code>import onnxruntime as rt sess = rt.InferenceSession('model.onnx') </code></pre> <p>It throws me the below error:</p> <pre><code>onnxruntime.capi.onnxruntime_pybind11_state.InvalidGraph: [ONNXRuntimeError] : 10 : INV...
<p>Looks like a bug in Keras-&gt;ONNX converter.</p> <p><code>starts</code> input of Slice must be int32 or int64: <a href="https://github.com/onnx/onnx/blob/master/docs/Operators.md#Slice" rel="nofollow noreferrer">https://github.com/onnx/onnx/blob/master/docs/Operators.md#Slice</a></p> <p>You can try to patch the mod...
keras|python-3.6|tensorflow2.0|onnx|onnxruntime
0
372,752
65,133,876
Sorting numpy complex array, asignment by value and by reference
<p>I have came across to an interesting problem that I think has to do something with assignment by value and by reference using numpy arrays. Say I want to sort numpy array using classic bubble sort. If I do not include in the function numpy.copy or copy.deepcopy of the swapped value (i.e. the temporary variable) the ...
<p>Your <code>bubbleSortComplex</code> is giving you the wrong result for a very simple, yet probably harder to spot, reason.</p> <p>You don't need to perform <code>deepcopy</code>, on <code>nlist[i]</code> to make it work but you need to be careful about the input to the function.</p> <p>This code <code>nlist2 = num.z...
python|numpy|variable-assignment
0
372,753
65,276,197
Error while creating embedding vector (for matrices) (Input 0 of layer dense is incompatible with the layer)
<p>I'm trying to create embedding vector for matrices.</p> <p>first I'm converting the input of matrices to vector:</p> <pre><code>x = input_x.reshape(input_x.shape[0], input_x.shape[1]*input_x.shape[2]) </code></pre> <p>i.e each sample (each input) is vector (instead of matrix)</p> <p>And I'm building the following mo...
<p>You're using the argument <code>max_length</code> wrong:</p> <blockquote> <p><strong>input_length</strong>: Length of input sequences, when it is constant. This argument is required if you are going to connect Flatten then Dense layers upstream (without it, the shape of the dense outputs cannot be computed).</p> </b...
python|tensorflow|keras|deep-learning
1
372,754
65,136,438
Is there a pandas function to select latest available date of a data frame?
<p>I have the following code, but I want to automate or simplify the latest date available selection. Here's my code:</p> <pre><code>import pandas as pd covid_url = 'https://raw.githubusercontent.com/mariorz/covid19-mx-time-series/master/data/covid19_confirmed_mx.csv' covid_total = pd.read_csv(covid_url, index_col=0)...
<p>Change to date</p> <pre><code>df.index = pd.to_datetime(df.index, format='%d-%m-%Y') #df.loc[df.index.max()] </code></pre>
python|pandas
1
372,755
65,294,879
Pandas assigning values to dataframe, conditional on values in another with the same dimensions issue/question
<p>I'm trying to better understand Pandas/Python so I've been playing around with some stuff. I ran into an issue, I know some workarounds, but I'm wondering why it happened in the first place.</p> <p>Here's my full code, followed by an explanation:</p> <pre><code>df1 = pd.DataFrame(np.random.rand(5, 10).round(2), inde...
<p>Just need to do:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(42) # for reproducibility df1 = pd.DataFrame(np.random.rand(5, 10), index = list(range(1,6)), columns = list(range(1, 11))) df2 = df1 &gt; 0.6 print(df2) </code></pre> <p><strong>Output</strong></p> <pre><code> 1 2 ...
python|pandas|dataframe
1
372,756
65,373,512
(Numpy or PyTorch) Sum array elements for given bins
<p>I would like this problem to be solved using PyTorch tensors. If there is no efficient solution in torch, then feel free to suggest a numpy solution.</p> <p>Let <code>a</code> be a 1-dimensional tensor (or numpy array), and <code>bin_indices</code> be a tensor (np array) of integers between 0 and <code>n</code> excl...
<p>Not sure if this is the best way but here is another solution:</p> <pre><code>&gt;&gt;&gt; bins = torch.unique(bins_indices) &gt;&gt;&gt; vfunc = np.vectorize( lambda x: torch.sum( a[ bins_indices == x ] ) ) &gt;&gt;&gt; vfunc( bins ) array([10, 3, -2]) </code></pre>
python|arrays|numpy|pytorch
2
372,757
65,395,508
Replace string with unique value
<p>I am working with a dataset where one of the columns, 'PARNO', has values separated with '/'.</p> <p>For example, 9644-54-3184/5544/2583. In reality this equates to 9644-54-3184, 9644-54-5544, 9644-54-2583.</p> <p>I could do a simple .str.replace if this was the only column, but there are other rows with this format...
<p>Here's a simple way to replicate the number extension from their prefixes:</p> <pre><code>def expand(s): return s.replace(&quot;/&quot;,f&quot;,{s.rsplit('-',1)[0]}-&quot;).split(&quot;,&quot;) print(expand(&quot;9644-54-3184/5544/2583&quot;)) # ['9644-54-3184', '9644-54-5544', '9644-54-2583'] </code></pre> <p...
python|pandas|str-replace
0
372,758
65,165,747
How to accomplish the multi-dimensional fancy indexing in PyTorch?
<p>I have a <strong>3D tensor</strong> (<code>[batch_size, seq_length, hidden_dim]</code>) and a <strong>2D list</strong> (<code>[batch_size, seq_length]</code>).</p> <p>I want to using list to accomplish the selection of this tensor.</p> <p>For example: the shape of 3D tensor <code>t [2, 5, 3]</code> and the shape of ...
<p>The code provided doesn't work, it seems you are looking to concatenate the tensors in the list on an axis that doesn't yet exit. I suggest you use <a href="https://pytorch.org/docs/stable/generated/torch.stack.html" rel="nofollow noreferrer"><code>stack</code></a> instead.</p> <p>I don't think you can achieve this ...
python|pytorch
0
372,759
65,418,230
Google Colab Pro crashed while allocating large memory
<p>I'm trying to use Colab pro GPU (max 25Gb memory) for training a sequential model. Based on the instructions found <a href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/gpu.ipynb#scrollTo=2qO2cS9QFn42" rel="nofollow noreferrer">here</a>, I'm setting the memory limit to 22Gb. Bel...
<p>I have had the same issue and had to change my tf code. Setting the maximum GPU memory does not mean that tf will figure out a way to run your code without trying to allocate more than what you have specified. That works for what I would call &quot;units&quot; of allocation but if one single operation is gigantic, i...
tensorflow|out-of-memory|google-colaboratory
0
372,760
65,266,994
How to save an image that has been visualized/generated by a Keras model?
<p>I am using <a href="https://github.com/alankbi/detecto" rel="nofollow noreferrer">detecto</a> model to visualize an image. So basically I am passing an image to this model and it will draw a boundary line accross the object and dislay the visualized image.</p> <pre><code>from keras.preprocessing.image import load_im...
<p>Detecto's documentation says the <strong>utils.read_image()</strong> is already returning a NumPy array.</p> <p>But you are passing the return of <strong>visualize.show_labeled_image()</strong> to Keras' <strong>img_to_array(img)</strong></p> <p>Looking at the Detecto source code of <strong>visualize.show_labeled_im...
numpy|machine-learning|keras|object-detection
0
372,761
65,197,392
Facebook-Prophet cross validation with monthly data - Workaround: Pandas timedelta does not support Month and Years
<p>I am using Facebook Prophet to forecast some time series data on monthly base.</p> <pre><code>ds y 2020-02-01 400.0 2020-03-01 450.0 2020-04-01 0.0 2020-05-01 225.0 </code></pre> <p>I would like to use the cross_validation() function to evaluate my results.</p> <pre><code>from fbprophet.diagnostics ...
<p>I believe units longer than a day (&quot;D&quot;) are no longer supported by pandas. This issue arises whenever you use pandas timedelta for those time units.</p> <p>I'd suggest using days and multiply 30 days times the number of months intended</p> <pre class="lang-py prettyprint-override"><code>from fbprophet.diag...
pandas|cross-validation|timedelta|facebook-prophet
1
372,762
65,216,803
Adding X and Y labels to pandas plot
<p>Very new to python, its part of my course but I don't have a great understanding of all the libraries such as pandas, and mattplotlib.</p> <p>I have code</p> <pre><code># plot graph for counts per minute plt.axes(frameon=0) # reduce chart junk minute_ct.plot(kind='line', rot=0, title=&quot;Summary of packet acti...
<p>Do:</p> <pre><code>plt.xlabel('x label') plt.ylabel('y label') </code></pre> <p>You can find some examples of matplotlib usage <a href="https://matplotlib.org/3.3.3/tutorials/introductory/usage.html#sphx-glr-tutorials-introductory-usage-py" rel="nofollow noreferrer">here</a>.</p>
python|pandas
2
372,763
65,274,113
df.ix not working , whats the right iloc method?
<p>This is my program-</p> <pre><code>#n= no. of days def ATR(df , n): df['H-L'] = abs(df['High'] - df['Low']) df['H-PC'] = abs(df['High'] - df['Close'].shift(1)) df['L-PC'] = abs(df['Low'] - df['Close'].shift(1)) df['TR']=df[['H-L','H-PC','L-PC']].max(axis=1) df['ATR'] = np.nan df.ix[n-1,'ATR']=df['TR'][:...
<p>Converting code is a pain and we have all been there...</p> <pre><code>df.ix[n-1,'ATR'] = df['TR'][:n-1].mean() </code></pre> <p>should become</p> <pre><code>df['ATR'].iloc[n-1] = df['TR'][:n-1].mean() </code></pre> <p>Hope this fits the bill</p>
pandas|dataframe|data-structures
0
372,764
65,197,015
How do I convert numpy array to days, hours, mins?
<p>Running with this series</p> <pre><code>X = number_of_logons_all.values split = round(len(X) / 2) X1, X2 = X[0:split], X[split:] mean1, mean2 = X1.mean(), X2.mean() var1, var2 = X1.var(), X2.var() print('mean1=%f, mean2=%f' % (mean1, mean2)) print('variance1=%f, variance2=%f' % (var1, var2)) </code></pre> <p>I get:<...
<p>You can use <code>f-string</code>s:</p> <pre><code>mean1, mean2 = 60785.792548, 61291.266868 variance1, variance2=7603208729.348722,7483553053.651829 print(f'mean1={pd.Timedelta(mean1, unit=&quot;s&quot;)}, mean2={pd.Timedelta(mean2, unit=&quot;s&quot;)}') print(f'variance1={pd.Timedelta(variance1, unit=&quot;s&quo...
python-3.x|pandas|numpy|mean|datetime64
0
372,765
65,422,225
How to solve KeyError(f"None of [{key}] are in the [{axis_name}]") in this case (Pandas)?
<p>I have a CSV file for example like this :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>name</th> <th>email</th> <th>physics</th> <th>chemistry</th> <th>maths</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Sta</td> <td>sta@example.com</td> <td>67</td> <td>78</td> <td>90</t...
<p>Let's assume you have your dataframe already, we use the Code you provided:</p> <pre><code>import pandas as pd df = pd.read_csv(&quot;sample.csv&quot;) </code></pre> <p>Your extra columns should be stored in a list, this makes your Code easier to write and easier to understand.</p> <pre><code>additional_cols = ['gr...
python|python-3.x|pandas|dataframe|numpy
2
372,766
65,165,363
how to know when stop training in CNN model based on Loss and IoU?
<p>I used a CNN model for segmentation task. the output training is like below :</p> <p><a href="https://i.stack.imgur.com/KVCk0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KVCk0.jpg" alt="enter image description here" /></a></p> <p>how to know when should I stop training based on Loss and IoU?</...
<p>Stop training when the loss is at minimum. When loss begins to increase(validation error is at its minimum) or accuracy begins to decrease, stop the training. In your image this appears to be Epoch 23, iteration 12600. IOU&gt;0.5 is considered a good prediction.</p>
python|tensorflow|deep-learning|loss
0
372,767
65,342,931
Pandas: groupby followed by aggregate - unexpected behaviour when joining strings
<p>Having a <code>pandas</code> data frame containing two columns of type <code>str</code>:</p> <pre><code> group sc wc 0 1 A word1 1 2 B word2 2 2 C word3 3 1 D word4 </code></pre> <p>which is created as follows:</p> <p><code>df = pd.DataFrame({&quot;group&quot;:[1,2,2,1],...
<p>I'm pretty sure this is a bug related to <code>GroupBy.agg</code> that manifests because of <code>as_index=False</code> - the entire subgroup DataFrame is passed to <code>agg</code>. Remove that and the output is as expected.</p> <pre><code>df.groupby(&quot;group&quot;)[&quot;wc&quot;].agg('|'.join).reset_index() ...
python|pandas|dataframe|aggregate
2
372,768
65,284,133
How to apply split string operation on address column in Python?
<p>Hi I have this column in df</p> <pre><code>**Purchase Address** 917 1st St, Dallas, TX 75001 682 Chestnut St, Boston, MA 02215 669 Spruce St, Los Angeles, CA 90001 </code></pre> <p>The expected output should be a new column City with values like:</p> <pre><code>**City** Dallas(TX) Boston(MA) Los Angeles(CA) </code><...
<p>you can use the split and map method to get the particular address city. <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html" rel="nofollow noreferrer">link</a></p> <pre><code>&gt;&gt; data['**Purchase Address**'].str.split(&quot;,&quot;) 0 [917 1st St, Dallas, TX 75001] 1 ...
python|pandas|dataframe
1
372,769
65,255,053
Easy way to horizontally flip images in dataset with json labels?
<p>I'm using Tensorflow 2.0 with Python to train an image classifier. I'm using the file model_main_tf2.py to train the model, and have a dataset of images for training and testing. The images were annotated using the LabelMe tool in Python, which allows me to create polygon masks for a Mask RCNN.</p> <p>What I would l...
<p>Since this question is under the Python tag - I assume you want this to be done in Python. Flipping can be done in <code>numpy</code>, <code>PIL</code>, or <code>opencv</code> (your choice).</p> <pre class="lang-py prettyprint-override"><code>image = # some image translated to a numpy array print(type(image)) &gt;&g...
python|machine-learning|computer-vision|tensorflow2.0
0
372,770
65,321,728
Python Pandas: Filtering Rows Based on Multiple Lists Containing Multiple Column Values
<p>I have a large dataframe of about 5.5 million rows and 13 columns. I would like to filter the table based on the values of 2 columns: 'product_id' and 'return_reason'.</p> <p>I would like to select the whole row if product_id and return_reason both have duplicated values.</p> <p>For example, assuming I have the foll...
<p>If need rows with all duplicated by 2 columns use <a href="http://andas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer"><code>DataFrame.duplicated</code></a> with <code>keep=False</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexin...
python|pandas|dataframe|filter
0
372,771
65,163,143
Equivalent of embeddings_regularizer in pyTorch
<p><code>tf.keras.layers.Embedding</code> has parameter <code>embeddings_regularizer</code>. What would be equivalent of this in pyTorch or <code>nn.Embedding</code>?</p>
<p>There is no direct equivalent for PyTorch as PyTorch only supports <code>L2</code> regularization on parameters via <a href="https://pytorch.org/docs/stable/optim.html" rel="nofollow noreferrer"><code>torch.optim</code></a> optimizers.</p> <p>For example <a href="https://pytorch.org/docs/stable/optim.html#torch.opti...
keras|pytorch
3
372,772
65,143,404
Pytorch CrossEntropyLoss Tensorflow Equivalent
<p>I am currently translating a pytorch code into tensorflow. There is a point that i am aggregating 3 losses in a tensorflow custom loop and i get an error that i am passing a two dimensional array vs a 1 dimensional into CategoricalCrossEntropy of tensorflow which is very legit and i understand why this happens... bu...
<p>Try using the loss <code>loss=tf.keras.losses.sparse_categorical_crossentropy</code></p>
python|numpy|tensorflow|pytorch
0
372,773
65,424,676
Pytorch's nn.TransformerEncoder "src_key_padding_mask" not functioning as expected
<p>Im working with Pytorch's <code>nn.TransformerEncoder</code> module. I got input samples with (as normal) the shape (<code>batch-size, seq-len, emb-dim</code>). All samples in one batch have been zero-padded to the size of the biggest sample in this batch. Therefore I want the attention of the all zero values to be ...
<p>I got the same issue, which is not a bug: <a href="https://pytorch.org/docs/master/generated/torch.nn.Transformer.html#torch.nn.Transformer" rel="nofollow noreferrer">pytorch's Transformer implementation</a> requires the input <code>x</code> to be <code>(seq-len x batch-size x emb-dim)</code> while yours seems to be...
python|nlp|pytorch|transformer-model
2
372,774
65,248,028
Is is possible to finetune SimCLR on an instance segmentation task using PyTorch Lightning Bolts?
<p>I have a dataset of high-resolution drone images, which I have split into tiles of size 512x512. The tiles will be annotated by delineating a specific type of vegetation and stored in COCO format. I would like to use self-supervised learning for instance segmentation in the tiles. The Pytorch Lightning bolts module ...
<p>I think yes, you can use SimCLR as a feature extractor and a deep model for instance segmentation based on the obtained data representation from the SimCLR (instead of data in normal cases).</p>
deep-learning|pytorch|conv-neural-network|pytorch-lightning
0
372,775
65,327,194
Find the mode for a pandas column based on filtering on another pandas column
<p>I have a dataframe that looks similar to this</p> <pre><code>df = pd.DataFrame({'id': [1001, 1002, 1003, 1004, 1005, 1006] 'resolution_modified': ['It is recommended to replace scanner', 'It is recommended to replace scanner', ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>pandas.DataFrame.groupby</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mode.html" rel="nofollow noreferrer"><code>pandas.S...
python|python-3.x|pandas
2
372,776
65,109,118
Train with YOLO pretrained weights on Darknet
<p>I'm attempting to train my Yolo object detector using the Darknet CNN. I'm using Yolov4 pre-trained weights which can predict Cars, Traffic Lights, and Stop Signs with these COCO Classes. Just wondering how I can add an extra layer so my model can also pick up Traffic Signs. Code below to train:</p> <pre><code>!./da...
<p>You have to train the model from the beginning with images of all previous objects, Cars, Traffic Lights, and Stop Signs, in addition to the new Traffic Signs.</p>
tensorflow|yolo|darknet|pre-trained-model
0
372,777
65,103,069
How can I read values from a buffer with Numpy when some bytes are padded?
<p>Currently I am using a sensor that constantly provides information by using serial port. The data read and saved in the buffer is for example:</p> <pre><code>b'\x00\x009\x00A\x002\x00\x00\x18\x00\x13\x00\x11\x00\x10\x00\x10\x00\x10\x00\x10\x00\x10\x00\x11' </code></pre> <p>I have been using numpy in order to convert...
<p>Those aren't &quot;padded&quot; bytes. <code>\x009</code> is <em>two</em> bytes - a byte with value 0, and a byte with value 57, which happens to correspond to the ASCII code for a <code>9</code> character. Most bytes that correspond to printable ASCII values are displayed as the corresponding ASCII characters in th...
python|numpy|pyserial
1
372,778
65,108,421
Google Colab keeps crashing when trying to run keras tuner
<p>This is my first machine learning project, working with a dataset i have created on my own.</p> <p>Unfortunately Google Colab keeps crashing. And it seems to have something to do with keras tuner, but i am not sure.</p> <p>It actually worked for a while. But now it is crashing immediately when i run it.</p> <p>edit:...
<p>This could be because of multiple colab tabs open and you are getting out of RAM. Use only single tab and run the process. Check with the code below how much you have RAM and how much it takes while you start the process. Let me know if this works.</p> <pre><code># memory footprint support libraries/code !ln -sf /op...
tensorflow|keras|deep-learning|google-colaboratory|keras-tuner
1
372,779
65,380,796
tflite flutter application gives only one output
<p>While working with <code>tflite</code> in flutter the output I get is <code>output = [{confidence: 0.8115850687026978, index: 90, label: cynoglossum lanceolatum}]</code></p> <p>and it's obviously seen that there is only one put, the model I am using trained from Teachable machine. How do I get multiple outputs from ...
<p>When you run your model there is an attribute numResults is defaulted to 1. You can change to get more results.</p> <pre><code>var recognitions = await Tflite.runModelOnImage( path: image.path, numResults: 1, threshold: 0.05, imageMean: 127.5, imageStd: 127.5, ); </code></pre>
flutter|tensorflow-lite
0
372,780
65,095,791
How to create a single array to represent a 3D grid of points in python
<p>So what I'm trying to do is create a 3D grid in python that can be used to interpolate some data I will be given at each of the points on the grid. What I want is to be able to have one 3D array that I can use to pick any point on the grid. For example if I wanted to pick the point along the 3rd row of x, the 2nd r...
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html" rel="nofollow noreferrer"><code>np.meshgrid</code></a> along with <a href="https://numpy.org/doc/stable/reference/generated/numpy.arange.html" rel="nofollow noreferrer"><code>np.arange</code></a>:</p> <pre><code>r = np.arange(...
python|arrays|numpy
0
372,781
65,327,060
How to get all 'first' instances of grouped and recurring values?
<p>I have a large dataframe (1.5mln,13) and I want to retrieve the index of all the first occurences of grouped events.</p> <p>The events are repeating in groups of varying lenghts like in my example date.</p> <p>How can I get a list with all the first 'a' events, and all the first 'b' events?</p> <p>Example data:</p> ...
<p>As I understood, you want the first row from a sequence of consecutive rows with the same value in <em>event</em> column.</p> <p>The code to get this result is:</p> <pre><code>df[df.event != df.event.shift()] </code></pre> <p>(compare the current value with the previous, looking for &quot;different&quot; cases, then...
python|pandas
2
372,782
65,059,321
Pandas: index-derived column with specific increments based on other columns
<p>I have the following data frame:</p> <pre><code>import pandas as pd pandas_df = pd.DataFrame([ [&quot;SEX&quot;, &quot;Male&quot;], [&quot;SEX&quot;, &quot;Female&quot;], [&quot;EXACT_AGE&quot;, None], [&quot;Country&quot;, &quot;Afghanistan&quot;], [&quot;Country&quot;, &quot;Albania&quot;]], colum...
<p>The best way to do this would be to use <code>ngroup</code> and <code>cumcount</code></p> <pre><code>name_group = pandas_df.groupby('FullName') pandas_df['sort_order'] = ( name_group.ngroup(ascending=False).add(1).mul(100) + name_group.cumcount().add(1) ) </code></pre> <p>Output</p> <pre><code> FullName ...
python|python-3.x|pandas|sorting
1
372,783
65,157,478
Creating new Pandas Dataframe column within pipeline process
<p>I apologize but I'm not sure how to explain this without just giving my example, therefore:</p> <p>For the titanic dataset in Kaggle, some people have added a new column called 'isChild' and applied it to the age column to where if the age is under 13 he is a child or else he/she is an adult. From there they are fin...
<p>So the answer to my question is that I first must create a class, like so:</p> <pre><code>class DataframeFunctionTransformer(): def __init__(self, func): self.func = func def transform(self, input_df, **transform_params): return self.func(input_df) def fit(self, X, y=None, **fit_params): return self </...
python|python-3.x|pandas|pipeline|preprocessor
1
372,784
65,233,132
How to dynamically update batch norm momentum in TF2?
<p>I found a PyTorch implementation that decays the batch norm <code>momentum</code> parameter from <code>0.1</code> in the first epoch to <code>0.001</code> in the final epoch. Any suggestions on how to do this with the batch norm <code>momentum</code> parameter in TF2? (i.e., start at <code>0.9</code> and end at <cod...
<p>You can set an action in the begin/the end of each batch, so you can control the any parameter during the epoch.</p> <p>Below the options for the callbacks:</p> <pre><code>class CustomCallback(keras.callbacks.Callback): def on_epoch_begin(self, epoch, logs=None): keys = list(logs.keys()) print(&q...
tensorflow|pytorch|tensorflow2.0|batch-normalization|momentum
1
372,785
65,412,636
Python doesnt imports matplotlib, matplotlib doesnt work
<p>So i searched a lot, but i am not able to solve the problem. Everytime i try to use matplotlib or similar (matplotlib.something), python isn't able to import it. It says:</p> <pre><code> File &quot;C:\Users\Privacy\ArduConnect.py&quot;, line 8, in &lt;module&gt; import matplotlib File &quot;C:\Users\Privacy\A...
<p>I had the same problem, you can fix it with:</p> <pre><code>pip uninstall pandas python -m pip install numpy==1.19.3 pip install pandas </code></pre> <p>From <a href="https://developercommunity.visualstudio.com/content/problem/1207405/fmod-after-an-update-to-windows-2004-is-causing-a.html" rel="nofollow noreferrer">...
python|python-3.x|numpy|matplotlib
-1
372,786
65,225,911
How to loop through elements from a python pandas dataframe to a new nested dictionary?
<p>I am currently using pandas library to read data from a CSV file. The data includes a &quot;data&quot; column which consists of 1's and 0's, and a &quot;published_at&quot; column which has unique time and date stamps (I have converted it to become the index of the dataframe). <a href="https://i.stack.imgur.com/yznc2...
<p>Hope you're doing well. This snippet will help you do the job!</p> <pre><code>result = {} for index, row in df.iterrows(): # Iterates over the row date = row['published_at'].split(' ')[0] # This line takes only the date of the row ( not hour and minute ...) ans = row['data'] # Finds if the data is zero or ...
python|python-3.x|pandas|dataframe|for-loop
0
372,787
65,106,011
Summarising features with multiple values in Python for Machine Learning model
<p>I have a data file containing different foetal ultrasound measurements. The measurements are collected at different points during pregnancy, like so:</p> <pre><code>PregnancyID MotherID gestationalAgeInWeeks abdomCirc 0 0 14 150 0 0 21 ...
<p>You can try this. a bit of a complicated query but it seems to work:</p> <pre><code>(df.groupby(['MotherID', 'PregnancyID']) .apply(lambda d: d.assign(tm = (d['gestationalAgeInWeeks']+ 13 - 1 )// 13)) .groupby('tm')['abdomCirc'] .apply(max)) .unstack() ) </code...
python|pandas
1
372,788
65,378,799
Skipping spaces in words of a given column while importing text file in pandas
<p>I am trying to import a dataset from a text file, which looks like this.</p> <pre><code>id book author 1 Cricket World Cup: The Indian Challenge Ashis Ray 2 My Journey Dr. A.P.J. Abdul Kalam 3 Making of New India Dr. Bibek Debroy 4 Whispers of Time Dr. Krishna Saksena </code></pre> <p>When I used for...
<p>Try with tab as a seperator:</p> <pre><code>df = pd.read_csv('book.txt', sep='\t') </code></pre>
python|pandas|dataframe|txt
1
372,789
65,386,741
I'm brand new to Jupyter and have no idea what is wrong with what I am doing
<p>I trying to use sklearn and ran into an error, but I have no idea what is wrong. This is my code:</p> <pre><code>import pandas as pdd from sklearn.tree import DecisionTreeClassifier df = pd.read_csv('vgsales.csv') X = df.drop(columns=['Name','Platform','Publisher','Genre'])#input y = df['Rank']#output model = Decisi...
<h2>Errors in your code</h2> <p>When you define X and Y for train, the matrix X will contain de column <code>Rank</code>. <strong>You should drop it too</strong>. Otherwise, your decision tree will be &quot;silly&quot;, because you are giving as input, the output. That's a huge mistake. Solving:</p> <pre><code>X = df.d...
python|jupyter-notebook|sklearn-pandas
0
372,790
65,336,903
Using photoshop to complete undersampling in tensorflow object detection?
<p>I'm currently training an object detection model using Tensorflow and I ran into a problem. I don't have enough samples to train my model effectively and it will take me a long time to get more samples. I was wondering if it could be a good idea to complete the remaining samples using photoshop or will I run into is...
<p>You have so many options:</p> <ol> <li><p><a href="https://github.com/aleju/imgaug#imgaug" rel="nofollow noreferrer">imgaug</a></p> </li> <li><p><a href="https://github.com/albumentations-team/albumentations#albumentations" rel="nofollow noreferrer">albumentations</a></p> </li> <li><p><a href="https://github.com/mdb...
tensorflow|machine-learning|object-detection|photoshop
1
372,791
65,377,858
Python weekly dataframe between two dates
<p>I have a dataframe below:</p> <pre><code> Code First End 0 A2M 31/03/2018 29/09/2020 1 AAN 31/03/2007 29/06/2007 2 AAP 31/12/1999 29/09/2000 3 ABB 30/06/2009 29/06/2009 4 ABC 31/12/2009 29/06/2019 5 ABS 31/03/2006 30/03/2008 6 ADP 31/12/1999 29/06/2003 7 AEO 31...
<p>Create a date_range, and then use <code>explode</code></p> <pre><code># pandas version: 1.1.4 df['date_rng'] = df.apply(lambda x: pd.date_range(x['First'], x['End'], freq='7D'), axis=1) df_exploded = df.explode(&quot;date_rng&quot;) result = df_exploded[['Code', 'date_rng']] result.columns = ['ticker', 'date'] </co...
python|pandas|date
2
372,792
65,137,558
Trying to use df.columns to get list of headers in Pandas Dataframe
<p>I made a pandas dataframe, but when I call df.columns I get RangeIndex(start=0, stop=17, step=1). What is happening? I just want to get a list of my headers</p>
<p>This post covers your question in detail: <a href="https://stackoverflow.com/questions/19482970/get-list-from-pandas-dataframe-column-headers">Get list from pandas DataFrame column headers</a></p> <p>Briefly, you can use: <code>df.columns.tolist()</code> or <code>df.columns.values.tolist()</code></p>
python|pandas
0
372,793
65,233,769
Weighted average across multiple dataframes
<p>I have several dataframes of identical dimensions, say df1 and df2.</p> <p>I want to create a third dataframe, say avg_df, that is a weighted average of the respective values in df1 and df2. Say I want to be df1 weighted with a factor of 2 and df2 with a factor of 1.</p> <p>I have another problem, in that some colum...
<p>If you really want to disregard the string column, and you are certain the two <code>df</code> are the same shape, then you can do this:</p> <pre><code>sel = ['b', 'c'] # numeric columns df3 = df1.copy() df3[sel] = 2/3 * df1[sel] + 1/3 * df2[sel] </code></pre> <p>On your data, <code>df3</code> is:</p> <pre><code> ...
python|pandas|dataframe
1
372,794
65,205,742
Creating a numpy array from repeating a function n times with random behavior inside the function without for loops
<p>I am doing optimizations in my code and would like to remove this for loop if possible. I have the following code:</p> <pre><code> def f(x): return np.pi * x * np.cos((np.pi / 2) * x ** 2) def monte_carlo(b, n): xrand = np.random.uniform(0, b, (1, n)) integral = np.sum(f(xrand)) ...
<p>You can basically do all the 100 iterations or how many ever you want in a single shot. See the code below-</p> <pre class="lang-py prettyprint-override"><code>def f(x): return np.pi * x * np.cos((np.pi / 2) * x ** 2) def monte_carlo(b, n, N): xrand = np.random.uniform(0, b, (N, n)) integral = np.sum(f...
python|numpy|for-loop|optimization|random
1
372,795
65,147,372
Plot Dataframe doesn't start from the beginning with matplotlib.axes.plot()
<p>I got a dataframe <code>Filled_series</code>:</p> <pre><code>2015-05-03 0.00000 2015-05-09 NaN 2015-05-15 7.27943 2015-05-21 NaN 2015-05-27 7.26766 ... 2019-10-03 12.96608 2019-10-09 9.42112 2019-10-15 6.36359 2019-10-21 10.27396 2019-10-27 9.76496 Nam...
<p>The plotting works fine, <strong>but</strong> the plotting function can't plot a line between a point and a <code>NaN</code>. If you force <code>matplotlib</code> to plot <em>markers</em> (e.g. by line style <code>-o</code>), you can see that it plots the non-<code>NaN</code>-points but won't produce a line from th...
python|pandas|matplotlib
1
372,796
65,421,907
Does this occur because there is an NaN?
<p>I have a list of floats, and when I try to convert it into series or dataframe</p> <pre><code>code 000001.SZ 1.305442 000002.SZ 1.771655 000004.SZ 2.649862 000005.SZ 1.373074 000006.SZ 1.115238 ... 601512.SH 16.305734 688123.SH 53.395579 603995.SH 19.598881 688268.SH ...
<pre><code>Ser=pd.DataFrame([[1,2,3,4,None],[2,3,4,5,np.nan]]) Ser=Ser.replace(np.nan,0) </code></pre> <p>You can do it like this. There are also other functions in pandas like fillna().:)</p>
python|pandas
0
372,797
65,380,037
Converting Nested JSON to pandas dataframe with specific condition
<p>Consider the JSON(a snippet of orignal JSON) below</p> <pre><code>{ &quot;Data&quot;: { &quot;abc&quot;: [ { &quot;Month&quot;: &quot;1990-01-01&quot;, &quot;Country&quot;: &quot;BEL&quot;, &quot;Version&quot;: &quot;12345&quot;, ...
<p>Try this:</p> <pre><code>cs=list(c['Data'].values())[0] </code></pre>
python|json|pandas|api
0
372,798
65,327,203
Pandas if column contains string then write to second dataframe
<p>I have two dataframes. I want to be able to search column(snippet_matched) from DF2 for see if it has a partial match with anything from column(Search) in DF1. if it does contain it I then want to write &quot;Yes&quot; to DF1 column(HR). Is something like this possible?</p> <p>df1</p> <pre><code>Number Search ...
<p>You can create a function for the partial matching and apply it on the df1['Search'] column. See below:</p> <pre><code>def match(cell, column): column=[set(i.split()) for i in column] cell=set(cell.split()) return 'Yes' if any(k-cell==set() for k in column) else 'No' df1['HR']=df1['Search'].apply(lambda...
python|pandas|dataframe
1
372,799
65,165,632
Find area between black contours
<p>I have a white contour, with black inside and around. I need to find the biggest circle that have only white areea inside, without holes, and does not contain black area from outside of the contour. For now, I can not find good way to do so. I am using openCv and Numpy in Python. of course if any other library is ne...
<p>you can do a distance transform (in OpenCV).</p> <p>invert picture so the fringes are white (true) and center is black (false). you may have to threshold your image, maybe remove the smudge in the middle.</p> <p>apply distance transform with L2 distance (euclidean).</p> <p>find highest peak (<code>minMaxLoc</code>)....
python|numpy|opencv
0