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
10,000
66,691,392
groupby agg with first non-null unique value
<p>Following code gives error</p> <pre><code>import pandas as pd import numpy as np df=pd.DataFrame({&quot;item&quot;:['a','a','b'],&quot;item1&quot;:['b','d','c']}) df.groupby(&quot;item&quot;).agg(model_list=(&quot;item1&quot;, np.unique)) </code></pre> <p>Since there are two unique values for item <code>a</code> (i...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.first.html" rel="nofollow noreferrer"><code>GroupBy.first</code></a> which by default remove missing values, so returned first non missing value:</p> <pre><code>df=pd.DataFrame({&quot;item&quot;:['a','a','b','b','b'],&...
pandas
1
10,001
57,408,216
Python List - set every n-th value None
<p>As the title says, i want to know how to set every n-th value in a python list as Null. I looked after a solution in a lot of forums but i didn't find much. I also don't want to overwrite existing values as None, instead i want to create new spaces with the value None</p> <p>The list contains the date (12 dates = 1...
<p>If I understood correctly:</p> <pre><code>import pandas as pd numdays = 370 date1 = '1990-01-01' date2 = '2019-06-01' mydates = pd.date_range(date1, date2,).tolist() date_all = pd.date_range(start=date1, end=date2, freq='1BMS') date_lst = [date_all] for i in range(12,len(mydates),13): # add this mydates.insert...
python|pandas|list
1
10,002
57,705,976
How to pad an array with rows
<p>I have a set of numpy arrays with different number of rows and I would like to pad them to a fixed number of rows, e.g.</p> <p>An array "a" with 3 rows: </p> <pre><code>a = [ [1.1, 2.1, 3.1] [1.2, 2.2, 3.2] [1.3, 2.3, 3.3] ] </code></pre> <p>I would like to convert "a" to an array with 5 rows:</p> <pre><code...
<p>You're looking for <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html" rel="nofollow noreferrer"><code>np.pad</code></a>. To zero pad you must set mode to <code>constant</code> and the <code>pad_width</code> that you want on the edges of each axis:</p> <pre><code>np.pad(a, pad_width=((0,2)...
python|numpy
2
10,003
70,643,487
create a column that is the sum of previous X rows where x is a parm given by a different column row
<p>Im trying to create a column where i sum the previous x rows of a column by a parm given in a different column row.</p> <p>I have a solution but its really slow so i was wondering if anyone could help do this alot faster.</p> <pre><code>| time | price |parm | |--------------------------|---...
<p>Maybe something like this could work. I have made up an example with to_be_summed being the column of the value that should be summed up and looback holding the number of rows to be looked back</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({&quot;to_be_summed&quot;: range(10), &quot;lookback&...
python|pandas|numpy|optimization|sum
0
10,004
51,549,631
Merge specific rows pandas df
<p>I'm currently merging all values in a pandas df row before any 4 letter <code>string</code>. But I'm hoping to apply this specific rows instead of all rows. Specifically, I only want to apply it to rows directly underneath <code>X</code> in <code>Col A</code>. So if it's <code>X</code> apply function to the row unde...
<p>We need to create a mask for row-under-X condition as well. I prepared a series <code>maskX</code> for that and then used this to update the <code>mask</code> you prepared. Net result is the desired output. </p> <pre><code>d = ({ 'A' : ['X','Foo','No','X','Foo','X','F'], 'B' : ['','Bar','Merge','','Barr',''...
python|pandas|sorting|dataframe|merge
0
10,005
51,189,988
Impossible to use keras in R
<p>I have been trying to install Keras in R. Previously I have done that in another machine , it worked well there, but now i am facing problems.</p> <p>Codes: </p> <pre><code>library(devtools) devtools::install_github("rstudio/reticulate") devtools::install_github("rstudio/keras") devtools::install_github("rstudio/t...
<p>I was able to install and use Keras in R using the following commands. I haven't faced any issues.</p> <pre><code>devtools::install_github(&quot;rstudio/keras&quot;) library(keras) install_keras() </code></pre>
tensorflow|keras
0
10,006
51,972,807
Align stacked bar charts usind pandas
<p>I'm trying to align all of the stacked bar charts having the same index. What's the best way of doing this?</p> <p><a href="https://i.stack.imgur.com/24FEA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/24FEA.png" alt="stacked_bar_plots"></a></p> <p>This is my code so far:</p> <pre><code>xanth...
<p>Here's the relevant code (should work if you put it at the bottom of the script in the question):</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt ... ... ... # Comment out old plot # ax = df.plot.bar(stacked=True, title="Zeitbedarf der einzelnen Abschnitte (Xanthomonas)", xlim=...
python|pandas|stacked
0
10,007
51,956,198
Ravel() on only two dimensions of a 3D numpy array
<p>I have a numpy array of shape <code>(182, 218, 182)</code>. </p> <p>I'm trying to reorganize it such that it is size <code>(182, 39676)</code> - e.g., take each of the 182 slices of it and ravel() out each of those slices into one dimension, but still keep the slices separate.</p> <p>I can think of a few ways of d...
<pre><code>import numpy # initialize a[182][218][182] a=numpy.reshape(a,(182,39676)) </code></pre> <p>This reshape should do the work.</p>
python|numpy
0
10,008
51,768,418
Python code to process CSV file
<p>I am getting the CSV file updated on daily basis. Need to process and create new file based on the criteria - If New data then should be tagged as New against the row and if its an update to the existing data then should be tagged as Update. How to write a Python code to process and output in CSV file as follows bas...
<p>I'm feeling nice, so I'll give you some code. Try to learn from it.</p> <hr> <p>To work with CSV files, we'll need the <code>csv</code> module:</p> <pre><code>import csv </code></pre> <p>First off, let's teach the computer how to open and parse a CSV file:</p> <pre><code>def parse(path): with open(path) as ...
python|pandas|csv
1
10,009
36,224,581
pandas crashes on series with multiple data types
<p>I have a simple excel file with two columns - one categorical column and another numerical column that i read into pandas with the read_excel function as below</p> <pre><code>df= pd.read_excel('pandas_crasher.xlsx') </code></pre> <p>The first column is of type Object with multiple types. Since the excel was badly ...
<p>For me, the crash seems to happen when pandas tries to sort the group keys. If I pass the <code>sort=False</code> argument to <code>.groupby()</code> then the operation succeeds. This may work for you as well. The sort appears to be a numpy operation that doesn't actually involve pandas objects, so it may ultimat...
python|excel|pandas|group-by|crash
1
10,010
36,225,177
Pandas read_sql() of a view keeps double quotes in columns with spaces
<p>I have an sqlite database with a view of several tables with a lot of columns with spaces in their names (I know, I know, not good practice, but it's out of my control). </p> <p>Anyways, so the problem that I'm having is related to the spaces in the column names when using <code>pd.read_sql('SELECT "stupid column ...
<p>This is apparently an issue with the version of sqlite that python 2.7 uses that will not be officially fixed (<a href="http://bugs.python.org/issue19167" rel="nofollow noreferrer">http://bugs.python.org/issue19167</a>). </p> <p>If you want to still use python 2.7 or below, you can replace the <code>sqlite.dll</c...
python|sqlite|pandas
0
10,011
41,750,186
Using k-nearest neighbour without splitting into training and test sets
<p>I have the following dataset, with over 20,000 rows:</p> <p><a href="https://i.stack.imgur.com/RlM5s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RlM5s.png" alt="enter image description here"></a></p> <p>I want to use columns A through E to predict column X using a k-nearest neighbor algorith...
<blockquote> <p>To do this, I tried to implement my own k-nearest algorithm by calculating the Euclidean distance for each row from every other row, finding the k shortest distances, and averaging the X value from those k rows. This process took over 30 seconds for just one row, and I have over 20,000 rows. Is there ...
python|numpy|machine-learning|scikit-learn|nearest-neighbor
1
10,012
41,942,960
Python randomly drops to 0% CPU usage, causing the code to "hang up", when handling large numpy arrays?
<p>I have been running some code, a part of which loads in a large 1D numpy array from a binary file, and then alters the array using the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer">numpy.where()</a> method. </p> <p>Here is an example of the operations perf...
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a> is creating a copy there and assigning it back into <code>arr</code>. So, we could optimize on memory there by avoiding a copying step, like so -</p> <pre><code>vol_avg = (np.sum(arr) ...
python|arrays|numpy
1
10,013
37,671,974
Tensorflow negative sampling
<p>I am trying to follow the udacity tutorial on tensorflow where I came across the following two lines for word embedding models:</p> <pre><code> # Look up embeddings for inputs. embed = tf.nn.embedding_lookup(embeddings, train_dataset) # Compute the softmax loss, using a sample of the negative labels each time....
<p>You can find the documentation for <code>tf.nn.sampled_softmax_loss()</code> <a href="https://www.tensorflow.org/api_docs/python/tf/nn/sampled_softmax_loss" rel="noreferrer">here</a>. There is even a good explanation of <strong>Candidate Sampling</strong> provided by TensorFlow <a href="https://www.tensorflow.org/ex...
python|tensorflow
12
10,014
37,889,843
Find rank and percentage rank in list
<p>I have some very large lists that I am working with (>1M rows), and I am trying to find a fast (the fastest?) way of, given a float, ranking that float compared to the list of floats, and finding it's percentage rank compared to the range of the list. Here is my attempt, but it's extremely slow:</p> <pre><code>X =[...
<p>Sorting the array seems to be rather slow. If you don't need the array to be sorted in the end, then numpy's boolean operations are quicker.</p> <pre><code>arr = np.array(X) bool_array = arr &lt; val # Returns boolean array RANK = float(np.sum(bool_array)) PCT_RANK = RANK/len(X) </code></pre> <p>Or, better yet, u...
python|performance|numpy|pandas|rank
6
10,015
31,546,867
Creating legend in matplotlib after plotting two Pandas Series
<p>I plotted two Pandas Series from the same DataFrame with the same x axis and everything worked out fine. However, when I tried to manually create a Legend, it appears but only with the title and not with the actually content. I've tried other solutions without any luck. Here's my code:</p> <pre><code> fig = plt....
<p>Maybe you have a good reason to do it your way, but if not, this is much easier:</p> <pre><code>In [1]: import pandas as pd import numpy as np import matplotlib.pyplot as plt # Optional, just better looking import seaborn as sns # Generate random data df = pd.DataFrame(np.random.randn(10,3), columns=['tally', 'cost...
python|pandas|matplotlib|plot
3
10,016
47,723,508
How do I extract the particular row from .csv file and write out in to another file
<p>I have .csv file something like this:</p> <pre><code>x, y, z 1, 10, 45 2, 0, 34 4, 15, 34 5, 99, 38 6, 13, 23 5, 99, 38 6, 13, 23 . . . 1000, 234, 678 </code></pre> <p>now I would like to write out the rows of column x, which can be advisable by 5 form this .csv file.</p> <p>He...
<p>If you want to write out each 5th row you can simply do</p> <pre><code>df.iloc[::5, :].to_csv('file_name.csv') </code></pre> <p>whereby <code>df</code> is a pandas dataframe created like this:</p> <pre><code>import pandas as pd df = pd.read_csv('input.csv') </code></pre> <p>Otherwise, you can also do</p> <pre><...
python|pandas|csv|numpy|anaconda
2
10,017
48,950,424
What is the value of 10j in SciPy?
<p>I am learning Python and SciPy. I met below two expressions: </p> <pre><code>a = np.concatenate(([3], [0]*5, np.arange(-1, 1.002, 2/9.0))) </code></pre> <p>and </p> <pre><code>b = np.r_[3,[0]*5,-1:1:10j] </code></pre> <p>The two expressions output the same array. I don't understand 10j in the 2nd expression. Wha...
<p>It's a shorthand for creating an <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html" rel="nofollow noreferrer"><code>np.linspace</code></a>.</p> <p>As per the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html" rel="nofollow noreferrer">docs for <code>np.r_</c...
python|arrays|numpy|scipy
3
10,018
58,888,092
How to remove a rough line artifact from image after binarization
<p>I am stuck in a problem where I want to differentiate between an object and the <a href="https://i.stack.imgur.com/5BU7o.jpg" rel="nofollow noreferrer">background</a>(having a semi-transparent white sheet with backlight) i.e a fixed rough line introduced in the background and is merged with the object. My algorithm ...
<p>Since you are already using connectedComponents the best way is to exclude, not only the ones which are small, but also the ones that are touching the borders of the image. You can know which ones are to be discarded using <code>connectedComponentsWithStats()</code> that gives you also information about the bounding...
python|numpy|opencv|image-processing|image-thresholding
0
10,019
58,708,819
How to calculate growth in percentage between rows in a Pandas DataFrame?
<p>I have a data-frame such as:</p> <pre><code> A B(int64) 1 100 2 150 3 200 </code></pre> <p>now I need to calculate the growth rate and set it as an additional column such as: </p> <pre><code> A C 1 naN 2 50% 3 33.33% </code></pre> <p>how can I achieve that? Thank you so much for your help!<...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.pct_change.html" rel="nofollow noreferrer"><code>Series.pct_change</code></a> with multiple by <code>100</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mul.html" rel="nofollow noreferrer...
python|pandas|dataframe
4
10,020
56,088,440
Append columns to a DataFrame using apply and compute new columns based on existing values using apply on the row
<p>Given a DataFrame </p> <pre class="lang-py prettyprint-override"><code> a b c d 1 5 5 5 5 2 5 5 5 5 3 5 5 5 5 </code></pre> <p>I would like to add more columns on the DataFrame based on the existing ones but using some logic that can't fit in a lambda. The desired result should look something like this:</p> <pr...
<p>Use:</p> <pre><code>print (df) a b c 1 89 11 4 2 91 9 10 3 99 17 5 thresholds = { 'a': {'warning': 90, 'critical': 98, 'operation': 'lt'}, 'b': {'warning': 10, 'critical': 15, 'operation': 'gt'}, 'c': {'warning': 5, 'critical': 9, 'operation': 'le'} } import operator ops = {'gt':...
python|pandas|dataframe|series
1
10,021
56,387,827
How do I retain the column name used in my group by with Pandas
<p>I have two data frames. I would like to use group by on the second data frame and then merge the two together on the Company Name column. The issue is that with my group by statement I loose the Company Name column. </p> <pre><code>import pandas as pd df1 = pd.DataFrame( { 'Company Name': ['Google','Go...
<p>Replace this line:</p> <pre><code>df = df.groupby(['Company Name']).sum() </code></pre> <p>With:</p> <pre><code>df = df.groupby('Company Name', as_index=False).sum() </code></pre> <p>Then your code will work as expected, and return:</p> <pre><code> Company Name Location Sales 0 Google Somewhere 2469...
python|pandas|pandas-groupby
2
10,022
56,434,677
How do I remove duplicates based on not only one but two conditions from other columns
<p>I am trying to remove the duplicated "Box" rows based on two columns in my Dataframe:</p> <p><a href="https://i.stack.imgur.com/3Dr4p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Dr4p.png" alt="enter image description here"></a></p> <pre><code>import pandas as pd d = {'Box': ['A1', 'A1', 'A2...
<p><code>DataFrame.drop_duplicates(...)</code> defaults to keeping the first item it finds based on the subset of columns you specify.</p> <p>In other words, <code>df.drop_duplicates('Box')</code> will keep the first of each unique value of <code>Box</code> and drop the rest.</p> <p>So we just need to sort our data f...
python|pandas|dataframe|duplicates
0
10,023
56,133,320
How to remove special characters from csv using pandas
<p>Currently cleaning data from a csv file. Successfully mad everything lowercase, removed stopwords and punctuation etc. But need to remove special characters. For example, the csv file contains things such as 'César' '‘disgrace’'. If there is a way to replace these characters then even better but I am fine with ...
<p>When saving the file try:</p> <pre><code>df.to_csv('clean_soccer.csv', encoding='utf-8-sig') </code></pre> <p>or simply</p> <pre><code>df.to_csv('clean_soccer.csv', encoding='utf-8') </code></pre>
python|pandas|csv|data-cleaning
1
10,024
56,381,714
Is there anyway to reset multi index in pandas?
<p>I want to obtain stock data using pandas_datareader. I have the data, but the index I got is <code>multiIndex. _data.columns</code></p> <pre><code>MultiIndex(levels=[['High', 'Low', 'Open', 'Close', 'Volume', 'Adj Close'], ['MSFT']], codes=[[0, 1, 2, 3, 4, 5], [0, 0, 0, 0, 0, 0]], names=['Attr...
<p>There are several "Price" Columns to choose from. I chose <code>'Adj Close'</code>. This is mostly the same as <a href="https://stackoverflow.com/questions/56381714/is-there-anyway-to-reset-multi-index-in-pandas/56382230#comment99364733_56381714">ChrisA</a>'s comment.</p> <pre><code>_data.stack()['Adj Close'].res...
python|pandas
3
10,025
55,898,944
Matplotlib: how to display a line with different colors base on the line data
<p>I have a numpy array which takes only two values <code>0.0018</code> and <code>0.0018001</code></p> <pre><code>price_high_y = [0.0018 0.0018 0.0018 0.0018001 0.0018001 0.0018 0.0018 0.0018] </code></pre> <p>What I would like to do is to display this line with the values 0.0018 in black and 0.0018001 in yellow. It ...
<p>Is this what you want</p> <pre><code>price_high_y = np.array([0.0018, 0.0018, 0.0018, 0.0018001, 0.0018001, 0.0018, 0.0018, 0.0018]) yvals = sorted(np.unique(price_high_y)) colors = {0.0018: 'k', 0.0018001: 'y'} for i, y in enumerate(yvals): plt.axhline(i+0.5, color=colors[y]) plt.yticks(np.arange(len(yvals)...
python|pandas|matplotlib
0
10,026
64,673,064
Shape gets changed when preprocessing with column transformer and predicting the testing data
<p>The data structure is like below.</p> <pre><code>df_train.head() ID y X0 X1 X2 X3 X4 X5 X6 X8 ... X375 X376 X377 X378 X379 X380 X382 X383 X384 X385 0 0 130.81 k v at a d u j o ... 0 0 1 0 0 0 0 0 0 0 1 6 88.53 k t av e d y ...
<p>I have tried to create a Minimal Reproducible Example of your problem, and I do not run into any errors myself. Can you run it on your side? See if there are any important differences between the dataframe created here and yours?</p> <p>Note that:</p> <ul> <li>When transforming your test data, you should only transf...
python|python-3.x|pandas|scikit-learn|linear-regression
1
10,027
64,973,770
PyToch: ValueError: Expected input batch_size (256) to match target batch_size (128)
<p>I've faced a ValueError while training a BiLSTM part of speech tagger using pytorch. <strong>ValueError: Expected input batch_size (256) to match target batch_size (128).</strong></p> <pre><code>def train(model, iterator, optimizer, criterion, tag_pad_idx): epoch_loss = 0 epoch_acc = 0 model.tr...
<p><em>(continuing from the comments)</em></p> <p>I guess that your batch-size is equal to 128 (its nowhere defined), right? The LSTM outputs a list of the outputs of every timestep. But for classification you normaly just want the last one. So the first dimension of <code>outputs</code> is your sequence length which i...
python|neural-network|pytorch|lstm|part-of-speech
0
10,028
40,041,076
Optimize Python code. Optimize Pandas apply. Numba slow than pure python
<p>I'm facing a huge bottleneck where I apply a method() to each row in Pandas DataFrame. The execution time is in sorts of 15-20 minutes.</p> <p>Now, the code I use is as follows:</p> <pre><code>def FillTarget(self, df): backup = df.copy() target = list(set(df['ACTL_CNTRS_BY_DAY'])) df = df[~df['ACTL_CN...
<p>This is a bit rushed solution because I'm about to leave into the weekend now, but it works.</p> <p>Input Dataframe:</p> <pre><code>index APPT_SCHD_ARVL_D ACTL_CNTRS_BY_DAY 919 2020-11-17 NaN 917 2020-11-17 NaN 916 2020-11-17 NaN 915 2020-11-...
python|pandas|optimization|jit|numba
1
10,029
39,530,157
Python numpy nonzero cumsum
<p>I want to do nonzero <code>cumsum</code> with <code>numpy</code> array. Simply skip zeros in array and apply <code>cumsum</code>. Suppose I have a np. array </p> <pre><code>a = np.array([1,2,1,2,5,0,9,6,0,2,3,0]) </code></pre> <p>my result should be</p> <pre><code>[1,3,4,6,11,0,20,26,0,28,31,0] </code></pre> <p>...
<p>You need to mask the original array so only the non-zero elements are overwritten:</p> <pre><code>In [9]: a = np.array([1,2,1,2,5,0,9,6,0,2,3,0]) a[a!=0] = np.cumsum(a[a!=0]) a Out[9]: array([ 1, 3, 4, 6, 11, 0, 20, 26, 0, 28, 31, 0]) </code></pre> <p>Another method is to use <code>np.where</code>:</p> <pr...
python|numpy
3
10,030
69,662,602
Drop % of rows that do not contain specific string
<p>I want to drop 20% of rows that do not contain 'p' or 'u' in label column. I know how to drop all of them, but I do not know how to drop certain percent of rows. This is my code:</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;text&quot;: [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quo...
<p>Use:</p> <pre><code>#for unique indices df = df.reset_index(drop=True) #get mask for NOT contains p or u m = ~df[&quot;label&quot;].str.contains('p|u') #get 20% Trues from m #https://stackoverflow.com/a/31794767/2901002 mask = np.random.choice([True, False], m.sum(), p=[0.2, 0.8]) #filter both masks and remove ro...
python|pandas
2
10,031
53,943,248
Find duplicated rows, multiply a certain column by number of duplicates, drop duplicated rows
<p>I have a pandas dataframe of about 70000 rows, and 4500 of them are duplicates of an original. The columns are a mix of string columns and number columns. The column I'm interested in is the <code>value</code> column. I'd like to look through the entire dataframe to find rows that are completely identical, count the...
<p>I think this question is nothing more of figuring out how to get a count of the occurrences of each unique row. If a row occurs only once, this number is one. If it occurs more often, it will be > 1. This count you can then use to multiply, filter, etc.</p> <p>This nice one-liner (taken from <a href="https://stacko...
python|pandas|dataframe|duplicates
1
10,032
54,228,133
How to merge list of tuples
<p>I have two lists of tuples like this:</p> <pre><code>x1 = [('A', 3), ('B', 4), ('C', 5)] x2 = [('B', 4), ('C', 5), ('D', 6)] </code></pre> <p>I want to merge the two lists as a new one x3 so that the values in the list are added.</p> <pre><code>x3 = [('A', 3), ('B', 8), ('C', 10),('D',6)] </code></pre> <p>Could...
<p>You can create a dictionary and then loop over the values in each list, and either adding to the current value for each key in the dictionary, or setting the value equal to the current value if no value currently exists. Afterwards you can cast back to a list.</p> <p>For example:</p> <pre><code>full_dict = {} for ...
python|pandas|list
6
10,033
53,952,470
Matrix Subtract like Matrix Multiplication in tensorflow
<p>This is my first post I usually found all my answers in the archives, but having a hard time with this one, thanks for the help!</p> <p>I have two matrix A and B. Performing a matrix multiplication operation is trivial using tf.matmult. But I want to do matrix subtract similar to how matrix multiplication works. ...
<p>Trying a vectorization operation that may not be taken as matrix subtract.</p> <pre><code># shape=(2,3,6) B_new = tf.tile(tf.expand_dims(B,axis=-1),multiples=[1,1,A.shape[1]]) # shape=(2,3,6) A_new = tf.tile(tf.expand_dims(A,axis=0),multiples=[B.shape[0],1,1]) # shape=(2,6) result = tf.reduce_sum(tf.square(A_new - ...
python|tensorflow|matrix|matrix-multiplication
0
10,034
53,893,869
How to create a range of time in Python?
<p>I want to iterate over the value of an hour to plot the number of trips in each hour. </p> <p>I have found no solution on the internet to how to solve this problem. Can one tell me how to do this?</p>
<p>You can find a best documentation at <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html</a>.</p> <p>Please have a look at the below example.</p> <pre><code>&gt;&gt;&gt; impor...
python|python-3.x|pandas
2
10,035
38,107,979
From tuples to linear equations with numpy
<p>i need help in the following topic. Lets say i have three points, each with x, y coordinates and a corresponding z value, e.g.:</p> <pre><code>p_0 = (x_0, y_0, z_0) : coordinates of first point p_1 = (x_1, y_1, z_1) : coordinates of second point p_2 = (x_2, y_2, z_2) : coordinates of third point </code></pre> <p>L...
<p>You could use</p> <pre><code>p = np.row_stack([p_0, p_1, p_2]) B = np.ones_like(p) # copy the first two columns of p into the last 2 columns of B B[:, 1:] = p[:, :2] z = p[:, 2] </code></pre> <hr> <p>For example,</p> <pre><code>import numpy as np p_0 = (1,2,3) p_1 = (4,-5,6) p_2 = (7,8,9) p = np.row_stack([p_0...
python|numpy|matrix|interpolation|linear-algebra
1
10,036
65,934,904
groupby and get min then append values of the min row
<p>I use groupby and then minimum as aggregation function. I need some other values of the row with the minimum value. In the following MWE, I need <code>City</code> value of the row with the minimum distance <code>mindist</code>.</p> <pre><code>import pandas as pd data = {'City' : ['London', 'Paris', 'Lyon','NY', 'Bri...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> by <code>Distance</code> with <code>City</code> <code>Series</code>:</p> <pre><code>df['City1'] = df['mindist'].map(df.set_index('Distance')['City']) print(df) Ci...
pandas|pivot-table
1
10,037
65,938,535
passing an iterator to fit/train/predict functions - is it possible?
<p>i wonder if theres a way to pass an iterator like into those varius sk models for example: random-forest/logistic regression etc.</p> <p>i have a tensor flow dataset can fetch from there a numpy iterator but cannot use it in those functions.</p> <p>any solution?</p> <pre><code>xs = tfds.as_numpy(tf.data.Dataset.from...
<p>An example of fitting and testing a model with your data stored in a list is below:</p> <pre class="lang-py prettyprint-override"><code> # Import some libraries from sklearn.datasets import make_classification from sklearn.linear_model import LogisticRegression from sklearn.model_selection import trai...
scikit-learn|tensorflow-datasets
0
10,038
52,745,193
variable colons for indexing in Python
<p>Suppose I have a Numpy array <strong>A</strong> that has a certain number of dimensions. For the rest of the question I will consider that <strong>A</strong> is a 4-dimensional array:</p> <pre><code>&gt;&gt;&gt;A.shape (2,2,2,2) </code></pre> <p>Sometimes, I would like to access the elements </p> <pre><code>A[:,...
<p>When you provide a <code>:</code> when indexing, python calls that a <a href="https://docs.python.org/3/library/functions.html#slice" rel="nofollow noreferrer"><code>slice</code></a>. When you provide comma-separated slices, it is really just a tuple of slices.</p> <p>The <code>:</code> is equivalent to <code>slic...
python|numpy|indexing
0
10,039
52,457,989
pandas df.apply unexpectedly changes dataframe inplace
<p>From my understanding, pandas.DataFrame.apply does not apply changes inplace and we should use its return object to persist any changes. However, I've found the following inconsistent behavior:</p> <p>Let's apply a dummy function for the sake of ensuring that the original df remains untouched:</p> <pre><code>&gt;&...
<p>Interesting question! I believe the behavior you're seeing is an artifact of the way you use <code>apply</code>.</p> <p>As you correctly indicate, <code>apply</code> is not intended to be used to modify a dataframe. However, since <code>apply</code> takes an arbitrary function, it doesn't guarantee that applying th...
python|pandas|dataframe|pandas-apply
3
10,040
46,186,352
Iterating over dataframe returns only column headers
<p>I'm trying to extract the latitude, longitude, magnitude and times from a csv which contains data from Earthquakes, in order to plot them into a map.</p> <p>My current code for the extraction of the data is:</p> <pre><code>import pandas as pd csv_path = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2...
<p>You have a pandas dataframe, not a file. Iteration over a dataframe gives you the <em>headers of the series</em>:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; filename = pd.read_csv('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_hour.csv', names = ['time','latitude','longitude','mag'...
python|pandas|matplotlib|dataframe|plot
5
10,041
58,530,060
Pandas Transform and add second line between the measurements
<p>I am struggeling with transforming a pandas dataframe.</p> <pre><code>df= 0 A -- cm 1 B -- cm2 2 C 69 cm/s 3 D 48 cm/s 4 E 152 ms 5 F 1.05 NaN 6 G 9.15 NaN 7 H -- ...
<p>You can stack and transpose since you will always have groupings of two.</p> <hr> <pre><code>u = df.set_index(0).stack().to_frame().T u.columns = [ x if y == 1 else f'{x}_Unit' for x, y in u.columns] </code></pre> <p></p> <pre><code> A A_Unit B B_Unit C C_Unit D D_Unit E E_Unit F G H H_U...
python-3.x|pandas|numpy
3
10,042
58,414,941
Lenth of values mismatch using np.where or how to write values based on condition into the new column
<p>Suppose I have a df: </p> <pre><code>A | B | aa| 11| aa| 12| aa| 13| ab| 11| ac| 11| ab| 12| ad| 11| ae| 11| </code></pre> <p>I'm trying to create third column and fill it depending on the next condition:<br> IF item in A has value 12 OR 13 - write 'yes in the C column. Else-write no.</p>...
<p>I think you need first test values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a> and then in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferr...
python|pandas|numpy
2
10,043
68,942,031
Merging dataframes, based on range
<p>I have been struggling my whole day on merging two datasets. One data set shows me an customer ID, paydate and product_code, the other one tells me the special deals the company made with the customer for a special period.</p> <ul> <li>customer = customer</li> <li>product_code = product_code</li> <li>date_from &lt;=...
<p>According to your example, you'll need to perform an <strong>outer merge</strong>.</p> <ol> <li>Import pandas</li> </ol> <pre><code>import pandas as pd </code></pre> <ol start="2"> <li>Create raw data (as an example)</li> </ol> <pre><code>customer_1 = ['A1', 'A1', 'A2', 'A2', 'A2', 'A2', 'A3', 'A3'] paydate = ['1-6-...
python|pandas|merge
-1
10,044
68,880,288
CNN feature Extraction
<pre><code>class ResNet(nn.Module): def __init__(self, output_features, fine_tuning=False): super(ResNet, self).__init__() self.resnet152 = tv.models.resnet152(pretrained=True) #freezing the feature extraction layers for param in self.resnet152.parameters(): param.requires_grad = fine_tunin...
<p>ResNet is not as straightforward as VGG: it's not a sequential model, <em>i.e.</em> there is some model-specific logic inside the <code>forward</code> definition of the <code>torchvision.models.resnet152</code>, for instance, the flattening of features between the CNN and classifier. You can take a look at <a href="...
python|machine-learning|deep-learning|pytorch|conv-neural-network
1
10,045
69,238,906
append to/insert a row with an index value into an indexed dataframe without losing the index name?
<p>Given the dataframe:</p> <pre><code>df = pd.DataFrame([{'myindex':1,'a':2,'b':3},{'myindex':2,'a':22,'b':33}]).set_index('myindex') </code></pre> <p>and a new row:</p> <pre><code>new_row = {'myindex':11,'a':20,'b':30} </code></pre> <p>Is the most parsimonious way of adding <code>new_row</code> to the dataframe to <c...
<p>You can try something like this:</p> <pre><code>df = df.append((pd.Series({'myindex':11,'a':20,'b':30}, name=new_row['myindex'])[1:])) # Output a b myindex 1 2 3 2 22 33 11 20 30 </code></pre>
pandas|indexing
0
10,046
44,407,873
Tensorflow: traning by batch stuck forever in sess.run
<p>I'm trying to train my model batch by batch, as I couldn't find any example to how to do it properly. This is as far as I can do, on my mission to find how to train a model batch by batch in Tensorflow.</p> <pre><code>queue=tf.FIFOQueue(capacity=50,dtypes=[tf.float32,tf.float32],shapes=[[10],[2]]) enqueue_op=queue....
<p>After couple hour of searching, I found the Solution myself. So, I'm answering my own question now below. The queues are filled by background threads, which are created when you call <code>tf.train.start_queue_runners()</code> If you don't call this method, the background threads will not start, the queues will rema...
python|python-3.x|tensorflow
5
10,047
61,160,328
Is it possible to train a model Tensorflow Object Detection API with Tensorflow 2.1?
<p>When training the model Tensorflow Object Detection API on Tensorflow-gpu 2.1, there is an error: </p> <p><strong>No module named 'tensorflow.contrib'</strong> </p> <p>Is it possible to train a model Tensorflow Object Detection API with Tensorflow 2.1?<br> I dont want to change the version of Tensorflow.<b...
<p>Tensorflow object detection API currently works only for Tensorflow 1.x (>=1.12.0), but it's in the works. </p> <p>See this Github thread: <a href="https://github.com/tensorflow/models/issues/6423" rel="nofollow noreferrer">https://github.com/tensorflow/models/issues/6423</a>. </p>
tensorflow|object-detection|object-detection-api|tensorflow2.x
1
10,048
71,530,521
pandas rolling window aggregating string column
<p>I am struggling when computing string aggregation operation using rolling window on pandas.</p> <p>I am given the current df, where <em>t_dat is</em> the purchase date, <em>customer_id</em> and <em>article_id</em> are self-explanatory.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>t_da...
<p>I was able to aggregate by the day. Create a second dataframe and accumulate by customer all articles per day. Use the pd.Grouper to create your 7 day rolling window!</p> <pre><code>data=&quot;&quot;&quot; t_dat customer_id article_id 2020-04-24 486230 781570001 2020-04-24 486230 598755030 2020-04-27 486230 ...
python|pandas|pandas-groupby|rolling-computation
0
10,049
71,526,523
handling million of rows for lookup operation using python
<p>I am new to data handling . I need to create python program to search a record from a samplefile1 in samplefile2. i am able to achieve it but for each record out of 200 rows in samplefile1 is looped over 200 rows in samplefile2 , it took 180 seconds complete execution time.</p> <p>I am looking for something to be mo...
<p>I don't think using Pandas is helping here as you are just comparing whole lines. An alternative approach would be to load the first file as a set of lines. Then enumerate over the lines in the second file testing if it is in the set. This will be much faster:</p> <pre><code>@timeit def func(): with open('sample...
python|pandas|csv|bigdata|dask
1
10,050
69,755,679
Creating numpy array from calculations across arrays
<p>I currently have the task of creating a 4x4 array with operations performed on the cells</p> <p>Below you will see a function that takes in <code>array</code> into function <code>the_matrix</code> which returns <code>adj_array</code></p> <p>It then has a for loop that is supposed to loop through <code>array</code>, ...
<p>Your <code>ref_array</code> is object dtype, (4,4) containing tuples:</p> <pre><code>In [26]: ref_array Out[26]: array([[(5, 0), (5, 1), (5, 2), (5, 3)], [(6, 0), (6, 1), (6, 2), (6, 3)], [(7, 0), (7, 1), (7, 2), (7, 3)], [(8, 0), (8, 1), (8, 2), (8, 3)]], dtype=object) </code></pre> <p>Your it...
python|arrays|numpy|matrix|nodes
1
10,051
43,285,133
How to write two variables in one line?
<p>I would like to write two variable in a file. I mean this is my code :</p> <pre><code>file.write("a = %g\n" %(params[0])) file.write("b = %g\n" %(params[1])) </code></pre> <p>and what I want to write in my file is :</p> <pre><code>f(x) = ax + b </code></pre> <p>where <code>a</code> is <code>params[0]</code> and...
<p>If all you want to write to your file is <code>f(x) = ax + b</code> where <code>a</code> and <code>b</code> are <code>params[0]</code> and <code>params[1]</code>, respectively, just do this:</p> <pre><code>file.write('f(x) = %gx + %g\n' % (params[0], params[1])) </code></pre> <p><code>'f(x) = %gx + %g' % (params[0...
python|python-2.7|python-3.x|numpy
1
10,052
43,406,111
Is GPU efficient on parameter server for data parallel training?
<p>On <a href="http://download.tensorflow.org/paper/whitepaper2015.pdf" rel="nofollow noreferrer">data parallel training</a>, I guess the GPU instance is not necessarily efficient for parameter servers because parameter servers only keep the values and don't run any computation such as matrix multiplication.</p> <p>Th...
<p>Your assumption is a reasonable rule of thumb. That said, Parag points to a paper that describes a model that can leverage GPUs in the parameter server, so it's not always the case that parameter servers are not able to leverage GPUs.</p> <p>In general, you may want to try both for a short time and see if throughpu...
machine-learning|tensorflow|google-cloud-ml|google-cloud-ml-engine
0
10,053
43,204,940
Using multiprocessing to create two arrays in python simultaneously
<p>I've written a python script that uses numpy to create two arrays from different sources of data and compares them to each other. Building the arrays is quite a slow process so I wanted to find a way of building them at the same time to speed the script up. I tried to do this using the multiprocessing module like th...
<p>that is pretty easy to fix. You see, with multiprocessing you have to seperate the function and the arguments:</p> <pre><code>p1 = Process(target=[some function], args=[(some arguments,other args)]) </code></pre> <p>Also, you shouldn't print Processes, but define in their function that they should print out someth...
python|arrays|numpy|multiprocessing
0
10,054
72,282,582
Trying to make an image classification model using AutoML Vision run on a website
<p>I've created a classification model using AutoML Vision and tried to use <a href="https://cloud.google.com/vision/automl/docs/tensorflow-js-tutorial?_ga=2.245966400.-55487651.1648514707&amp;_gac=1.61854174.1648905034.Cj0KCQjw6J-SBhCrARIsAH0yMZhG7bXhnNscFr09VIp9bK3x70O9dGFC2U-ZIHn3ZMtaW7FlOIQJ8E8aAk0_EALw_wcB" rel="n...
<p>models built with AutoML should not have dynamic ops, but seems that yours does.</p> <p>if that is truly model designed using AutoML, then AutoML should be expanded to use asynchronous execution.</p> <p>if model was your own (not AutoML), it would be a simple <code>await model.executeAsync()</code> instead of <code>...
tensorflow.js|google-cloud-automl
0
10,055
72,312,859
In Keras is it possible to see what were the predictions on each step during model.fit() or model.evaluate?
<p>I am fitting an ANN using Keras. As I don't trust the loss function output, I would like to see, what are the intermediate values that are compared to the target ones in order to calculate the loss after every epoch.</p> <pre><code>history = model.fit(X, Y, epochs=epoc,batch_size=bs) scores = model.evaluate(X, ...
<p>To get predictions for each epoch you have to create callbacks and declare a on_epoch_end function as shown in this <a href="https://www.tensorflow.org/guide/keras/custom_callback#a_basic_example" rel="nofollow noreferrer">document</a>.</p> <pre><code>class prediction_for_each_epoch(tf.keras.callbacks.Callback): ...
python|tensorflow|keras
0
10,056
72,158,678
How do I query more than one column in a data frame?
<p>I'm taking a Data Science class that uses Python and this is a questions that stumped me today. &quot;How many babies are named “Oliver” in the state of Utah for all years?&quot; To answer this question we were supposed to use data from this set <a href="https://raw.githubusercontent.com/byuidatascience/data4names/m...
<p>You have all the code there you just need one more line to Sum accordint to the state:</p> <pre><code>print(oliver.UT.sum()) # this will give you the total for the state of UTAH </code></pre> <p>and forget about the quiz.</p>
python|pandas|data-science
0
10,057
72,225,655
Extracting multiple sets of rows/ columns from a 2D numpy array
<p>I have a 2D numpy array from which I want to extract multiple sets of rows/ columns.</p> <pre><code># img is 2D array img = np.arange(25).reshape(5,5) array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]) </code></pre> <p>I k...
<p>IIUC, you can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.r_.html" rel="nofollow noreferrer"><code>numpy.r_</code></a> to generate the indices from the slice:</p> <pre><code>img[np.r_[0,2:4][:,None],2] </code></pre> <p>output:</p> <pre><code>array([[ 2], [12], [17]]) </code></p...
python|numpy|multidimensional-array|numpy-slicing
2
10,058
72,376,652
Need to find black point
<p>I have 2D array with x and y. I need to extract black point shown on graph. Point is before sudden increase. Also I paste data for x, y.</p> <p><strong>Does anyone have any idea how to get this point?</strong></p> <pre><code>x = [50,30,40,40,60,70,80,90,100,110,120,130,140,160,170,180,200,210,220,240,250,270,280,300...
<pre><code>min(zip(y, x)) </code></pre> <p>That would produce the <code>y</code> and the <code>x</code> coordinate of the point with the smallest <code>y</code> coordinate.</p>
python|pandas|numpy|scipy
1
10,059
50,519,983
How to apply a function to multiple columns in Pandas
<p>I have a bunch of columns which requires cleaning in Pandas. I've written a function which does that cleaning. I'm not sure how to apply the same function to many columns. Here is what I'm trying:</p> <pre><code>df["Passengers", "Revenue", "Cost"].apply(convert_dash_comma_into_float) </code></pre> <p>But I'm getti...
<p>Use double brackets [[]] as @chrisz points out:</p> <p>Here is a MVCE:</p> <pre><code>df = pd.DataFrame(np.arange(30).reshape(10,-1),columns=['A','B','C']) def f(x): #Clean even numbers from columns. return x.mask(x%2==0,0) df[['B','C']] = df[['B','C']].apply(f) print(df) </code></pre> <p>Output</p> <p...
pandas
9
10,060
50,504,670
group by two columns count in pandas
<p>I have a Pandas DataFrame like this :</p> <pre><code>df = pd.DataFrame({ 'Date': ['2017-1-1', '2017-1-1', '2017-1-2', '2017-1-2', '2017-1-3'], 'Groups': ['one', 'one', 'one', 'two', 'two']}) Date Groups 0 2017-1-1 one 1 2017-1-1 one 2 2017-1-2 one 3 2017-1-2 ...
<p>To get count of unique records use:</p> <pre><code>df.groupby('Date')['Groups'].nunique() </code></pre>
python|pandas
2
10,061
50,276,500
Adding time deltas to a running total in Pandas
<p><a href="https://i.stack.imgur.com/p2rSD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p2rSD.png" alt="enter image description here"></a></p> <p>So I have two columns of data in my dataframe. TimeDeltasDiffs and ActualTime. First row of the dataframe has a start time in the ActualTime column....
<p>You do not necessarily need to use .apply(). Consider below approach. Given that below is the <code>df</code></p> <pre><code> ActualTime TimeDeltasDiffs 0 2018-04-16 17:06:01 00:00:00 1 0 00:00:01 2 0 00:00:00 3 0 00:0...
python|pandas|timedelta
1
10,062
50,527,616
Changing value of matrix and assigning value
<p>The code below based on <a href="http://www.johnwittenauer.net/machine-learning-exercises-in-python-part-1/" rel="nofollow noreferrer">http://www.johnwittenauer.net/machine-learning-exercises-in-python-part-1/</a> works </p> <pre><code>theta = np.matrix(np.array([0, 0])) def computeCost(X, y, theta, iterations, ...
<p>A probable explanation: it is a problem of types (int vs float).</p> <p>The assignment </p> <pre><code>theta = np.matrix(np.array([0, 0])) </code></pre> <p>creates a matrix of integers. There is some implicit conversion to integers when you assign directly its coefficients:</p> <pre><code>&gt;&gt;&gt; m = np.mat...
python|numpy|machine-learning
0
10,063
50,446,949
PIL: fromarray gives a wrong object in P mode
<p>I want to load an image in <code>P</code> mode, transform it into <code>np.array</code> and then transform it back, but I got a wrong Image object which is a gray image, not a color one</p> <pre><code>label = PIL.Image.open(dir).convert('P') label = np.asarray(label) img = PIL.Image.fromarray(label, mode='P') img.s...
<p>Images in 'P' mode require a palette that associates each color index with an actual RGB color. Converting the image to an array loses the palette, you must restore it again.</p> <pre><code>label = PIL.Image.open(dir).convert('P') p = label.getpalette() label = np.asarray(label) img = PIL.Image.fromarray(label, mod...
python|numpy|machine-learning|python-imaging-library
2
10,064
45,637,245
How do I plot with matplotlib?
<p>How do I plot these using matplotlib or pandas' plot? </p> <p>I've tried this btw: </p> <pre><code>topic_count.plot.bar(stacked=True) </code></pre> <p>Which outputs : </p> <pre><code> &lt;matplotlib.axes._subplots.AxesSubplot at 0x118bdfeb8&gt; </code></pre> <p>and nothing else, I am not seeing a plot. please ...
<p>Crude example with matplotlib:</p> <pre><code>import matplotlib.pyplot as plt foo = [1, 2] plt.plot(foo) plt.show() </code></pre> <p>And this should show you something like this: <a href="https://i.stack.imgur.com/hBwzO.png" rel="nofollow noreferrer">Plot result</a></p> <p>Some references:</p> <ul> <li><a href="...
python|pandas|matplotlib|plot
4
10,065
62,766,171
Cutting a pandas DataFrame into small blocks and do simple calculations on each block
<p>I want to divide pandas DataFrame columns into blocks of 3 and find the mean of each block for each row.</p> <p>Towards that end, by using a for-loop, I created a list of DataFrames by cutting them into blocks of 3, found their mean and reshaped it back into the shape I want.</p> <p>The following code does the job:<...
<p>I think you can do it directly by specifying axis=1 in <code>mean</code> on the selection of the 3 columns in the list comprehension. then use it in <code>pd.concat</code></p> <pre><code>df_ = pd.concat([df.iloc[:,i:i+3].mean(axis=1) for i in range(0,df.shape[1],3)], axis=1, ignore_index=True) </cod...
python|pandas
1
10,066
62,685,261
Units of the last dense output layer in case of multiple categories
<p>I am currently working on this <a href="https://colab.research.google.com/github/lmoroney/dlaicourse/blob/master/TensorFlow%20In%20Practice/Course%203%20-%20NLP/Course%203%20-%20Week%202%20-%20Exercise%20-%20Answer.ipynb" rel="nofollow noreferrer">colab</a>. Task is to classify the sentences into a certain category....
<p>is 6 because the encode targets are in [1,5] but keras sparse_cat creates one-hot labels from 0 so it creates another unuseful label (0).</p> <p>to use <code>Dense(5, activation='softmax')</code> you simply can do y-1 in order to get labels in [0,4] and get them starting from 0</p> <p>following the colab link, you c...
python|tensorflow|keras|neural-network|cross-entropy
2
10,067
62,492,482
Using np.where, langdetect in pandas
<p>I want to add a new column in dataframe, which will paste the data from another column if it is written in English, and paste nothing if it is not in English using langdetect library.</p> <pre><code>df['lyrics_english'] = np.where(detect(df[&quot;lyrics&quot;]) == 'en', df[&quot;lyrics&quot;], '') </code></pre> <p>I...
<p>I guess might be due to some non-string values like <code>nan</code>, you can try:</p> <pre><code>df['lyrics_english'] = np.where(detect(df[&quot;lyrics&quot;].fillna(&quot;&quot;)) == 'en', df[&quot;lyrics&quot;], '') </code></pre> <p>If this doesn't work, then you need to look into <code>df[&quot;lyrics&quot;].uni...
python|pandas|numpy|dataframe|sentiment-analysis
0
10,068
54,518,161
TypeError from SciKit-Learn's LabelEncoder
<p>Here is my code:</p> <pre><code>#Importing the dataset dataset = pd.read_csv('insurance.csv') X = dataset.iloc[:, :-2].values X = pd.DataFrame(X) #Encoding Categorical data from sklearn.preprocessing import LabelEncoder labelencoder_X = LabelEncoder() X[:, 1:2] = labelencoder_X.fit_transform(X[:, 1:2]) </code></pr...
<p>Here is a small demo:</p> <pre><code>In [36]: from sklearn.preprocessing import LabelEncoder In [37]: le = LabelEncoder() In [38]: X = df.apply(lambda c: c if np.issubdtype(df.dtypes.loc[c.name], np.number) else le.fit_transform(c)) In [39]: X Out[39]: age sex bmi chil...
python|pandas|scikit-learn
1
10,069
73,600,444
Convert a column to timedelta and remove days from it
<p>I am trying to convert a column with data like this: 1:38:17 or 36:21 to timedelta format. This column is extracted from a website and converted to a table using pandas.</p> <pre><code>df[' Chip Time'] = df[' Chip Time'].apply(pd.to_timedelta, errors='coerce') </code></pre> <p>This returns 0 days 01:38:17 but for ro...
<p>I think you want to use <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pd.to_datetime</code></a> instead of <code>pd.to_timedelta</code>:</p> <pre><code>df[' Chip Time'] = pd.to_datetime(df[' Chip Time'], format='%H:%M:%S').dt.time </code></pre>
python|pandas|time
1
10,070
73,831,488
Iterate through all sheets of all workbooks in a directory
<p>I am trying to combine all spreadsheets from all workbooks in a directory into a single df. I've tried with <code>glob</code> and with <code>os.scandir</code> but either way I keep only getting the first sheet of all workbooks. First attempt:</p> <pre><code>import pandas as pd import glob workbooks = glob.glob(r&qu...
<p>If I understand what you have written correctly, you want something like this:</p> <pre><code>import pandas as pd import glob # list of workbooks in directory workbooks = glob.glob(r&quot;\mydirectory\*.xlsx&quot;) l = [] # for each file in list for file in workbooks: # Class for file allows for retrieving she...
python|pandas|glob
0
10,071
73,730,601
How to scale x axis which is increasing constantly using pandas
<p>I have 3 columns <code>v1</code>, <code>v2</code>, and <code>v3</code> with 10,000 entries and I want to plot <code>v1</code>, <code>v2</code>, and <code>v3</code> on the y-axis.</p> <p>In the x-axis, I want to plot <code>v1</code>, <code>v2</code>, <code>v3</code> points every 500 seconds until the length of column...
<p>How's something like this, it grabs every 500th row (and includes the last row) and plots it using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html" rel="nofollow noreferrer">Pandas plot</a>:</p> <pre class="lang-py prettyprint-override"><code>df[::500].append(df[-1:]).plot(y=['v1', '...
python|pandas|matplotlib
0
10,072
73,710,166
Efficient function mapping with arguments in numpy
<p>I am trying to create a heightmap by interpolating between a bunch of heights at certain points in an area. To process the whole image, I have the following code snippet:</p> <pre class="lang-py prettyprint-override"><code> map_ = np.zeros((img_width, img_height)) for x in range(img_width): for y in range(img_h...
<p>There's a few problems with your implementation.</p> <p>Essentially what you're implementing is approximation using radial basis functions.</p> <p>The usual algorithm for that looks like:</p> <pre><code>sum_w = 0 sum_wv = 0 for p,v in points.items(): d = distance(p,x) w = 1.0 / (d*d) sum_w += w sum_wv +=...
python|numpy|optimization
1
10,073
71,128,812
How to scale a fixed sparse matrix by the value in a 1x1 tensor in pytorch?
<p>Is it possible to scale a fixed sparse matrix by the value in a 1x1 tensor in pytorch?</p> <p>For example, in code I'm working on I'm seeing the following issue:</p> <pre><code>&gt;&gt;&gt; import torch &gt;&gt;&gt; sp_mat = torch.sparse_coo_tensor([[0,1,2],[0,1,2]],[1,1,1],(3,3)) &gt;&gt;&gt; w = torch.tensor([0.5]...
<p>While unlearnable param is simple, to make the tensor learnable it has to be of the same shape as your data (hence requirements are 2x that memory unfortunately as 0D normal/sparse tensor seems not to be broadcasted correctly).</p> <p>In this case <code>w</code> has to be recreated as sparse tensor, could be done li...
python|pytorch|sparse-matrix
0
10,074
71,197,977
How to find ratio of values in two rows that have the same identifier using python dataframes
<p>I have a dataframe with 4858 rows and 67 columns. This contains the stats from each game in the season for each MLB team. This means that for every game, there are two rows of data. One with the stats from one team and the other with the stats from the team they played. Here are the column names: ['AB', 'R', 'H', 'R...
<p>Assumptions:</p> <ul> <li>always 2 rows for each url</li> <li>in each url, among the 2 rows, you don't care which is divided by which</li> </ul> <p>A small example of your dataset:</p> <pre><code>df = pd.DataFrame({ 'url': ['1', '1', '2', '2', '3', '3'], 'non-stat1': np.arange(1., 7.), 'non-stat2': np.ar...
python|pandas|dataframe|group-by|pandas-groupby
0
10,075
71,108,178
How to get multiple same tag text in a single variable in XML Processing Python?
<pre><code>&lt;PREAMB&gt; &lt;AGENCY TYPE=&quot;S&quot;&gt;HOMELAND SECURITY &lt;/AGENCY&gt; &lt;AGENCY TYPE=&quot;O&quot;&gt;LABOR&lt;/AGENCY&gt; &lt;AGY&gt; &lt;HD SOURCE=&quot;HED&quot;&gt;AGENCY:&lt;/HD&gt; &lt;P&gt;U.S. Citizenship and Immigration Services&lt;/P&gt; ...
<p>You are making this a bit too complicated, I believe. Try it this way:</p> <pre><code>targets = ['.//AGENCY','.//AGY//P'] agencies = [] for target in targets: agencies.extend([agency.text for agency in preambl.findall(f'{target}')]) print('agencies are: ',agencies) </code></pre> <p>And see if you get your expect...
python|json|pandas|xml|xml-parsing
0
10,076
71,380,141
Why seaborn with displot irregular
<p>I used the script:</p> <pre><code>sns.displot(data=df, x='New Category', height=5, aspect=3, kde=True) </code></pre> <p>but the data not irregular like this pict I want the order to be like this::</p> <ul> <li>Less than 2 hours</li> <li>Between 1 to 2 hours</li> <li>Between 2 to 4 hours</li> <li>Between 4 to 6 hours...
<p>The easiest way to fix an order, is via <code>pd.Categorical</code>:</p> <pre class="lang-py prettyprint-override"><code>from matplotlib import pyplot as plt import seaborn as sns import pandas as pd import numpy as np # first, create some test data categories = ['Less than 2 hours', 'Between 1 to 2 hours', 'Betwee...
python|python-3.x|pandas|dataframe|seaborn
2
10,077
71,144,447
pandas: how to do piecewise calculation based on condition of one column
<p>I have a dataframe like this:</p> <pre><code>symbol Time Volume cumVolume group ... 00001 0 100 100 0 ... 00001 3 100 200 0 ... 00001 7 -200 0 0 ... 00001 12 ...
<p>First, we want to calculate this value for each <code>&quot;group&quot;</code>, so we need to <code>df.groupby(&quot;group&quot;)</code>. Then, for each group, you can get the &quot;end time&quot; using <code>df_group.max()</code>. Now, to calculate &quot;time to section end&quot; we just substract the values: <code...
python|pandas|dataframe
1
10,078
71,105,644
AttributeError: 'CRS' object has no attribute 'equals'
<p>I'm trying to make an interactive map with Geopandas using the default data-set.</p> <pre><code>countries.to_crs(epsg=3395) countries.explore(column='pop_est',cmap='magma') </code></pre> <p>Now I get the following error:</p> <pre><code>--------------------------------------------------------------------------- Attri...
<p>You have an outdated version of pyproj installed in your environment. You need at least pyproj 2.5.0. GeoPandas 0.10.x contains an installation <em>bug</em> that allows you to install older versions but this doesn't work. Update your pyproj.</p> <pre><code>conda update pyproj </code></pre> <p>or</p> <pre><code>pip ...
geopandas
1
10,079
71,239,580
generating a Markov chain simulation using a transition matrix of specific size and with a given seed, using the mchmm library
<p>I am trying to generate a Markov simulation using a specific sequence as start, using the <a href="https://github.com/maximtrp/mchmm" rel="nofollow noreferrer">mchmm</a> library coded with scipy and numpy. I am not sure if I am using it correctly, since the library also has Viterbi and Baum-Welch algorithms in the c...
<p>The states in the <code>MarkovChain</code> instance <code>a</code> are <code>'A'</code>, <code>'B'</code> and <code>'C'</code>. When the <code>simulate</code> method is given a string for <code>state</code>, it expects it to be the name of one of the states, i.e. either <code>'A'</code>, <code>'B'</code> or <code>'...
python|numpy|scipy
1
10,080
52,220,959
Batch multiplication/division with scalar in tensorflow
<p>I'm struggling to find a simple way to multiply a batch of tensors with a batch of scalars.</p> <p>I have a tensor with dimensions N, 4, 4. What I want is to divide tensor in the batch with the value at position 3, 3.</p> <p>For example, let's say I have:</p> <pre><code>A = [[[1, 1, 1, 0], [1, 1, 1, 0], ...
<p>You should just do:</p> <pre><code>B = A / A[:, 3:, 3:] </code></pre>
python-3.x|tensorflow|batch-processing
0
10,081
52,042,732
anti join pandas data frames at different levels in python
<p>I am having two pandas data frames say df1 and df2. df1 has 6 variables and df2 has 5 variables. and first variable in both the data frames are in string format and reaming are in int format.</p> <p>i want to identify the mismatched records in both data frames by using first 3 columns of both data frames and ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> with left join first, get columns names of added columns from <code>df2</code> and filter out all non <code>NaN</code>s rows by them:</p> <pre><code>df = df1.merge(df2, on...
python|pandas|anti-join
1
10,082
52,075,111
reshape is deprecated issue when I pick series from pandas Dataframe
<p>When I try to take one series from dataframe I get this issue </p> <blockquote> <p>anaconda3/lib/python3.6/site-packages/numpy/core/fromnumeric.py:52: FutureWarning: reshape is deprecated and will raise in a subsequent release. Please use .values.reshape(...) instead return getattr(obj, method)(*args, **kwds)...
<p>For avoid chained indexing use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a>:</p> <pre><code>box = [df.loc[df[categories[0]] == atype, 'price'] for atype in categories[1]] </code></pre> <p>And for remove <code>Futu...
pandas|numpy|dataframe
1
10,083
60,719,348
compare two column in two table in pandas based on the specific condition
<p>I have two data frame as shown below.</p> <p>user table: Details about the courses and modules attended by each users.</p> <pre><code>user_id courses. Num_of_course attended_modules Total_Modules 1 [A] 1 {A:[1,2,3,4,5,6]} 6 2 [A,B,C] 3 ...
<p>Use cunstom function with difference between dictionaries, lastm create new dictionarie with <code>if-else</code> for empty lists in input is also empty list:</p> <pre><code>df2 = df2.set_index('course_id') mo = df2['modules'].to_dict() #print (mo) pop = df2['Popular_modules'].to_dict() #print (pop) </code></pre> ...
pandas|pandas-groupby
1
10,084
60,509,061
How to create dataframe in pandas that contains Null values
<p>I try to create below dataframe that deliberately lacks some piece of information. That is, <code>type</code> shall be empty for one record.</p> <pre><code>df = {'id': [1, 2, 3, 4, 5], 'created_at': ['2020-02-01', '2020-02-02', '2020-02-02', '2020-02-02', '2020-02-03'], 'type': ['red', NaN, 'blue', 'blu...
<p><code>NaN</code>, <code>Null</code>, <code>Na</code> doesn't not represent an absence of value.</p> <hr> <p>Use <em>Python's</em> <a href="https://docs.python.org/3/c-api/none.html" rel="nofollow noreferrer"><strong><em><code>None</code></em></strong></a> Object to represent absence of value.</p> <pre><code>impor...
python|pandas
4
10,085
60,530,727
KeyError when trying to get to a value in 2d array (imported from csv file)
<p>I need a code in which I load data from several csv files (containing distance, altitude, angle, wavelength etc.)</p> <pre><code>import numpy as np import pandas as pd date = 20180710 # import csv files geometry = pd.read_csv('20180710_geo.csv', sep=';') TWOb = pd.read_csv('l2b.csv', sep=';') calib = pd.read_csv('...
<p>Thank you for your answer, Serge Ballesta!</p> <p>I managed to get the wanted value in the table with <code>str = obs.loc[idx[0], 'Solar distance [au]']</code> and then just converted it with <code>D = float(str.replace(',', '.'))</code> and it works.</p>
python|pandas|csv
0
10,086
60,398,009
find the duplicates and apply a condition on other column in pandas
<p>firstly I need to check the serial no column and find the duplicates,once the duplicate are found then second conditions has to applied on the rank column and which is the least rank &amp; i need to update the status with rank 1 in least rank and other duplicate column has be updated with rank 2</p> <p><img src="h...
<p>Could you try this and check ?</p> <pre><code>counts = df.groupby(['Serial No'])['Rank'].count().gt(1).reset_index() dup_sernos = counts[counts['Rank'] == True]['Serial No'].tolist() df['Status'] = df[df['Serial No'].isin(dup_sernos)].sort_values(['Serial No', 'Rank']).groupby(['Serial No']).cumcount()+1 df['Status...
python|pandas
0
10,087
60,548,567
Can I use a Tensor as a list index?
<p>I have this Custom Keras Layer that chooses between elements of a list, like a Dense layer, and I want it to return the element of the list it predicted directly. The list is a list of <code>Keras.layers.Layer</code>. I have this piece of code:</p> <pre class="lang-py prettyprint-override"><code>def call(self, inpu...
<p>There is a bigger problem. </p> <p>This layer will not work, because you cannot get derivatives of <code>argmax</code>, the <code>kernel</code> will be impossible to train. And you will get an error message like "An operation has None for gradient"</p> <p>As a workaround, I'd suggest you to:</p> <ul> <li>1: calcu...
python|tensorflow|keras|deep-learning|keras-layer
1
10,088
60,643,795
For loop doesn't work for web scraping Google search in python
<p>I'm working on web-scraping Google search with a list of keywords. The nested For loop for scraping a single page works well. However, the other for loop searching keywords in the list does not work as I intended to which <strong>scrapes</strong> the data for each searching result. The results didn't get the search ...
<p>You need to create ceo as a list and append to it inside the for loop so you don't keep overwriting it</p>
python|pandas|loops|for-loop|web-scraping
0
10,089
60,574,862
Calculating pairwise Euclidean distance between all the rows of a dataframe
<p>How can I calculate the Euclidean distance between all the rows of a dataframe? I am trying this code, but it is not working:</p> <pre><code>zero_data = data distance = lambda column1, column2: pd.np.linalg.norm(column1 - column2) result = zero_data.apply(lambda col1: zero_data.apply(lambda col2: distance(col1, col...
<p>To compute the Eucledian distance between two rows i and j of a dataframe df:</p> <pre><code>np.linalg.norm(df.loc[i] - df.loc[j]) </code></pre> <p>To compute it between consecutive rows, i.e. 0 and 1, 1 and 2, 2 and 3, ...</p> <pre><code>np.linalg.norm(df.diff(axis=0).drop(0), axis=1) </code></pre> <p>If you wa...
python|pandas|numpy|dataframe|euclidean-distance
8
10,090
72,557,824
Alter dataframe based on values in other rows
<p>I'm trying to alter my dataframe to create a Sankey diagram.</p> <p>I've 3 million rows like this:</p> <pre><code>client_id | | start_date | end_date | position 1234 16-07-2019 27-03-2021 3 1234 18-07-2021 09-10-2021 1 1234 28-03-2021 17-07-2021 2...
<p>Because the source and target are calculated by each client's date order. So it is possible to order the date and find its next position.</p> <pre><code>columns = [&quot;client_id&quot; ,&quot;start_date&quot;,&quot;end_date&quot;,&quot;position&quot;] data = [ [&quot;1234&quot;,&quot;16-07-2019&quot;,&quot;27-0...
python|python-3.x|pandas|dataframe|sankey-diagram
1
10,091
72,550,951
Use pandas.groupby() and cumsum() with row wise condition check and replacement
<p>We have a dataframe,df with four variables A, B,C, and D.</p> <p>Variable A has two levels 1,2, and 3 (in this example only).</p> <p>Variable B, C and D are continuous variables.</p> <p>Formula used for filling column C based on A and B is</p> <pre><code>df['C'] = 150 - df['B'].groupby(df['A']).cumsum() </code></pre...
<pre><code>import pandas as pd qqq = [] def func_data(x): aaa = 150 for i in x: aaa -=i if aaa &gt; 150: aaa =150 if aaa &lt; 0: aaa = 0 qqq.append(aaa) df['F'] = df.groupby(['A'])['B'].apply(func_data) df['F'] = qqq print(df) </code></pre> <p>Output</p...
python|pandas|dataframe|group-by|cumsum
1
10,092
72,533,815
I trained a model in torch and then convert it to caffe and after that to tf. How to convert it now to onnx?
<p>I trained a Resnet model in torch. Then, I converted it to caffe and to tflite. now I want to convert it to onnx. How can I do it? I try that command:</p> <pre><code>python3 -m tf2onnx.convert --tflite resnet.lite --output resnet.lite.onnx --opset 13 --verbose </code></pre> <p>because the current format of the mode...
<p>you can try something like this checkout <a href="https://docs.microsoft.com/en-us/windows/ai/windows-ml/tutorials/tensorflow-convert-model" rel="nofollow noreferrer">link</a> may be you need to freeze the model layers before starting conversion.</p> <pre><code>pip install onnxruntime pip install git+https://github....
python|tensorflow|tensorflow-lite|onnx|tf2onnx
0
10,093
32,152,890
ipython date attribute not found
<p>Im using ipython notebook to run some analytics using pandas. however, im running into problems with the following function and the date attributes</p> <pre><code>def get_date(time_unit): t = tickets['purchased date'].map(lambda x: x.time_unit) return t # calling it like this produces this error get_date('...
<p>When you do -</p> <pre><code>t = tickets['purchased date'].map(lambda x: x.time_unit) </code></pre> <p>This would not replace whatever is inside the <code>time_unit</code> string and take <code>x.week</code> , instead it would try to take the <code>time_unit</code> attribute of x, Which is causing the error you are ...
python|pandas|ipython|ipython-notebook
2
10,094
32,386,791
Returing a single boolean value if value is duplicated in pandas series?
<p>Given the following pandas DataFrame:</p> <pre><code>mydf = pd.DataFrame([{'Campaign': 'Campaign X', 'Date': '24-09-2014', 'Spend': 1.34, 'Clicks': 241}, {'Campaign': 'Campaign Y', 'Date': '24-08-2014', 'Spend': 2.89, 'Clicks': 12}, {'Campaign': 'Campaign X', 'Date': '24-08-2014', 'Spend': 1.20, 'Clicks': 1}, {'Cam...
<p>It looks like your first proposed method is the fastest on a small dataframe.</p> <pre><code>%timeit mydf.Campaign.duplicated().any() The slowest run took 4.08 times longer than the fastest. This could mean that an intermediate result is being cached 10000 loops, best of 3: 39.9 µs per loop %timeit True in mydf['...
python|python-2.7|pandas
1
10,095
40,561,836
Copy certain rows from pandas dataframe to a new one (Time condition)
<p>I have a dataframe which looks like this:</p> <pre><code> pressure mean pressure std 2016-03-01 00:00:00 615.686441 0.138287 2016-03-01 01:00:00 615.555000 0.067460 2016-03-01 02:00:00 615.220000 0.262840 2016-03-01 03:00:00 614.993333 0.13...
<p>I couldn't load your data using <code>pd.read_clipboard()</code>, so I'm going to recreate some data:</p> <pre><code>df = pd.DataFrame(index=pd.date_range('2016-03-01', freq='H', periods=72), data=np.random.random(size=(72,2)), columns=['pressure', 'mean']) </code></pre> <p>Now ...
python|pandas|dataframe
3
10,096
40,562,728
Putting lower bound and upper bounds on numpy.random.exponential
<p>I want to extract samples from the exponential distribution with lambda =2 , however these must be bounded between 1 and 10.I know the usual syntax for creating samples in the exponential distribution however I do not know how to bound it .</p> <p>Also I cannot use scipy.</p>
<pre><code>import numpy as np t = 0 t &lt; 1 or t &gt; 10: t = np.random.exponential(2) </code></pre> <p>That should do it</p>
python|numpy|exponential
0
10,097
40,646,767
Which file to be used for eval step in TEXTSUM?
<p>Am working on the texsum model of tensorflow which is text summarization. I was following commands specified in readme at <a href="https://github.com/tensorflow/models/tree/master/textsum" rel="nofollow noreferrer">github/textsum</a>. It said that file named validation, present in data folder, is to be used in eval ...
<p>So you don't have to run eval unless you are in fact testing your model after you have trained to determine how the training does against another set of data it has never seen before. I have also been sing it to determine if I am starting to overfit the data.</p> <p>So you will usually take 20-30% of your overall d...
tensorflow|eval|textsum
1
10,098
61,878,521
slicing by indices on multiple axes numpy
<pre><code>A = np.arange(120).reshape(2, 3, 4, 5) is_ = [1, 2] js = [0, 1, 2, 3] A[:, :, is_, :][:, :, :, js].shape == (2, 3, 2, 4) </code></pre> <p>Is there a better way of doing the double slice here?</p> <p>I tried <code>A[:, :, is_, js]</code> but that does it "zip" style.</p> <p>Efficiency would be nice too, I...
<p>You can do it in a single indexing step. You just need to add a new axis to either of the indexing arrays so they are broadcastable:</p> <pre><code>is_ = np.array([1, 2]) js = np.array([0, 1, 2, 3]) A[:, :, is_[:,None], js] </code></pre>
python|numpy
2
10,099
61,998,420
NaN in else statement
<p>Please I can't figure out why is function returning me <code>NaN</code> in <code>else</code> statement.</p> <p>The goal is to get mean of the all goals scored in whole season by team without the last match. If there is only one match in the season, I want to return goals scored in that match. </p> <p>DF:</p> <pre...
<p>Why you complicate your life? If there's only 1 match, the mean will be simply its score.</p> <p>No need for <code>if</code>-<code>else</code>.</p> <p>So your command</p> <pre><code>df["HOME_GOALS_LAST_SEASON"] = df.groupby(["HOME", "SEASON"]).apply(last_season) </code></pre> <p>replace with</p> <pre><code>df["...
python|pandas|if-statement
1