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
359,800
58,806,540
Is there an efficient way (not a for loop) to initialize an array in numpy where each cells is a multiple of the previous cell?
<p>I would like to create a numpy array (in python), where the axes values are determined by the value in the previous cell and an additional function.</p> <p>For example: In the following example the values on the y axis (rows) is determined by: </p> <pre><code>Array[i:0] = Array[i-1:0] + 3 + some_other_func() </co...
<p>I think what you are looking for are <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.accumulate.html" rel="nofollow noreferrer">accumulator</a> functions, specifically <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html" rel="nofollow noreferrer">cumsum</a> since...
python|arrays|axis|numpy-ndarray
0
359,801
58,636,938
pandas Concatenate strings based on column values
<p>I have a dataframe</p> <pre><code>df = pd.DataFrame({ 'Names': ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'], 'Value': ['A1','A2','A3','B1','B2','C1','C2','C3']}) # Names Value #0 A A1 #1 A A2 #2 A A3 #3 B B1 #4 B B2 #5 C C1 #6 C C2 #7 C C3 </code...
<p>Try this out:</p> <pre><code>df.groupby('Names')['Value'].apply(list).reset_index(name='Values') </code></pre>
python|python-3.x|pandas|numpy
1
359,802
58,962,634
Comparing current row and previous row in different columns in Pandas
<p>I have a dataframe looks like follows: <a href="https://i.stack.imgur.com/kHLXh.png" rel="nofollow noreferrer">enter image description here</a></p> <p>for every date changed on original date column will generate a new row recording the previous original order date and current order date. I wanna check for the same...
<p>You can try masking with df.shift() (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shift.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shift.html</a>)</p> <p>For instance if you wanted the same column to compare to ...
python|pandas
1
359,803
58,711,722
Remove Duplicated Values From List In Pandas Dataframe
<p>I have a column in my dataframe that is a list with values from rows. Is there any way to get the same columns with unique values in these lists sorted also.</p> <p>This is my dataframe column.</p> <pre><code>ListProds ['YIZ12FF-A', 'YIZ12FF-A', 'YIIE2FF-A', 'YIR72FF-A', 'YIR72FF-A', 'YIR72FF-A'] ['HYY32ZY-A', 'HY...
<p>Convert values to sets and then sort them:</p> <pre><code>df['ListProds'] = df['ListProds'].apply(lambda x: sorted(set(x))) </code></pre> <p>Or like mentioned @Chris A in comments use <code>np.unique</code>:</p> <pre><code>df['ListProds'] = df['ListProds'].apply(lambda x: np.sort(np.unique(x))) #if lists are sort...
python|pandas
3
359,804
58,665,534
I have a pytorch image classifier training, and I want to pause training and save the weights at time of program pause. Can I do this?
<p>I'm in the middle of training a classifier that's been training for a few days now, but my problem is that I didn't code in to save .pt checkpoints throughout training, and so I'll only end up with a weights file when the program is done with all of its epochs. Is there a way to pause training (PAUSE BREAK) and sav...
<p>Unfortunately, PyTorch does not have a native API for this at the moment. For the current job, you could use an IDE like <a href="http://www.pydev.org" rel="nofollow noreferrer">PyDev</a> or <a href="https://www.jetbrains.com/pycharm/" rel="nofollow noreferrer">Pycharm</a> to attach a debugger to the running process...
python|pytorch
2
359,805
58,983,045
How to reproduce a Keras model from the weights/biases?
<p>I want to use the weights and biases from a Keras ML model to make a mathematical prediction function in another program that does not have Keras installed (and cannot).</p> <p>I have a simple, MLP model that I'm using to fit data. I'm running in Python with Keras and a TensorFlow backend; for now, I'm using an inp...
<p>I think it's good to familiarise yourself with linear algebra when working with machine learning. When we have an equation of the form <code>sum(matrix elem times another matrix elem)</code> it's often a simple matrix multiplication of the form <code>matrix1 * matrix2.T</code>. This simplifies your code quite a bit:...
python|tensorflow|machine-learning|keras
3
359,806
58,784,373
Transfer learning for facial identification using classifiers
<p>I wish to know whether I can use an Inception or ResNet model to identify faces. I want to know whether transfer learning and training is even considerable for my task. </p> <p>I just want to be able to identify faces but I am also curious whether I can retrain/optimize a pre-trained model for my task.</p> <p>Or h...
<p>Transfer learning for facial detection would be a great way to go ahead. Also, yes transfer learning with facenet is a great idea. </p> <p>Also, for transfer learning to work it is not necessary that the model had to be initially pre-trained with only faces like using facenet. A model pre-trained with imagenet woul...
python|tensorflow|keras|transfer-learning|facial-identification
1
359,807
58,953,344
replace the text in one column with a dictionary in other column
<p>I have texts in one column and respective dictionary in another column. I have tokenized the text and want to replace those tokens which found a match for the key in respective dictionary. the text and and the dictionary are specific to each record of a pandas dataframe.</p> <pre class="lang-py prettyprint-override...
<p>You can use <code>dict.get</code> method after zipping the 2 cols and splitting the sentence:</p> <pre><code>df['modified_text']=([' '.join([b.get(i,i) for i in a.split()]) for a,b in zip(df['text'],df['dictionary'])]) print(df) </code></pre> <hr> <p>Output:</p> <pre><code>id ...
python|pandas|dataframe|dictionary
1
359,808
58,778,867
How can i convert mnist data to RGB format?
<p>I am trying to convert MNIST dataset to RGB format, the actual shape of each image is (28, 28), but i need (28, 28, 3). </p> <pre><code>import numpy as np import tensorflow as tf mnist = tf.keras.datasets.mnist (x_train, _), (x_test, _) = mnist.load_data() X = np.concatenate([x_train, x_test]) X = X / 127.5 - 1 ...
<p>You should store the reshaped 3D [28x28x1] images in an array:</p> <pre><code>X = X.reshape((70000, 28, 28, 1)) </code></pre> <p>When converting, set an other array to the return value of the <code>tf.image.grayscale_to_rgb()</code> function :</p> <pre><code>X3 = tf.image.grayscale_to_rgb( X, name=None ) </code>...
python|numpy|tensorflow|keras|tensorflow-datasets
4
359,809
58,802,659
Is there a way to sort a tensor with respect to a sub array?
<p>I want to sort a tensor with respect to a sub-array. For example, I have a following tensor:</p> <pre class="lang-py prettyprint-override"><code>A = tf.constant([[4, 2, 1, 7, 5], [10, 20, 30, 40, 50]]) </code></pre> <p>And I want to sort this tensor A respect to the A[0, :].</p> <p>The result I ...
<p>Using <code>tf.gather</code> with <code>tf.argsort</code>:</p> <pre><code>import tensorflow as tf: a = tf.constant([[4, 2, 1, 7, 5], [10, 20, 30, 40, 50]]) b = tf.gather(a, tf.argsort(a[0]), axis=1) b </code></pre> <p>Output:</p> <pre><code>&lt;tf.Tensor: id=152, shape=(2, 5), dtype=int32, num...
python|tensorflow
2
359,810
58,610,249
Problem Using Pivot_Table in Python: is there any way to keep the original order of the data and not having multiindex?
<p>I am trying to recreate my data frame. Below is the original dataframe:</p> <pre><code>df = pd.DataFrame([['January','Monday',0,1,20],['January','Monday',1,2,15],['January','Wednesday',0,1,35],['March','Monday',0,1,23],['March','Monday',1,2,50],['March','Monday',2,3,60] ,['April','Wednesday',0,1,75]],columns = ['Mo...
<p>You can try using groupby with unstack:</p> <pre><code>df.groupby(['Month','Day','Data2'])['Data2'].first().unstack().reset_index() </code></pre> <p>Output:</p> <pre><code>Data2 Month Day 1 2 3 0 April Wednesday 1.0 NaN NaN 1 January Monday 1.0 2.0 NaN 2 January Wed...
python|pandas|pivot-table
0
359,811
58,609,302
Retrieving data from a huge table
<p>Let me decribe the task: Each column represents the ship (name of the column is the name of a ship and rows are containers). The name of the ship is in the form nn: xxxxxx (ttttttt). The containers are represented in the form aa-bb-cccccccc/yyyy/xx@ddddddddd.ee, where bb is the name of the final destination of a con...
<p>Let's us regular expressions with <code>extract</code> then <code>value_counts</code> and you can filter your result to get your proper destinations.</p> <pre><code>from io import StringIO intxt = StringIO("""1: Brandenburg (Post-Panamax) ES-NL-10633096/1938/X1@hkzydbezon.dk/6749 BE-BR-61613986/3551/B1@oqk.bf/3992...
python|pandas|split
2
359,812
58,840,816
How to compare PANDAS Columns in a Dataframes to find all entries appearing in different columns?
<p>Full disclosure. I'm fairly new to Python and discovered PANDAS today.</p> <p>I created a Dataframe from two csv files, one which is the results of a robot scanning barcode IDs and one which is a list of instructions for the robot to execute. </p> <pre><code>import pandas as pd #import csv file and read the column...
<p>To check True/False if all the items required are in the column;</p> <p><code>all([item in df["IDs Scanned"] for item in df["IDs required"].unique()])</code></p> <p>To get a list of the unique missing items:</p> <p><code>sorted(set(df["IDs required"]) - set(df["IDs Scanned"]))</code></p> <p>Or using pandas synta...
python-3.x|pandas|csv|dataframe
0
359,813
59,009,393
How to iterate through data set in pandas based on days?
<p>I have the following code</p> <pre class="lang-py prettyprint-override"><code> data for label, content in data.items(): print('label:', label) print('content:', content, sep='\n')` </code></pre> <p>That is all. IGNORE IT</p>
<p>You can subset by index</p> <pre><code>data2 = data.loc[(data.index.month == 11) &amp; (data.index.day == 10)] </code></pre> <p>You index is <code>datetime</code> type, and you want it converted to string. First we need to reset_index</p> <pre><code>data2 = data2.reset_index() data2["Date"] = data2["Date"].astype...
python|pandas
0
359,814
58,738,708
How to predict the label after training the dataset in NLP
<p>I am trying to do sentiment analysis on comments; the data set contains two main colums: the first one is "review" which has the reviews of the users, and the second colum is whether it is positive or negative; I got a template from a source to prepocessing the data, the training and testing is okay. However, I want...
<p>As G.Anderson has already mentioned your classfier is trained with numerical data, as you used:</p> <pre><code>X=cv.fit_transform(corpus).toarray() </code></pre> <p>and CountVectorizer is made for this.</p> <p>To use it, you also have to use the trained CountVectorizer, you have to implement:</p> <pre><code># Pr...
python|numpy|machine-learning|scikit-learn|nlp
1
359,815
58,993,267
Issue installing @tensorflow-models/knn-classifier with npm
<p>I installed @tensorflow-models/knn-classifier with npm, but when i run it i get an error "Cannot find module '@tensorflow-models/knn-classifier'". I can see the module under node modules but still i get this error. Other models like @tensorflow-models/mobilenet, @tensorflow-models/universal-sentence-encoder are reso...
<p>For now the package is missing <code>index.js</code>. Here is the fix</p> <pre><code>const tf = require('@tensorflow/tfjs'); const knnClassifier = require('./node_modules/@tensorflow-models/knn-classifier/dist/knn-classifier'); const classifier = knnClassifier.create(); console.log('classifier', classifier) </code...
javascript|node.js|tensorflow.js
3
359,816
58,922,881
Python how to create a document matrix with (i,j) entries being term index
<p>I run into the following issues with text data matrix manipulation. </p> <p>I have the original text document as well, stored in a list. Below is an example for the first element of the list of text data.</p> <pre><code>text_data[1] u"\n The Bechtel Group Inc. offered in 1985 to sell oil to Israel at a discount o...
<p>I ran into a similar challenge a few months ago. I'm pretty sure there is a way to do it using Python NLTK. Googling "corpus to term count vectors" should get you a good start.</p> <p>I ended up just implementing my own though, as you suggest in your question.</p> <pre class="lang-py prettyprint-override"><code>de...
python|numpy|text|data-manipulation|lda
0
359,817
58,823,655
How to calculate the average values of a year from quarterly data?
<p>I have this dataframe and I want to calculate the average number of each year</p> <pre><code>index cath_date 1 2017Q4 111 2 2017Q3 107 3 2018Q2 105 4 2017Q2 105 5 2017Q1 101 7 2018Q3 98 8 2016Q3 97 9 2018Q1 94 10 2018Q4 91 11 2016Q1 91 12 2015Q4 85 13 2016Q4 83 14 2016Q2 81 15 2...
<p>Your math seems a little funky (e.g., <code>2015</code> has a minimum value of 28, so how could the mean be 28?), but you can just <code>.groupby</code> the first 4 characters and calculate the mean:</p> <pre><code>In [6]: df.groupby(df['index'].str.slice(0, 4)).mean() Out[6]: cath_date index 2015 6...
python|pandas
4
359,818
58,945,344
How do I add a new column to an existing dataframe and fill it with partial data from another column?
<p>I have a dataframe <em>jobs</em> <a href="https://i.stack.imgur.com/0L6BM.png" rel="nofollow noreferrer">screenshot of dataframe</a></p> <p>I need to add a new column ‘year’ to jobs data frame. This column should contain the corresponding year for each post_date (which is already a column). For example: for post_da...
<p>Use <code>dt.year</code>:</p> <pre><code>jobs['year'] = pd.to_datetime(jobs['post_date'], errors='coerce').dt.year </code></pre>
python|pandas|dataframe
2
359,819
58,944,642
ModuleNotFoundError: No Module name 'pandasql'
<p>I am trying to import pandasql. I am running the following code in a jupyter notebook running python: </p> <pre><code>!pip install pandasql from pandasql import sqldf import pandas as pd </code></pre> <p>This logs an error saying <code>ModuleNotFoundError: No Module name 'pandasql'</code></p> <p>I understand this...
<p>I know I am quite late in responding this but try this, but as you are working on Jupyter notebook, you can try <code>pip install pandasql</code> in Anaconda prompt</p>
python|pandas|pandasql
3
359,820
58,888,559
IndexError:list index out of range in python code
<p>when I'm running this code I have an error and I can't understand whats the problem. this code work like when the (getx )create the array of systems, Cost, weight and expression functions start calculation according to (getx) array. array W is Weight , C is Cost and R is Reliability under the error. </p> <p>error ...
<p>Quickly reproduced the example given by you and ran it. The problem arises in the very first iteration in this line:</p> <pre><code>expW = expW + w[possition][int(char)] </code></pre> <p>where you get an <code>IndexError</code>. The problem is that you initialize <code>W</code> as empty list and pass to the functi...
python|numpy|data-science
0
359,821
58,907,260
How can I save scan data(topic) in npy file?
<p>I'm newbie in ros</p> <p>I'm trying to save LiDAR Laserscan data to npy file to check my test code without launching ros.</p> <p>The ideal form i wanna save is numpy array file which contains every information in each Laserscan topic data such as header(stamp, seq), angle data(angle_min, --), ranges.</p> <p>I hop...
<p>I solved my qustion! here is my code :)</p> <p>By dong this, I could save all of topic as numpy array</p> <pre><code>self.scan_data = np.array([]) # define it at __init__ '''at the scan callbalck function''' buffer = msg # Laserscan msg from subscriber self.scan_data = np.array(buffer) self.save_scan = np.append(...
python|linux|numpy|save|ros
2
359,822
58,927,662
TensorFlow Serving Error - Could not find meta graph def matching supplied tags: { serve }
<p>I am trying to restore a TensorFlow's Saver object (.ckpt.*) and convert it into SavedModel object(.pb) so that I can deploy it with TensorFlow Serving.</p> <p>This is how I convert:</p> <pre class="lang-py prettyprint-override"><code> with tf.Session() as sess: # Restore the graph from (.meta .data .i...
<p>you need to add prediction signature to your builder-</p> <pre><code>prediction_signature = tf.saved_model.signature_def_utils.predict_signature_def({&quot;input&quot;: inputs}, {&quot;output&quot;:output}) builder = saved_model_builder.SavedModelBuilder('exported_moddel/') builder.add_meta_graph_and_variables(ses...
tensorflow|tensorflow-serving
3
359,823
58,675,421
Pandas groupby convert series to dataframe with maximum count of values
<p>Input Data looks like following:</p> <pre><code>id season city date team1 team2 toss_winner toss_decision result dl_applied winner win_by_runs win_by_wickets player_of_match venue ...
<p>Use:</p> <pre><code>df.groupby('season').agg(mode=('toss_winner',lambda x: x.mode())) </code></pre> <p>or:</p> <pre><code>df_count=df.groupby(['season','toss_winner'])['toss_winner'].count().rename('count').reset_index() df_count_mode=df_count[df_count['count'].eq(df_count['count'].max())] print(df_count_mode) ...
python|pandas|dataframe
1
359,824
58,729,329
Resample only within the same day
<p>I have a dataframe containing an asset price (OHLC asset data) such that its index is a datetime. The data shoud be sample in minutes but my dataset have some missing minutes. </p> <p><a href="https://i.stack.imgur.com/9nUgn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9nUgn.png" alt="enter im...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>DataFrame.groupby</code></a> by days and chain <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.resample.html" re...
python|pandas
2
359,825
58,966,203
How is scipy.stats.multivariate_normal.pdf different from the same function written using numpy?
<p>I need to use the multivariate normal distribution in a script. I have noticed that my version of it gives a different answer from scipy's method. I can't really figure out why...</p> <p>Here is my function:</p> <pre><code>def gauss(x, mu, sigma): assert np.linalg.det(sigma)!=0, "determinant of sigma is 0" ...
<p>The particular input you've used as an example could be slightly misleading because the values are so low that numerical issues would easily suffice to cause the discrepancy you are seeing. However, even when using an example with larger densities, you will still have issues:</p> <pre class="lang-py prettyprint-ove...
python|python-3.x|numpy|scipy|probability
3
359,826
59,037,789
Vectorized way to generate 2D array from 2 1D arrays
<p>I have a pair of equal length numpy arrays. <code>dwells</code> contains float numbers representing dwell times, and <code>ids</code> represents a state. In my example there are only 3 unique states labeled <code>0</code>, <code>1</code>, <code>2</code>.</p> <pre><code>dwells = np.array([4.3,0.2,3,1.5]) ids = np.ar...
<p>Assuming we have a smallest possible timestep of <code>delta</code>:</p> <pre><code>import numpy as np dwells = np.array([4.3,0.2,3,1.5]) ids = np.array([2, 0, 1, 2]) def dwell_map(dwells, ids, delta=0.1): import numpy as np import sys idelta = 1 / delta # ensure that idelta is an integer number...
python|arrays|numpy|vectorization
2
359,827
58,655,386
How to remove error values in large df with 1000 columns
<p>I have a large dataset with more than 1000 columns, the dataset is messy with mixed dtypes. There are 2 int64 columns, 119 float columns and 1266 object columns.</p> <p>I would like to begin data cleaning but realised there are several issues. As there are too many columns, visual inspection of the data to locate e...
<p>This will do the trick:</p> <pre><code>for col in df.columns[df.dtypes=='object']: df.loc[df[col].str.startswith('$$ER',na=False),col]='' </code></pre> <p>You can also use <code>contains()</code> but you will have to specify <code>regex=False</code></p> <pre><code>for col in df.columns[df.dtypes=='object']: ...
python|pandas|dataframe|data-cleaning
4
359,828
58,697,491
Combine rows into one ohlc row if time is the same?
<p>I have been experimenting with <code>resampling</code>(60S) data from tick <code>database</code> to another database called <code>min</code>.</p> <p>I took a <code>to_excel</code> of both databases by loading into <code>pandas</code>.</p> <p>In the <code>min</code> dataframe:</p> <pre><code> timestamp ...
<p>you can use <code>.agg</code> and pass a dictionary of columns with your intended aggregation metric after an initial <code>groupby</code></p> <pre><code>print(df) timestamp open high low close 0 2019-11-04 14:23:00 30468 30473.9 30440.15 30445 1 2019-11-04 14:23:00 30468 30473.9 30440.1...
python|pandas|sqlite
2
359,829
58,882,378
PySpark - use datetime object with a PandasUDFType.GROUPED_MAP
<p>I have created a PandasUDF to return the most recent 'count' for each ID. The 'date' column in the spark DF is a string type(YYYY-mm-dd). In the function below I use pd.to_datetime to convert the string to a datetype to get the max(date) for each ID. The function(below) works just fine when applied to a pandas dataf...
<p>According to this <a href="https://stackoverflow.com/questions/56053572/cant-apply-a-pandas-udf-in-pyspark">answer</a> and checking <a href="https://docs.databricks.com/spark/latest/spark-sql/udf-python-pandas.html#supported-sql-types" rel="nofollow noreferrer">supported types</a>, current pandas_udf does not suppor...
python|pandas|pyspark
1
359,830
58,995,873
Error: 'NoneType' object is not iterable when read_sql
<p>have looked all over the internet for a solution.</p> <p>This is the code:</p> <pre><code>import pyodbc import pandas as pd conn = pyodbc.connect("Driver={SQL Server};" "Server=Server;" "Trusted_Connection=yes;") cursor = conn.cursor() query = """ SET nocount ...
<p>Could you remove the <code>SET nocount ON; USE database;</code>?</p> <p>I think that way of getting a result from a connection is not right. Either you use the cursor and perform tasks without getting anything or you get stuff using just a select from a connection the way you did, but without those lines.</...
python|sql|pandas
2
359,831
58,866,966
Custom Reorder of Values in Python Dataframe
<pre><code>import pandas as pd import numpy as np table = pd.DataFrame() table["SORT_WW"]= ["03", "50", "01", "52", "03", "48", "02", "47"] table ["Name"] = ["a", "b", "c", "d", "e", "f", "g", "h"] </code></pre> <p>And my current table is like:</p> <p><a href="https://i.stack.imgur.com/rZccw.png" rel="nofollow nor...
<p>From my understanding, you want to reorder your rows based on how the values in SORT_WW map to positions in your ordered categorical array.</p> <p>Here's an option to get the sorted indices by converting your categorical array into an <code>Index</code>:</p> <pre><code>df.iloc[pd.Index(SORT_WW_reorder).get_indexer...
python|numpy|dataframe
0
359,832
59,003,872
Running for-loop and skipping stocks with 'KeyError' : Date
<p>I have written the following code which gets list of symbols of sp500 from wikipedia and then scrapes the data from yahoo daily reader. </p> <pre><code>html = urlopen('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies') soup = BeautifulSoup(html,'lxml') sp500_raw = soup.find('table', {'class': 'wikitable so...
<p>Error shows problem in line with <code>web.get_data_yahoo</code> so you would have to put all this part in <code>try/except</code></p> <pre><code> for ticker in row: try: stock_data.append(web.get_data_yahoo(ticker, start, end)) for df in stock_data: df.to_csv(ticker, ...
python|python-3.x|for-loop|pandas-datareader
1
359,833
58,829,053
numpy.maximum.reduce not returning maximum value
<p>Hi I am trying to find the maximum of binary masks for which I have used <code>numpy.maximum.reduce</code>. I have a set of binary masks and in order to find the maximum from all the masks(which according to me points to the most edges in the images) and avoid overlapping. Therefore I used <code>numpy.maximum.reduce...
<p>Here is a simple example of getting the maximum value pixel-by-pixel of 4 binary mask images using Python/OpenCV/Numpy</p> <p>4 Masks:</p> <p><a href="https://i.stack.imgur.com/Vb0Vi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vb0Vi.png" alt="enter image description here"></a></p> <p><a hre...
python|numpy|opencv|image-processing|computer-vision
0
359,834
70,168,182
Mapping a column with no unique identifier in pandas
<p>I have two dataframes and I want to map a column from <code>df2</code> to <code>df1</code>, but I don't have one unique column to use as an index so I do the following:</p> <pre><code>df1['completion_time']=df1[['participant','Movement_type']].merge(df2,how='left').completion_time </code></pre> <p>but the end result...
<p>Just use <code>df3 = pd.merge(df1, df2)</code>. This results in the correct df3 for me:</p> <pre><code> participant vis total_time Movement_type question completion_time 0 1194 8 24.747 A 40 11.0 1 1194 4 22.151 B 52 45.0 2 1190 8 28.853 A 40 20.0 3 1190 4 137.254 B ...
python|pandas
0
359,835
70,301,301
Error when Identifying Effects of Causal Model
<p>I am trying to use the CausalModel and Econml libraries in order to determine the effect of a variable on different scenarios displayed in the dataset below :</p> <p><a href="https://i.stack.imgur.com/8P1Yl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8P1Yl.png" alt="enter image description her...
<p>I was also encountering this problem but when I used a linear regression model instead of the Random Forest Regressor metalearner I had no issues.</p> <p>This requires replacing</p> <pre><code>identified_estimand_experiment = model.identify_effect(proceed_when_unidentifiable=True) from sklearn.ensemble import Rando...
python|pandas|causality|causalml
1
359,836
70,338,314
How to splice a dataframe into smaller tables and save each table to an excel sheet
<p>Here is a table</p> <pre><code>df = {'index':['Larry','Moe','Curly'], 'age':[54,58,65], 'eye':['blue','brown','brown'], 'fortune':[1,1.5,1.2], 'food':['pizza','pasta','burgers'], 'job':['actor','actor','actor'], 'kids':[2,3,4]} df = pd.DataFrame(df) df = df.set_index('index') </code></pre> <p>I would li...
<p>If you are looking to save each two columns into a separate sheet, try:</p> <pre><code>col = df.columns # ExcelWriter not Excelwriter with pd.ExcelWriter('filename' + '.xlsx') as xlswriter: for i in range(0,len(col), 2): # you can use `iloc` to slice by column number df.iloc[:,i:i+2].to_excel(x...
python|pandas|dataframe|loops
1
359,837
70,068,382
Matplotlib not shown x tick labels
<p>I have a dataframe as follows (reproducible data):</p> <pre><code>import pandas as pd import numpy as np from datetime import datetime np.random.seed(365) rows = 2 start_date=datetime.strptime('2020-01-01 00:00:00', '%Y-%m-%d %H:%M:%S') data = np.random.uniform(2.1, 6.5, size=(rows, cols)) index = pd.bdate_range(st...
<p>Use matplotlib annotation to attach labels to the chart:</p> <pre><code>data=&quot;&quot;&quot;Date,Ta 2020-01-01 00:00:00,6.242405 2020-01-01 01:00:00,4.923052 2020-01-01 02:00:00,5.112286 2020-01-01 03:00:00,4.689673 2020-01-01 04:00:00,4.493104 2020-01-01 05:00:00,3.719512 2020-01-01 06:00:00,5.473153 2020-01-01 ...
python|pandas|date|datetime
3
359,838
70,219,851
Create Dataframe from deeply nested json
<p>I am trying to read below json schema to dataframe, i can convert it to my preferred type by iterating over all nodes but it can take a while because original json files is much longer then this example. (in tens of thousands)</p> <pre><code> &quot;data&quot;: [ { &quot;node&quot;: { ...
<p>Construct the individual DataFrames of authors and genres and join to the original <code>df</code>:</p> <pre><code>authors = pd.json_normalize(data[&quot;data&quot;], record_path=[&quot;node&quot;,[&quot;authors&quot;]])[[&quot;node.first_name&quot;, &quot;node.last_name&quot;]] genres = pd.Series([&quot;, &quot;.jo...
python|json|pandas|parsing
1
359,839
70,166,460
Sum time intervals of sparse time-series data with overlapping events
<p>I've got some time-sorted data which tracks the beginning and end time of different events. For illustration purposes imagine I'm tracking when a set of light bulbs are turning on and off. My data is structured like so:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Bulb ID</th> <th>Eve...
<p>Your solution might work but has a lot of ifs and buts. Try <code>pd.pivot_table</code></p> <pre><code>pd.pivot_table(data=df,values=&quot;Time (s)&quot;, columns=&quot;Event (on/off)&quot;, index=&quot;Bulb ID&quot;,aggfunc=np.sum) </code></pre> <p>This can then we used to further calculate stuff.</p>
python|pandas|dataframe|time-series
0
359,840
70,063,166
Pandas Dataframe Comparison - specify mismatched columns
<p>I have two dataframes as shown below, <code>df1</code> and <code>df2</code>:</p> <pre><code>df1 = emp_name emp_city counts emp_id 2 two city2 3 4 fourxxx city4 1 5 five city5 1 df2 = emp_nam...
<p>You can use <code>df2.columns + ','</code> to add commas and then <code>str[:-1]</code> to remove the last one:</p> <pre><code>df3['mismatch_col'] = df2.ne(df1, axis=1).dot(df2.columns + ',').str[:-1] </code></pre> <p>Result:</p> <pre><code> emp_name emp_city counts mismatch_col emp_id ...
python|pandas|dataframe
2
359,841
70,152,654
Continuing tally on python dataframe
<p>I have a dataframe with three columns. These columns contain a name and a running tally of how many times the name has appeared, and the third column is a concatenation of these two columns.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>name</th> <th>count</th> <th>concat</th> </tr> </...
<p>One possible solution I found would be to use Lag functionality of Pandas. If you already have a DataFrame with initial count and you add more data to it you can use the following:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd tmp = df.copy() # copy for reference and mask for 'count' while...
python|pandas
0
359,842
70,112,107
Apply multiple conditions and apply function to columns
<p>I would like to be able to add a new column to a data frame and then use conditions about the values in each row to categorise it into zero, one or multiple categories which would be record in the final column.</p> <p>e.g., with this DataFrame, df</p> <pre><code> Name Height Qualification Type 0 Jai 5...
<p>Create a custom function and apply it to your dataframe while creating your <code>Type</code> column :</p> <pre class="lang-py prettyprint-override"><code>def get_type(row): out = [] if row.Height &lt; 6 and row.Qualification == &quot;Msc&quot;: out.append(&quot;A&quot;) if row.Height &lt; 5.2: ...
python|pandas|dataframe|numpy
0
359,843
70,326,298
Create dataframe out of multiple dataframes
<p>I want to create a new dataframe out of 3 original dataframes I have. 3 dataframes have format: <code>Name|col1|col2</code>. Names are identical from all dataframes, the differences are values from <code>col1</code> and <code>col2</code>.</p> <p>df1:</p> <pre><code>abc 1 2 xyz 3 4 </code></pre> <p>df2:</p> <pre>...
<p>This should do the trick, you may need to add another few steps to get in in the format you need but the logic to make it is all there.</p> <pre><code>df1['key'] = 'df1' df2['key'] = 'df2' df3['key'] = 'df3' (pd.merge( pd.concat([df1, df2, df3]), pd.concat([df1, df2, df3]), on = 0). query('key_x != ...
python|pandas|dataframe
0
359,844
70,119,886
How to Audio Classification in Android give input Audio file?
<p><strong>I Classify a audio file in android use live recording. But I want to classification get a Audio file from android internal or external storage. How do this work? Please help me.</strong></p> <p>My mainActivity code is given below, that are-&gt; <strong>MainActivity.kt</strong></p> <pre><code>package com.exam...
<p>Instead of using <a href="https://www.tensorflow.org/lite/api_docs/java/org/tensorflow/lite/support/audio/TensorAudio#load(AudioRecord)" rel="nofollow noreferrer"><code>tensorAudio.load(audioRecord: AudioRecord)</code></a>, you can similarly use <a href="https://www.tensorflow.org/lite/api_docs/java/org/tensorflow/l...
android|tensorflow|kotlin|audio|classification
0
359,845
70,265,639
Best way to perform arbitrary operations on groups with Dask DataFrames
<p>I want to use Dask for operations of the form</p> <pre class="lang-py prettyprint-override"><code>df.groupby(some_columns).apply(some_function) </code></pre> <p>where <code>some_function()</code> may compute some summary statistics, perform timeseries forecasting, or even just save the group to a single file in AWS ...
<p>It appears that the current version of documentation and the source code are not in sync. Specifically, in the source code for <code>dask.groupby</code>, there is this message:</p> <blockquote> <p>Dask groupby supports reductions, i.e., mean, sum and alike, and apply. The former do not shuffle the data and are effic...
python|pandas|dask|dask-dataframe
1
359,846
70,307,974
Converting Object Attributes to Dataframe
<p>I am trying to take attributes from a list of objects and create a dataframe with the results... the following process works for the most part, but it seems inefficient and not proper. Is there another approach that wont take so many lines of code?</p> <p>Below, I am creating blank lists for each column, grabbing an...
<p>Given your example, and without benefit of testing, since I don't have the library you are using for tasks, I believe you should rethink you approach as follows:</p> <p>Rather than all the individual assignment statements, I would create two dictionaries: The first entitled attrib_dict maps the task attrib to a df c...
python|python-3.x|pandas|dataframe
0
359,847
70,098,500
How can I group-by a Dataframe to get repeated values as a list for a column
<p>After querying a DB I get a Dataframe like this:</p> <pre><code> Animal Max Speed 0 Falcon 380.0 1 Falcon 370.0 2 Parrot 24.0 3 Parrot 26.0 </code></pre> <p>As can be seen, Animal column has repeated values and I wanna group that column and get as result (it doesn't matter if the res...
<pre><code>d = {&quot;Animal&quot;: [&quot;Falcon&quot;, &quot;Falcon&quot;, &quot;Parrot&quot;, &quot;Parrot&quot;], &quot;Speed&quot;: [123, 235.2, 323, 223.3]} df = pd.DataFrame(d) df[&quot;Speed&quot;] = df.Speed.apply(lambda x: str(x)) df['CT_Speed'] = df.groupby(['Animal'])['Speed'].transform(lambda x : ', '.joi...
python|pandas|dataframe|pandas-groupby
0
359,848
70,130,957
How to handle errors from IBM Watson when iterating over rows
<p>I am a student working on a project using IBM Watson's NLU to parse through various News articles and return a sentiment score. I have the articles in a table, and I have a loop set up to go through each cell in the first column, analyze it, normalize it, and append the new data to the table.</p> <pre><code>masterd...
<p>I would recommend creating a separate function to encapsulate all that sentiment analysis logic. In the end, you would call it like this:</p> <pre class="lang-py prettyprint-override"><code>df['SENTIMENT_SCORE'] = df['CONTENT'].apply(safe_complex_function) </code></pre> <p><code>safe_complex_funtion</code> would be ...
python|pandas|dataframe|error-handling|nlp
1
359,849
70,244,189
How to create list that return the occurences of Id_1 in a dataframe?
<p>I want to create list that return the occurences of Id_1 in a dataframe:</p> <pre><code>Id_1 Id_2 0 1401 1 1 1401 3 2 1801 0 3 1801 2 4 1801 0 5 1801 0 6 2001 1 7 2001 5 8 2201 0 9 2201 0 # I would like this output: L = [(1401,2), (1801, 4),(2001,2), (2201,2)]...
<p>Use <code>value_counts</code> and <code>to_dict</code>:</p> <pre><code>L = df.value_counts('Id_1').to_dict().items() print(list(L)) # Output: [(1801, 4), (1401, 2), (2001, 2), (2201, 2)] </code></pre>
python|python-3.x|pandas|list|dataframe
0
359,850
70,369,697
Winsorizing on column with NaN does not change the max value
<p>Please note that a similar question was asked a while back but never answered (see <a href="https://stackoverflow.com/questions/65110340/winsorizing-does-not-change-the-max-value">Winsorizing does not change the max value</a>).</p> <p>I am trying to <code>winsorize</code> a column in a dataframe using <code>winsoriz...
<p>It looks like the <code>nan_policy</code> is being ignored. But winsorization is just clipping, so you can handle this with pandas.</p> <pre><code>def winsorize_with_pandas(s, limits): &quot;&quot;&quot; s : pd.Series Series to winsorize limits : tuple of float Tuple of the percentages to...
python|pandas|dataframe|numpy|scipy
2
359,851
70,340,132
Python: Pandas dataframe, merge/join tabels on different keys
<p>I have 3 tables of following form:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'ISIN': [1, 4, 7, 10], 'Value1': [2012, 2014, 2013, 2014], 'Value2': [55, 40, 84, 31]}) df1 = df1.set_index(&quot;ISIN&quot;) df2 = pd.DataFrame({'ISIN': [1, 4, 7, 10], ...
<p>You should not set the index prior to joining if you wish to keep it as part of the data in your dataframe. I suggest first merging, then setting the index to your desired value. In a single line:</p> <pre><code>output = df1.merge(df2,on='ISIN').merge(df3,on='Symbol') </code></pre> <p>Outputs:</p> <pre><code> ISIN...
python|pandas|merge
1
359,852
70,152,586
GeoDataFrame is Inverted when I converted from Raster to Vector using RasterIO
<p>I'm currently using this code to convert a raster file to a geodataframe:</p> <pre><code>import rasterio from rasterio.features import shapes mask = None with rasterio.open(#INSERT TIF FILE HERE) as src: image = src.read(1) # first band, not sure yet how to do it with multiple bands results = ( {'prop...
<ul> <li>you can use <strong>shapely</strong> <code>affine_transform()</code></li> <li>have picked up a sample <em>GEOTIFF</em>* to make this working example</li> </ul> <pre><code>import rasterio from rasterio.features import shapes import geopandas as gpd from shapely.affinity import affine_transform as T from pathlib...
vector|raster|geopandas|shapely|rasterio
0
359,853
70,242,786
Add new columns and add values from another DataFrame based on a filter
<p>Add new columns and add values from another DataFrame based on a filter:</p> <p>I have two DataFrames as follows: infra_df:-</p> <pre><code> Name time net 8am stat 8am net 8am net 8am sig 8am net 8am </code></pre> <p>measures_df:-</p> <pre><code> tcp_time. tcp_wait...
<p>If length of measures_df is same like number of <code>net</code> values in <code>infra_df</code> use:</p> <pre><code>m = infra_df['Name'].eq('net') df = pd.concat([infra_df, measures_df.set_index(m.index[m])], axis=1) print (df) Name time tcp_time. tcp_wait 0 net 8am 12.0 33.0 1 stat 8am ...
python|pandas
1
359,854
70,024,576
Create pandas dataframe from ordered dict fails
<p>I have the following python method that I got it from the selected answer to <a href="https://stackoverflow.com/questions/52902158/how-to-create-a-pandas-dataframe-from-a-list-of-ordereddicts">this question</a>:</p> <pre><code>def _dataframe_from_ordered_dict(self, source_data): return pd.DataFrame([source_d...
<p>Try this:</p> <pre><code>import pandas as pd from collections import OrderedDict l = [OrderedDict([('\ufeffZipcode', '1606'), ('primary_city', 'Worcester'), ('state', 'MA'), ('AXLE_CA_Local_Zone', '2'), ('AXLE_DS_Zone', '2'), ('ASCR_DS_Zone', '2'), ('CDL_NJ_Local_Zone', ''), ('CRX_GA_Local_Zone', ''), ('CRX_TPAFL_Z...
python-3.x|pandas
0
359,855
70,217,438
Combining data sets of different sizes
<p>My problem is next:</p> <p>I have data frame A that looks like this:</p> <pre><code>1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 </code></pre> <p>and data frame B that look like this:</p> <pre><code>2 2 2 2 2 2 2 2 2 </code></pre> <p>and I am...
<p>for the first one :</p> <pre><code>A.iloc[2:4, 2:4] = A.iloc[2:4, 2:4] + B.to_numpy() </code></pre> <p>and for the second one :</p> <pre><code>A.iloc[0:2, 0:2] = A.iloc[2:4, 2:4] + B.to_numpy() </code></pre>
python|pandas|numpy
0
359,856
70,147,936
How do I fill a large array in numpy?
<p>I'm trying to fill an array of size 2 ^ 32 and at a certain stage of filling it gives out that the process was killed</p> <pre><code>def MakeArr(n): start_time = time.time() arr = np.random.randint(1, 2**n, size=2**n, dtype=np.int64) print(arr) print(&quot;Time to create: %s sec&quot; % (time.time(...
<p>An array of 2^32 may be too large for python or numpy to handle. You may be able to get a bigger array by changing the dtype to a lower one, like <code>np.int8</code>.</p>
python|arrays|python-3.x|numpy|kill-process
0
359,857
70,297,435
Python make plot
<p>I have this code of a mortgage calculator. I would like to make this code into a plot using Matplotlib. The values I want is &quot;Principal Paid&quot; and &quot;Interest Paid&quot; as a line, showing the dollars on x and the years/dates on the y. I'm not sure how to start since I have input values, can someone help...
<p>Assuming that the <code>df</code> returned by <code>fixed_rate_mortgage</code> function is correct, the following code can be used as a starting point to plot the data frame using matplotlib.</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt x1 = df['Principal Paid'] x2 = df['Inter...
python|pandas|dataframe|matplotlib
0
359,858
70,255,503
numpy.where on 2D array is slower than list comprehension of numpy.where on 1D array
<ol> <li><p>Why is Numpy slower than list comprehensions in this case?</p> </li> <li><p>What is the best way to vectorize this grid-construction?</p> </li> </ol> <pre><code>In [1]: import numpy as np In [2]: mesh = np.linspace(-1, 1, 3000) In [3]: rowwise, colwise = np.meshgrid(mesh, mesh) In [4]: f = lambda x, y: n...
<pre><code>In [1]: In [2]: mesh = np.linspace(-1, 1, 3000) ...: In [3]: rowwise, colwise = np.meshgrid(mesh, mesh) ...: In [4]: f = lambda x, y: np.where(x &gt; y, x**2, x**3) </code></pre> <p>In addition lets make the sparse grid:</p> <pre><code>In [2]: r1,c1 = np.meshgrid(mesh,mesh,sparse=True) In [3]: rowwise....
python|arrays|numpy|performance
2
359,859
70,025,234
Failed exporting df.to_csv using a variable name in the path
<p>I am using a function <code>MyFunction(DataName)</code> that creates a pd.DataFrame(). After certain modifications to data, I am able to export such dataframe into csv with this code:</p> <pre><code> df.to_csv (r'\\kant\kjemi-u1\izarc\pc\Desktop\out.csv', index = True, header=True) </code></pre> <p>Creating an 'out...
<p>thanks for your help. In the beggining I was confused with 'NewFinger' I thought it was some sort of module I needed to install. I could not find information in google. However I solved the issue based on your suggestion actually with the following code:</p> <pre><code>DataName = &quot;whichever name&quot; df.to_cs...
pandas|dataframe|path|export-to-csv
0
359,860
70,205,952
How to change only certain values in a column with mapping? - Pandas
<p>I am trying to change specific values in my <code>chicken</code> column based on my <code>chunkiness</code> column. My <code>chicken</code> column contains <code>bob</code>, <code>all</code>, <code>berries</code>, <code>moss</code>.</p> <pre><code>mapping_dict = {0.0: &quot;small&quot;, 1.0: &quot;meh&quot;, 2.0: &q...
<p>I wasn't able to run your code due to missing data, but perhaps adding <code>na_action='ignore'</code> to the <code>map</code> method might work:</p> <pre class="lang-py prettyprint-override"><code>mapping_dict = {0.0: &quot;small&quot;, 1.0: &quot;meh&quot;, 2.0: &quot;big&quot;, 3.0: &quot;chunky!&quot;} im_df[&qu...
python|pandas
0
359,861
70,156,651
Python IndexError: index 10 is out of bounds for axis 0 with size 10
<p>I am new to coding and python.</p> <p>Trying to make a little game and getting this error message:</p> <blockquote> <p>IndexError: index 10 is out of bounds for axis 0 with size 10.</p> </blockquote> <p>My question is: How should I fix this and how to respawn a new ice drop after the first one reached the end?</p> <...
<p>First of all, do not use opencv for games, use pygame or similar. Anyway, here is the solution -</p> <pre><code>... if ice_position[0] !=10: arr[ice_position[0], ice_position[1]] = 100 else: ice_position[0]=0 ... </code></pre> <p>you just needed to add an if else statement to reset to 0 when the snowball rea...
python|numpy
0
359,862
70,087,491
Converting a csv to dict with multiple values
<p>I have a csv that when loaded looks like this.</p> <pre><code>chicken, meat veal, meat rice, carbs potato, carbs carrot, veggies mushroom, veggies apples, fruits </code></pre> <p>I want to create a dictionary from it, so I'm using the code:</p> <pre><code>food = pd.read_csv('foods.csv', header=None, index_col=1, sq...
<p>You can skip Pandas and deal with the file directly. Since you actually have a two character delimiter <code>', '</code> it is easier to skip csv too:</p> <pre><code>di={} with open('/tmp/fruit.csv') as f: for x,y in (line.rstrip().split(', ') for line in f): di.setdefault(y, []).append(x) &gt;&gt;&gt; ...
python|pandas|csv|dictionary
1
359,863
70,025,727
get the average time that an object stayed in a certain state in Pandas
<p>I have got a large DF that contains some sales opportunities. this opps change stage several times during their lifecycle and we can see what those changes are and when were they made. The possible stages are:</p> <pre><code>Closed Won Closed No Deal Propose Negotiate Qualify ...
<p>This worked for me, but you forgot to mention wich &quot;OldValue&quot; represents the creation of an OPP.</p> <pre><code>df['difference'] = df.groupby('OpportunityId').reatedDate.diff() df['aux'] = df['OldValue'] + ' - ' + df['NewValue'] df['days_diff'] = df['difference'].dt.days df.groupby('aux')['days_diff'].mean...
python|python-3.x|pandas|dataframe
1
359,864
70,048,542
Retrieve elements with max occurences with a DRAW(tie) in the max occurrence
<p>Eg., I have the following list [s, d, s, e, d, d, s]</p> <p>I need to print the elements with highest occurrences. example output: d 2 s 2</p> <p><a href="https://i.stack.imgur.com/2Z5rI.png" rel="nofollow noreferrer">enter image description here</a></p> <p>So far, i have been able to get only one element with highe...
<p>You could do something like this:</p> <pre class="lang-py prettyprint-override"><code>counts = df[0].value_counts() counts = counts[counts == counts.max()] </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; counts s 3 d 3 Name: 0, dtype: int64 &gt;&gt;&gt; counts['s'] 3 &gt;&gt;&gt; counts['d'] 3 </code></...
python|pandas|list|count|max
0
359,865
70,206,847
Saving API response as a true .JSON file
<p><strong>Background -</strong><br>I am writing some code that will take an API response, write it to a file, and also save it in a pandas DataFrame, and eventually perform some data QC.</p> <p><strong>Issue -</strong><br>I have a <code>def response_writer():</code> function, which takes the response of an api call fr...
<p>adding the file extension might fix it:</p> <pre><code>def response_writer(): api_response = api_call() timestr = datetime.datetime.now().strftime(&quot;%Y-%m-%d-%H:%M&quot;) filename = 'api_response_'+timestr+'.json' with open(filename, 'w', encoding='utf-8') as output_data: json.dump(api_re...
python|json|pandas|dataframe|api
0
359,866
70,336,149
Calculating age from date in Python
<p>I have this dataset where I would like to calculate the age:</p> <pre><code>Name DOB John 1995-12-04 James 1997-10-01 Jacoob 1997-08-30 Hansard 1995-03-12 Yusoft 1992-12-12 Henry 1993-02-12 </code></pre> <p>I have tried this code:</p> <pre><code>now = pd.Timestamp('now') df['age'] = (now ...
<p>Use <code>year</code> property to compute age:</p> <pre><code>now = pd.Timestamp('now') CustomerDemographic['DOB'] = pd.to_datetime(CustomerDemographic['DOB'] CustomerDemographic['age'] = now.year - CustomerDemographic['DOB'].dt.year - (now.dayofyear &lt; CustomerDemographic['DOB'].dt.dayofyear) print(CustomerDemog...
python|pandas
1
359,867
70,189,768
Receiving negative probabilities for my predictions
<p>I got a model that guesses the gender and ethnicity of a person based of a 48x48 image from the data set(<a href="https://www.kaggle.com/nipunarora8/age-gender-and-ethnicity-face-data-csv" rel="nofollow noreferrer">https://www.kaggle.com/nipunarora8/age-gender-and-ethnicity-face-data-csv</a>).</p> <p>The model is cr...
<p>Issue solved, y1_output and y2_output needed activation='softmax</p>
python|tensorflow
1
359,868
70,153,250
Android: How to expand dimension of image using tensorflow lite in Android
<p>The question itself is self-explanatory. In Python, its quite simple to do that with tf.expand_dims(image, 0). How can I do the same thing in Android? I'm getting error on running the tensorflow model I prepared. It says,</p> <blockquote> <p>Cannot copy to a TensorFlowLite tensor (input_3) with <strong>X</strong> by...
<p>There is JVM/Android equivalent op in the TensorFlow API: <a href="https://www.tensorflow.org/jvm/api_docs/java/org/tensorflow/op/core/ExpandDims" rel="nofollow noreferrer">https://www.tensorflow.org/jvm/api_docs/java/org/tensorflow/op/core/ExpandDims</a>.</p> <p>However, if you are using TfLite Interpreter API to r...
android|tensorflow|tensorflow-lite
0
359,869
70,159,155
How to convert url data to csv using python
<p>i am trying to download the data from the following url and tying to save it as csv data but the output i am getting is a text file. can anyone pls help what i am doing wrong here ? also, is it possible to add multiple url in the same script and download multiple csv files.</p> <pre><code>import csv import pandas a...
<p>You can create a list of your necessary URLs like:</p> <pre><code>urls = ['http://url1.com','http://url2.com','http://url3.com'] </code></pre> <p>Iterate through the list for each url and your requests will be as it is:</p> <pre><code>for each_url in urls: with requests.Session() as s: # your_code_here <...
python|json|pandas|dataframe|python-requests
0
359,870
70,200,151
Dataframe filtering with multiple conditions on different columns
<p>Let's say we have the following dataframe:</p> <pre><code>data = {'Item':['1', '2', '3', '4', '5'], 'A':[142, 11, 50, 60, 12], 'B':[55, 65, 130, 14, 69], 'C':[68, -18, 65, 16, 17], 'D':[60, 0, 150, 170, 130], 'E':[230, 200, 5, 10, 160]} df = pd.DataFrame(data) </code></pre> <p>representing different items and the...
<p>Use a condition list then flat your dataframe with <code>melt</code> then keep rows where condition is False (<code>~x</code>) then unpivot your dataframe with <code>groupby_apply</code>:</p> <pre><code>condlist = [df['A'].between(-100, 100), df['B'].between(-100, 100), df['C'].between(-70, 7...
python|pandas|dataframe
2
359,871
70,207,371
Converting "Days" from Timedelta object to regular object
<p>I'm trying to merge the two data frames below on &quot;day&quot;, but the time delta object is preventing this. My understanding is that I should be able to then do something like <code>print(df['day'].days)</code> and get the actual day without the &quot;days.&quot;</p> <p>df1</p> <pre><code>import pandas as pd fro...
<p>so this would convert to days as a non-timedelta object:</p> <p>def get_custom_str_time(x): return math.floor(x.total_seconds()/(3600*24))</p> <p>df.insert( 0, 'day', df['days'].apply(get_custom_str_time) )</p>
python|pandas|datetime
0
359,872
70,080,654
numpy , applying function over list optimization
<p>I have this two code that are doing the same but for different data structs</p> <pre><code>res = np.array([np.array([2.0, 4.0, 6.0]), np.array([8.0, 10.0, 12.0])], dtype=np.int) %timeit np.sum(res, axis=1) 4.08 µs ± 728 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) </code></pre> <pre><code>list_obj_arr...
<p>Since you used <code>otypes</code> you read enough of the <code>vectorize</code> docs to know that it is not a performance tool.</p> <pre><code>In [430]: timeit v_func(list_obj_array) 38.3 µs ± 894 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) </code></pre> <p>A list comprehension is faster:</p> <pre><c...
python|numpy|vectorization
2
359,873
70,161,635
PCA to select features for Linear regression in Pipeline
<p>I have a dataset with some numeric and categorical variables. I tried to preprocess categorical variables with pandas dummies in order to scale the data with StandardScaler. However, some columns also have missing values (mostly categorical) so I used imputer in the pipeline though it still generates the error:</p> ...
<p>you can access the pca by pipeline.named_steps['PCA']</p> <p>I fixed the errors in the pipeline for imputer</p> <p>Only get dummies the category columns df_cat=pd.get_dummies(df[cat_columns]) X=pd.concat(Df_numeric, df_cat, axis=1)</p> <pre><code> df=pd.read_csv('https://raw.githubusercontent.com/eric-b...
python|pandas|scikit-learn
-1
359,874
70,302,588
Save the minimum value of a nested for loop to Pandas Dataframe
<p>I am trying to calculate the distance from each point (coordinate) of a column in a Dataframe to each point (coordinate) of another column in another Dataframe and save the minimum distance to a Dataframe, such that the resulting Dataframe has the same length as the first column. data: intern:</p> <div class="s-tabl...
<p>I would suggest implementing what you want in the vectorised form as it's much faster. Numpy is super-efficient in the kind of calculation you need.</p> <p>Initialising some test data:</p> <pre><code>df_1 = pd.DataFrame({&quot;ID&quot;: [1, 2], &quot;coordinates&quot;: [(1.0, 0.0), (-0.5, 0.0)]...
python|pandas|dataframe|loops|nested
0
359,875
70,074,384
Line f(0) = 0 closest to a set of points
<p>Does anyone know a fast way to find a line closest to a set a points in python? (but the line should always cross the origin, in other words f(0) = 0)</p> <p>Given the equation of the line y = mx + 0 I want to find the m that optimizes this distance to every point in the set.</p> <p><a href="https://i.stack.imgur.co...
<p>The distance formula can be found here: <a href="https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line</a>. You want to minimize the sum of the distances but the distance formula contains an absolute value which will cre...
python|algorithm|numpy
0
359,876
56,096,120
What does DeepLab's --train_crop_size actually do?
<p>Following the <a href="https://github.com/tensorflow/models/blob/master/research/deeplab/g3doc/cityscapes.md" rel="noreferrer">instructions included in the model</a>, <code>--training_crop_size</code> is set to a value much smaller than the size of the training images. For instance:</p> <pre><code>python deeplab/tr...
<p>yes, it seems that in your case the images are cropped during the training process. This enables a larger batch size within the computational limitations of your system. A larger batch size leads to optimization steps which are based on multiple instances instead of considering only one (or very few) instance(s) per...
tensorflow|deeplab
5
359,877
56,241,431
pandas load in excel sheets and set to different dataframes
<p>I have an excel workbook with sheets named A, B and C</p> <p>I wanted to load all sheets and set the sheets to different dataframes, is this possible?</p> <p>This is what I have so far;</p> <pre><code>sheets=['A','B','C'] for s in sheets: df_+s=pd.read_excel(file,sheet_name=s) </code></pre> <p>so the outp...
<pre><code>dfs = pd.read_excel(file, None) </code></pre> <p>would return a dict of dataframes. The dataframes from sheet A is <code>dfs['A']</code>, sheet B is <code>dfs['B']</code> and sheet C is <code>dfs['C']</code>.</p>
excel|pandas|load
2
359,878
56,338,740
Need to select values from a column using a list of strings using pandas.str()
<p>Need to search a string column values from a list of strings. The strings in the search list are only a substring of the values in the column</p> <pre><code>df = pd.DataFrame(data={'text':['abc def', 'def ghi', 'poi opo', 'aswwf', 'abcs sd'], 'id':[1, 2, 3, 4, 5]}) Out [1]: text id 0 abc def 1 1 def ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing<...
python|pandas
2
359,879
56,407,075
Pythonic way of handling a python code for handling NAN and NAT columns
<p>I'm having a large data set with multiple columns, in each of these columns there are 4 separate columns.</p> <p>For ease the columns in Dataframe are US.A, US.B, US.C, BR.A, BR.B, BR.C Now if column US.B is blank only then fill all US related column with "-" similarly if BR.B is blank then fill BR related columns ...
<p>You can try the below approach:</p> <pre><code>df_US=df.filter(like='US') df_BR=df.filter(like='BR') </code></pre> <hr> <pre><code>pd.concat([df_US.mask(df_US['US.B'].isna(),'-'),df_BR.mask(df_BR['BR.B'].isna(),'-')],axis=1) </code></pre> <hr> <pre><code> US.A US.B US.C BR.A BR.B ...
python-3.x|pandas|dataframe
1
359,880
56,015,193
Possible gradient issue with custom activation function
<p>I need a custom activation function formulated below:</p> <p><a href="https://i.stack.imgur.com/YRHTS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YRHTS.png" alt="enter image description here"></a></p> <p>Here is how I implement it with tensorflow:</p> <pre><code>import tensorflow as tf ses...
<p>The problem is that you don't use <code>tf.where()</code> correctly to implement your activation function. You can use <code>tf.gradients</code> to see your gradient as follows:</p> <pre><code>import tensorflow as tf ... result = s_lamda_activation(a, 5) grad = tf.gradients(result,a) with tf.Session() as sess: ...
python|tensorflow
0
359,881
56,139,551
Duplicating rows where a cell contains multiple pieces of data
<p>I would like to take a dataframe and duplicate certain rows. One column, called <code>name</code>, may have multiple names. An example dataframe is contructed below:</p> <pre><code>data = [ ['Joe', '17-11-2018', '2'], ['Karen', '17-11-2018', '4'], ['Bill, Avery', '17-11-2018', '6'], ['Sam', '18-11-...
<p>After <code>str.split</code> , it become a <a href="https://stackoverflow.com/questions/53218931/how-to-unnest-explode-a-column-in-a-pandas-dataframe/53218939#53218939"><code>unnest</code></a> problem </p> <pre><code>df['name']=df.name.str.split(',') unnesting(df,['name']) Out[97]: name date number 0 ...
python|python-3.x|pandas
3
359,882
56,256,941
Which initializers are affected by tf.variable_scope("Model", reuse=None, initializer=initializer)?
<pre><code>initializer = tf.random_uniform_initializer(-0.1, 0.1) with tf.name_scope("Train"): with tf.variable_scope("Model", reuse=None, initializer=initializer): model = network.Model(iterator, is_training=True) </code></pre> <p>My question is which varia...
<p>Short answer is no. And you can check it with </p> <pre class="lang-py prettyprint-override"><code>initializer = tf.random_uniform_initializer(-0.1, 0.1) with tf.variable_scope("Model", reuse=None, initializer=initializer): model = tf.layers.Conv2D(filters=3, kernel_size=1) print(model.get_config()) </code></p...
python|tensorflow
0
359,883
56,416,998
Fix ValueError: shapes (1,2) and (4,4) not aligned: 2 (dim 1) != 4 (dim 0) in python
<p>I am using sklearn with pandas to create and fit a Linear Regression Classifier to continue a chart.</p> <p>The code i am using to create the the arrays is:</p> <pre><code>sample_data = pd.read_csv("includes\\csv.csv") sample_datat = pd.read_csv("includes\\csvt.csv") X_train= np.array(sample_data["day"]) y_train=...
<p>You should reshape it as (-1,1) instead of (1,-1)</p>
python|pandas|scikit-learn|numpy-ndarray|sklearn-pandas
1
359,884
56,039,172
How to use pandas .at function for Series with multiindex
<p>I am iterating through a large dataframe with multiindex using iterrows. The result is a Series with multiindex. After some profiling, it turned out that most of the time is spent on getting the cell value for the series, so I would like to use the Series.at function, as it is much faster. Unfortunately I haven't fo...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.loc.html" rel="nofollow noreferrer"><code>Series.loc</code></a>:</p> <pre><code>print (s.loc[("bar","one")]) 1.265936258705534 </code></pre> <p>EDIT:</p> <p>It seems it is bug.</p> <p>If working with DataFrame it working nice:</...
python|pandas
2
359,885
56,333,259
How to select the channel with maximum value at every pixel in a multichannel image?
<p>I want to fetch the channel with maximum value at every pixel in a multichannel image. I want to do with numpy without using any loop. Is there a shortcut to fetch these values?</p> <p>I can do the same by looping over every pixel value as below:</p> <pre><code>label_list = [] for i in range(height): for j in ...
<p>Argmax can solve the purpose. It returns the indices of the maximum value along an axis.</p> <p>np.unique(np.argmax(img, axis=2))</p> <p>Maybe it can help someone else.</p>
python|numpy|computer-vision
2
359,886
56,091,234
Pandas Data Frame is not correctly identified: Instance of 'tuple' has no 'filter' member
<p>I am writing a class containing pandas functionalities. As an input I have a pandas dataframe but python seems to not recognizing it right.</p> <pre><code>import pandas as pd class box: def __init__(self, dataFrame, pers, limit): self.df = dataFrame, self.pers = pers, self.data = limit ...
<p>Your problem is the comma at the end of <code>self.df = dataFrame,</code> (and <code>self.pers = pers,</code>). The comma isn't necessary here.</p> <p>The comma makes the class think you're defining <code>self.df</code> as a tuple with one member. To check this, create a box object <code>b</code> and try <code>pr...
python|pandas
1
359,887
56,245,812
Nested If statement with read_csv
<p>Have an if statement that goes and downloads a file from a server. When it's not in the if statement the script runs fine, however, within the if statement it gives me an error. Any idea?</p> <pre><code> leagues = { '1': 'Premier League', '2': 'Championship League', '3': 'Le...
<p><code>'utf-8' codec can't decode byte 0xa0 in position 1: invalid start byte</code> usually means it's a character (e.g., smart quotes) that can't be decoded into a unicode string. Thus, the problem is most likely in the .csv document, not in the code itself.</p> <p>To handle it, you can pass an explicit <code>enco...
python|python-3.x|pandas|dataframe
1
359,888
56,292,852
Improve Harmonic Mean efficiency in Pandas pivot_table
<p>I'm applying harmonic mean from scipy.stats for aggfunc parameter in Pandas pivot_table but it is much slower than a simple mean by orders of magnitude.</p> <p>I would like to know if this is excepted behavior or there is a way to turn this calculation more efficient as I need to do this calculation thousands of ti...
<p>I would recommend using <strong>multiprocessing.Pool</strong>, the code below has been tested for 20 million records, it is 3 times faster than the original, give it try please, for sure code still needs more improvements to answer your specific question about the slow performance of statistics.harmonic_mean. note: ...
python|python-3.x|pandas|numpy|scipy
2
359,889
56,271,619
Error in importing Keras with tensorflow-gpu backend (can't find libcublas.so.10.0)
<p>I'm trying to run a library included in Keras, given that it's very power-consuming I'd like to use tensorflow-gpu as a backend. During import, I get this ImportError</p> <pre><code>Using TensorFlow backend. --------------------------------------------------------------------------- ImportError ...
<p>You can try to uninstall tensorflow with :</p> <pre><code>pip uninstall tensorflow-gpu </code></pre> <p>and install an older version of it :</p> <pre><code>pip install tensorflow-gpu==1.12.0 </code></pre>
python|tensorflow|keras|nvidia
0
359,890
56,187,991
Removing a list of letter groupings and words from data-frame populated with sentences
<p>I have a dataframe <code>df</code> which contains uncleaned text strings</p> <pre><code> phrase 0 the quick brown br fox 1 jack and jill went up the hill </code></pre> <p>I also have a list of words and letter groupings that I'd like to <code>remove</code> called remove wh...
<p>Use nested list comprehension with <code>split</code>, tes membership by <code>in</code> and join splitted values back:</p> <pre><code>L = ['br', 'and'] df['phrase']=[' '.join(x for x in sent.split() if x not in L) for sent in df['phrase']] print (df) phrase 0 the quick brown fox 1 ...
python|pandas
3
359,891
56,299,999
Create new Pandas columns using the value from previous row
<p>I need to create two new Pandas columns using the logic and value from the previous row.</p> <p>I have the following data:</p> <pre><code>Day Vol Price Income Outgoing 1 499 75 2 3233 90 3 1812 70 4 2407 97 5 3474 82 6 1057 53 7 2031 6...
<p>I'd calculate the product and the mask separately, and then update the cols:</p> <pre><code>In [11]: vol_price = df["Vol"] * df["Price"] In [12]: incoming = df["Price"].diff() &lt; 0 In [13]: df.loc[incoming, "Income"] = vol_price In [14]: df.loc[~incoming, "Outgoing"] = vol_price In [15]: df Out[15]: Day ...
python|pandas
1
359,892
56,240,001
RuntimeError: expected type torch.cuda.FloatTensor but got torch.FloatTensor
<p>I keep getting the error message below. I cannot seem to pinpoint to the tensor mentioned. Below you'll find the trainer.py and main.py modules. The model I am developing is GAN on CelebA dataset. I am running the code on a remote server so have spent a handful amount of time debugging my model.</p> <p>This is the ...
<p>You are getting that error because one of <code>out_cls, label_org</code> is not on the GPU.</p> <p>Where does your code enact the <code>parser.add_argument('--cuda', action='store_true', help='enables cuda')</code> option?</p> <p>Perhaps something like:</p> <pre><code>trainer = Trainer(opt) if opt.cuda: trai...
pytorch
2
359,893
56,217,208
Handling in DataFrame in Python
<pre><code>CustomerNumber TransactionDate 1 [ 12/3/2019 12/4/2019 12/17/2019 ] 2 [ 1/4/2019 4/4/2019] 3 [ 7/5/2019] 4 [ 7/5/2019 7/7/2019 9/5/2019 9/15/2019 10/15/2019] </code></pre> <p>Hi , I have This DataFrame TransactionDate(MM/DD/YYYY), I w...
<p>We can use <code>datetime.timedelta</code> for this by converting each value in each row to a <code>datetime.datetime</code>, taking the difference of consecutive values and extracting the day value.</p> <pre><code>from datetime import datetime date_format = '%m/%d/%Y' def differencer(value): return [(datetim...
python|pandas
1
359,894
56,365,617
Checking each of element in 2D matrix
<p>I have <code>100x100</code> <code>matrix</code> in <code>numpy</code> which is made of <code>0's</code> and <code>1's</code>. I also have a <code>canvas</code> made of squares which are arranged <code>100x100</code>. This <code>canvas</code> is in correspondence with <code>matrix</code> (first square to <code>elemen...
<p>You don't need a loop</p> <pre><code># create the canvas as a copy of the original matrix canvas=m.copy() # convert canvas to have 'object' type so it can contain different types canvas=canvas.astype('object') #replace the values with the colors canvas[canvas==0]='white' canvas[canvas==1]='black' </code></pre> <p>...
python|python-3.x|numpy|matrix
2
359,895
56,347,686
Pandas parse json column and and keep existing column into a new dataframe
<p>I have the following dataframe:</p> <pre><code>name stats smith {"eye_color": "brown", "height": 160, "weight": 76} jones {"eye_color": "blue", "height": 170, "weight": 85} will {"eye_color": "green", "height": 180, "weight": 94} </code></pre> <p>I use the following code to parse the json field into a new datafr...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>df.join()</code></a>:</p> <pre><code>new_df=df[['name']].join(df["stats"].apply(json.loads).apply(pd.Series)) </code></pre>
python|python-3.x|pandas
2
359,896
56,103,048
Create all combination of 11 names out of 22 where sum of credit is 100
<p>I have two columns one has 22 Names and another column with respective credit against each name. I need to know all the combination of 11 names which sums up to 100.</p> <p><a href="https://i.stack.imgur.com/vBWuW.png" rel="nofollow noreferrer">i am attaching image of data for example. </a></p> <p>I searched and r...
<p>Doing combinations calculations of this sort is not quick. I'm timing it using time.time.</p> <pre><code>starttime = time.time() </code></pre> <p>We will use combintations from itertools.</p> <pre><code>from itertools import combinations </code></pre> <p>First I will recreate your data (please include next time ...
python|pandas|itertools
1
359,897
56,210,237
Numpy array limiting operation X[X < {value}] = {value}
<p>I came across the following in a piece of code:</p> <pre><code>X = numpy.array() X[X &lt; np.finfo(float).eps] = np.finfo(float).eps </code></pre> <p>I found out the following from the documentation:</p> <blockquote> <p><strong>class numpy.finfo(dtype)</strong>:</p> <p>Machine limits for floating point types.</p> <p...
<p>This is a fancy way of changing values of an array and changing values if condition is met. On an easy example:</p> <pre><code>X = np.random.randint(1, 100, size=5) print(X) # array([ 1, 17, 92, 9, 11]) X[X &lt; 50] = 50 # Change any value lower than 50 to 50 print(X) # array([50, 50, 92, 50, 50]) </code></pre> <...
python|numpy
1
359,898
56,236,779
Slicing NumPy array given start and end indices for generic dimensions
<p>Given a numpy array x of shape <code>(N_1...N_k)</code> where k is arbitrary, and 2 arrays :</p> <pre><code>start_indices=[a_1,...,a_k], end_indices=[b_1,...b_k], where `0&lt;=a_i&lt;b_i&lt;=N_i`. </code></pre> <p>I want to slice x as follows: <code>x[a_1:b_1,...,a_k:b_k]</code>.</p> <p>Lets say :</p> <pre><code...
<p>You can use <code>slice</code> notation to create an indexing tuple that could be used for the indexing -</p> <pre><code>indexer = tuple([slice(i,j) for (i,j) in zip(start_indices,end_indices)]) out = x[indexer] </code></pre> <p>Alternatively, with shorthand <a href="https://docs.scipy.org/doc/numpy-1.13.0/referen...
python|numpy|indexing|numpy-ndarray
3
359,899
56,015,457
Plotting a histogram with overlaid PDF
<p>This is a follow-up to my previous couple of questions. Here's the code I'm playing with:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import scipy.stats as stats import numpy as np dictOne = {'Name':['First', 'Second', 'Third', 'Fourth', 'Fifth', 'Sixth', 'Seventh', 'Eighth', 'Ninth'], ...
<p>You should plot the histogram with <code>density=True</code> if you hope to compare it to a true PDF. Otherwise your normalization (amplitude) will be off.</p> <p>Also, you need to specify the x-values (as an ordered array) when you plot the pdf:</p> <pre><code>fig, ax = plt.subplots() df2[df2[column] &gt; -999]....
python|pandas|scipy|histogram|curve-fitting
3