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
354,400
36,282,172
Is it possible to index numpy array with sympy symbols?
<p>Helle I want to do some summation on a numpy array like this</p> <pre><code>import numpy as np import sympy as sy import cv2 i, j = sy.symbols('i j', Integer=True) #next read some grayscale image to create a numpy array of pixels a = cv2.imread(filename) b = sy.summation(sy.summation(a[i][j], (i,0,1)), (j,0,1)) ...
<p>You can't use numpy object directly in SymPy expressions, because numpy objects don't know how to deal with symbolic variables. </p> <p>Instead, create the thing you want symbolically using SymPy objects, and then <code>lambdify</code> it. The SymPy version of a numpy array is IndexedBase, but it seems there is a b...
python|numpy|sympy
5
354,401
5,276,061
Efficient math operations on parts of "sparse" numpy arrays
<p>I have the following challenge in a simulation for my PhD thesis:</p> <p>I need to optimize the following code:</p> <pre><code>repelling_forces = repelling_force_prefactor * np.exp(-(height_r_t/potential_steepness)) </code></pre> <p>In this code snippet 'height_r_t' is a real Numpy array and 'potential_steepness'...
<p>masked arrays are implemented exactly for your purposes.</p> <p>Performance is the same as Sven's answer:</p> <pre><code>height_r_t = np.ma.masked_where(repelling_force_prefactor == 0, height_r_t) repelling_forces = np.ma.exp(-(height_r_t/potential_steepness)) </code></pre> <p>the advantage of masked arrays is th...
python|arrays|numpy|mask|slice
3
354,402
5,362,781
Numpy NdArray Memoization
<p>I'm working on some fairly computational intensive calculations that deal with numpy matrices and ndarrays, and from some digging around, there are about a dozen ways <strong>not</strong> to implement memoization, generally full of collisions, and issues with ndarrays being mutable objects. </p> <p>Has anyone come ...
<p>How about this package:</p> <p><s>http://packages.python.org/joblib/memory.html</s></p> <p><em><strong>2021 update</strong></em> <a href="https://joblib.readthedocs.io/en/latest/generated/joblib.Memory.html" rel="nofollow noreferrer">https://joblib.readthedocs.io/en/latest/generated/joblib.Memory.html</a></p>
python|multidimensional-array|matrix|numpy|memoization
9
354,403
4,908,957
Python - efficient representation of pixels and associated values
<p>I'm using python to work with large-ish (approx 2000 x 2000) matrices, where each <code>I</code>, <code>J</code> point in the matrix represents a single pixel.</p> <p>The matrices themselves are sparse (ie a substantial portion of them will have zero values), but when they are updated they tend to be increment oper...
<p>The general rule is, get the code working first, then optimize if needed...</p> <p>In this case, use a normal numpy 2000x2000 array, or 2000x2000x3 for RGB. This will be much easier and faster to work with, is only a small memory requirement, and has many other advantages, for example, you can use the standard ima...
python|data-structures|matrix|numpy|sparse-matrix
4
354,404
53,256,551
adding metadata to tensorflow tflearn CNN
<p>I built a simple CNN network for (medical) image classification successfully, using tflearn. When I tried to add metadata to the CNN, I ran into this problem:ValueError: Cannot feed value of shape (96, 2) for Tensor 'TargetsData/Y:0', which has shape '(1390, 2)'. Any help is appreciated:</p> <pre><code>#extract pi...
<p>It is good I can answer my question here! Anyway, I found the issue in my code above. It was a simple error. The error message led me astray. Here is the solution: Replace this code snippet</p> <pre><code>Zt= fully_connected(Z, 100, activation='relu') network = merge([network,Zt], 'concat') </code></pre> <p>with...
tensorflow|metadata|conv-neural-network
0
354,405
53,071,836
formulating a class to bring in new data while referencing a dictionary
<p>I have: </p> <p>if you wanted to accomplish this with classes instead of functions so you could import a csv and run it on new data.</p> <p>Which class would you make first and how would you iterate through the class to compare each piece of data as a part is in every building with different quantities but the mas...
<p>You would just make the dictionary a data member of the class</p> <pre><code>class Container: def __init__(self): self.data = {"part": [], # Data member of class "building": [], "qty": []} # Pass self to method of class, so it can access data members de...
python|pandas|class|oop
1
354,406
53,006,697
Panda Numpy converting data to a column
<p>I have a data result that when I print it looks like</p> <pre><code> &gt;&gt;&gt;print(result) [[0] [1] [0] [0] [1] [0]] </code></pre> <p>I guess that's about the same as [ [0][1][0][0][1][0] ] which seems a bit weird [0,1,0,0,1,0] seems a more logical representation but somehow it's not ...
<p>If you are looking to put that array in flat format pandas dataframe column, following is simplest way: <code> df["result"] = sum(result, []) </code></p>
python|pandas|numpy
1
354,407
52,955,320
Trying to use Universal Sentence Encoder Lite/2 via Tensorflow Serving
<p>I created a SavedModel using the Universal Sentence Encoder Lite version. If I load the SavedModel using tf.saved_model.loader.load, it works perfectly fine.</p> <p>However, if I try to serve the model using Tensorflow Serving, I'm getting the following error:</p> <blockquote> <p>"error": "indices[3] = 1 is not ...
<p>I was giving the input tensors in <strong>row format</strong>. By changing the format of the input tensors to <strong>columnar format</strong>, I was able to rectify the issue. A detailed description of row and columnar formats can be found <a href="https://www.tensorflow.org/tfx/serving/api_rest#request_format_2" r...
tensorflow|tensorflow-serving|tensorflow-hub
2
354,408
52,993,987
Construct dataframe from values in nested dictionary
<p>I have a list of lists of dictionaries that I'm trying to convert to a pandas DataFrame but I'm unable to use <code>pandas.DataFrame.from_dict()</code> because I want the value of the 'name' key to be the column header and the value of the 'duration' key to be the row value. Any suggestions on how I can make this wo...
<p>You can flatten your list of lists via <a href="https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable" rel="nofollow noreferrer"><code>itertools.chain</code></a>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>...
python|pandas|dictionary
4
354,409
53,206,161
Generate numpy array using multiple columns of pandas dataframe
<p>Sorry for the long post. I'm using python 3.6 on windows 10.I have a pandas data frame that contain around 100,000 rows. From this data frame I need to generate Four numpy arrays. First 5 relevant rows of my data frame looks like below</p> <pre><code>A B x UB1 LB1 UB2 LB2 0.2134 0.786...
<p>This should be rather straightforward:</p> <pre><code>from io import StringIO import pandas as pd import numpy as np data = """A B x UB1 LB1 UB2 LB2 0.2134 0.7866 0.2237 0.1567 0.0133 1.0499 0.127 0.24735 0.75265 0.0881 0.5905 0.422 1.4715 0.5185 0.0125 0.9875 0.1501 1.3...
python|arrays|pandas
1
354,410
53,307,167
diffrence from the max in each group
<p>I have a DataFrame like this:</p> <pre><code>df = pd.DataFrame({'id':['pt1','px1','t95','sx1','dc4','px5'], 'group':['f7','f7', 'f7','f8','f8','f8'], 'score':['2','3.3','4','8','4.9','6']}) </code></pre> <p>I want to add another column and calculate the difference between each score in each group with the maximum ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">groupby</a> and <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.transform.html" rel="nofollow noreferrer">transform</a> to generate the <code>max</code...
python|pandas
2
354,411
53,297,676
How do I select specific columns of a data frame, and sum them based on a condition?
<p>So here is an analogous situation of what I am trying to do</p> <pre><code>data = pd.read_csv(data) df = pd.DataFrame(data) print(df) </code></pre> <p>The data frame looks as follows</p> <pre><code> ... 'd1' 'd2' 'd3... 'd13' 0 ... 0 0 0... 0 1 ... 0 0.95 0... 0 2 ... 0 0.95 0...
<p>I believe you need compare last <code>13</code> columns selected by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.gt.html" rel="nofollow no...
python|pandas
5
354,412
53,059,201
How to convert 3D RGB label image (in semantic segmentation) to 2D gray image, and class indices start from 0?
<p>I have a rgb semantic segmentation label, if there exists 3 classes in it, and each RGB value is one of:</p> <pre><code>[255, 255, 0], [0, 255, 255], [255, 255, 255] </code></pre> <p>respectively, then I want to map all values in RGB file into a new 2D label image according to the dict:</p> <pre><code>{(255, 255,...
<p>How about this one:</p> <pre><code>mask_mapping = { (255, 255, 0): 0, (0, 255, 255): 1, (255, 255, 255): 2, } for k in mask_mapping: label[(label == k).all(axis=2)] = mask_mapping[k] </code></pre> <p>I think it's based on the same idea as the accepted method, but it looks more clear.</p>
python|numpy|array-broadcasting
1
354,413
53,289,027
generator of lists from pandas dataframe
<p>I have a pandas dataframe like</p> <pre><code> node centroid 1 1 2 2 3 4 5 6 7 2 4 1 8 4 10 1 </code></pre> <p>how can I create a generator of lists by this dataset in a way that nodes with the same centroid are in ...
<p>You use <code>yield</code> to make generators.</p> <pre><code>import pandas as pd import random df = pd.DataFrame({"node": [random.randint(1, 11) for _ in range(8)], "centroid": [random.randint(1, 5) for _ in range(8)]}) def list_gen(df): for x in df.centroid.unique(): yield df[df["centroi...
python|pandas|list|generator
1
354,414
53,306,040
Pandas resample/groupby day of week and year
<p>I am trying to create a report that is grouped by day of week for each year.</p> <p>I have a df that looks like this:</p> <pre><code> s1 s2 srd dt 2004-02-04 11:21:00 2365.79 2372.37 -7.0 2004-02-05 10:15:00 2365.79 2368.03 -2.0 2004-02-17 06:43:00 2421.05 2425.26 -4.0 2004-...
<p>If you want the <code>dayOfWeek</code> and <code>year</code> names in the index, you can assign them:</p> <pre><code>&gt;&gt;&gt; df.assign(year=df.index.year, dayOfWeek = df.index.weekday_name).groupby(['dayOfWeek','year']).srd.sum() dayOfWeek year Thursday 2004 -2.0 Tuesday 2004 -6.0 Wednesday 2004 -...
python-3.x|pandas|pandas-groupby
1
354,415
53,163,604
Resample with Pandas a longer period than original time horizon
<p>I have the following data of daily pricing:</p> <pre><code>2017-06-01 15.00 2017-06-02 20.00 </code></pre> <p>I'd like to resample it to hourly prices for over 35 hours. So the first 24h will have a value of 15.00 at every sample and from 24h to 35h the price will be at 20.00.</p> <pre><code>2017-06-01 00:00 ...
<p>You can create custom range of dates at hourly freq and reindex</p> <pre><code>df.index = pd.to_datetime(df.index) rng=pd.date_range(start=df.index.min(), periods=35, freq='H') df.reindex(rng).ffill() val 2017-06-01 00:00:00 15.0 2017-06-01 01:00:00 15.0 2017-06-01 02:00:00 15.0 2017-06-01 03:0...
python|pandas|sampling
0
354,416
53,229,424
Correlation 2D vector fields
<p>Having multiple 2D flow maps, ie vector fields how would one find statistical correlation between pairs of these? </p> <p>The <strong>problem</strong>:</p> <p>One should not (?) resize 2 flow maps of shape (x,y,2): <code>flow1, flow2</code> to 1D vectors and run </p> <p><code>np.correlation_coeff(flow1.reshape(1,...
<p>For some <em>measures of similarity</em> it may indeed be desirable to take the spatial structure of the domain into account. But a <em>coefficient of correlation</em> does not do that: it is invariant under any permutations of the domain. For example, the correlation between (0, 1, 2, 3, 4) and (1, 2, 4, 8, 16) is ...
numpy|scikit-learn|scipy|correlation|covariance
2
354,417
53,192,841
combine pd.merge with round and astype
<p>So I have two dataframes and am adding a column to df1 from df2 by using pd.merge</p> <p>It works fine, only with small problem that it adds 5 decimal. So to show it is like this:</p> <pre><code>df1 room | value A | 10 B | 19 df2 name | room | value | value2 Joe | A | 10 | 10.00000 Peter | B | ...
<p>Okay, just found this question:</p> <p><a href="https://stackoverflow.com/questions/45891237/integer-becomes-decimal-in-merged-dataframe-using-python-pandas">Integer becomes decimal in merged dataframe using python pandas</a></p> <p>So it makes sense. Therefore I have to replace first all "nan" with 0 and then do ...
python|pandas|merge
0
354,418
53,320,728
Extract one hot encoding from a file into a dataset
<p>I have a dataset images and corresponding labels, where to each image file there is a .txt file which contains the one hot encoding:</p> <pre><code>0 0 0 0 1 0 </code></pre> <p>My code looks something like this:</p> <pre><code>imageString = tf.read_file('image.jpg') imageDecoded = tf.image.decode_jpeg(imageString...
<p>Here is a function to do that.</p> <pre><code>import tensorflow as tf def read_label_file(labelPath): # Read file labelStr = tf.io.read_file(labelPath) # Split string (returns sparse tensor) labelStrSplit = tf.strings.split([labelStr]) # Convert sparse tensor to dense labelStrSplitDense = t...
python|tensorflow|tensorflow-datasets
1
354,419
53,106,717
Pandas Rolling mean with GroupBy and Sort
<p>I have a DataFrame that looks like:</p> <pre><code>f_period f_year f_month subject month year value 20140102 2014 1 a 1 2018 10 20140109 2014 1 a 1 2018 12 20140116 2014 1 a 1 2018 8 20140202 2014 2 a 1 2018 20 20140209 2014 2 a 1...
<p>Unless I'm misunderstanding it seems simpler than what you've done. What about this?</p> <pre><code>grp = pd.DataFrame(df.groupby(['subject', 'month', 'f_month'])['value'].sum()) grp['rolling'] = grp.rolling(window=2).mean() grp </code></pre> <p>Output:</p> <pre><code> value rolling subje...
python|pandas|group-by
2
354,420
53,139,784
feature generation - Aggregating based on certain column values
<p>Im using python to analyze and process a dataset. I am currently working on generating features but need some expertise.</p> <p>The data shows tasks that have been performed by trainees. Tasks can be easy or hard. Trainees can either assist or complete the task in full.</p> <p>I want to get aggregates of how may o...
<p>You could try using <code>pd.crosstab</code>, although this obviously won't be able to aggregate for a column that has no counts in <code>sample.csv</code> - e.g. the column, <code>CountEasyAssist</code>.</p> <pre><code>import pandas as pd df = pd.read_csv('sample1.csv') scores = df.groupby('Name')['Score'].sum()...
python|numpy|dataframe|data-science
0
354,421
53,333,644
How to use dask to populate DataFrame in parallelized task?
<p>I would like to use dask to parallelize a numbercrunching task.</p> <p>This task utilizes only one of the cores in my computer. </p> <p>As a result of that task I would like to add an entry to a DataFrame via <code>shared_df.loc[len(shared_df)] = [x, 'y']</code>. This DataFrame should be populized by all the (four...
<p>The right way to do something like this, in rough outline:</p> <ul> <li><p>make a function that, for a given argument, returns a data-frame of some part of the total data</p></li> <li><p>wrap this function in <code>dask.delayed</code>, make a list of calls for each input argument, and make a dask-dataframe with <co...
python|pandas|python-multiprocessing|python-multithreading|dask
0
354,422
53,060,501
Exporting keras model into tflite
<p>I am trying to combine this two examples and create the tflite file for my android app.</p> <p><a href="https://medium.com/nybles/create-your-first-image-recognition-classifier-using-cnn-keras-and-tensorflow-backend-6eaab98d14dd" rel="nofollow noreferrer">https://medium.com/nybles/create-your-first-image-recogniti...
<p>A bit late to the party but here's how you do it:</p> <pre><code>converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert() </code></pre> <p>Source: <a href="https://www.tensorflow.org/lite/convert/python_api" rel="nofollow noreferrer">https://www.tensorflow.org/lite/convert/pyt...
python|tensorflow|machine-learning|keras
1
354,423
52,951,066
How do you move to a new page when web scraping with BeautifulSoup?
<p>Below I have code that pulls the records off craigslist. Everything works great but I need to be able to go to the next set of records and repeat the same process but being new to programming I am stuck. From looking at the page code it looks like I should be clicking the arrow button contained in the span here unti...
<p>For each page you crawl you can find the next url to crawl and add it to a list.</p> <p>This is how I would do it, without changing your code too much. I added some comments so you understand what's happening, but leave me a comment if you need any extra explanation:</p> <pre><code>import requests from urllib.requ...
python|pandas|beautifulsoup
2
354,424
53,255,794
count numpy 2D array count
<p>I have a list <code>called months: array([ 1, 1, 1, ..., 12, 12, 12]),</code>which has 1~12 months and a list called <code>best_labels :array([8, 0, 0, ..., 6, 0, 0],</code> dtype=int32)`, which has 10 clusters (0~9)</p> <p>both have the same length 72915.</p> <p>Now I want to make a numpy array called <code>C[i...
<p>I think your loop should be like this</p> <pre><code>C = np.zeros((12,best_k),dtype=np.int) A = list(zip(months,best_labels)) for month, label in A: C[month-1][label] += 1 </code></pre>
python|arrays|numpy
0
354,425
53,032,754
python sklearn accuracy_score name not defined
<pre><code>x = df2.Tweet y = df2.Class from sklearn.cross_validation import train_test_split SEED = 2000 x_train, x_validation_and_test, y_train, y_validation_and_test = train_test_split(x, y, test_size=.02, random_state=SEED) x_validation, x_test, y_validation, y_test = train_test_split(x_validation_and_test, y_valida...
<p>You haven't imported accuracy score function</p> <pre><code>from sklearn.metrics import accuracy_score </code></pre>
python-3.x|pandas|classification|logistic-regression|sklearn-pandas
12
354,426
53,039,804
Storing each row of one column as Dictionary value pandas
<p>I'm newbie to pandas dataframe and I have a some tricky task to get it done.</p> <p>I have a dataframe like this. <a href="https://i.stack.imgur.com/GIcJ8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GIcJ8.png" alt="DataFrame"></a></p> <p>Text Format:</p> <p>SegmentUpper SegmentLower Materia...
<p>First convert column <code>MaterialNumber</code> to index and <code>rename</code> columns for possible split by <code>_</code> for 3 columns <code>DataFrame</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a>, then u...
python-2.7|pandas
1
354,427
53,192,824
Initialize a tensorflow model in main(), pass it to __init__ and execute inside another method
<p>I want to build a web service with flask where multiple deep learning models will be applied to certain types of data to give back a result. Currently, I want to load them locally on main() once at start, pass them to <strong>init</strong> to just initialize them once when the execution of the script starts and then...
<p>I'd hold on to the <code>Session</code> and just <code>run</code> multiple times. <code>saver.restore</code> should happen just once. For error checking you can <code>tf.get_default_graph().finalize()</code> after you specify the model to make sure the graph isn't changing each request, which would slow things down....
python|tensorflow|web-services|initialization
1
354,428
52,956,800
How to use if-else in pandas dataframes
<p>I have started learning pandas and got stumbled at the below problem:</p> <p>Following is a table which has data like:</p> <p>Book:</p> <pre><code>B_IDX B_NAME B_AUTHOR B_PRICE B_UTYPE B_ID 1 ABC aaa 12.21 SCI 182 2 BCD bbb 98 ECN 920 3 CDE ccc 22.34 SCI 22...
<p>For readability sake, build each result separately and then concatenate the pieces together.</p> <pre><code>u_id = df.B_ID.astype(str).where(df.B_UTYPE.eq('SCI')) u_cd = df.B_ID.map(ucode.set_index('U_ID').U_CD.astype(str)) ncol = (df.B_ID.astype(str) .str.extract(r'(\d{3})(\d+)') .where(df.B_UT...
python|pandas|dataframe
6
354,429
53,333,031
How to count the characters from the csv?
<p>My CSV have below data</p> <pre><code>['value'] ['abcd'] ['def abc'] </code></pre> <p>I want to count each characters in descending order of value, value is the header in the csv file. I have wrote one script below. Is there any better script than this?</p> <pre><code>from csv import DictReader with open("name.c...
<pre><code>from collections import defaultdict path = "name.csv" d_list = defaultdict(int) with open(path, 'r') as fl: for word in fl: for ch in word: #if word[0] == ch: dd[ch] += 1 del d_list['\n'] del d_list[' '] #print (d_list) dd = sorted(d_list.items(), key=lambda v:v[1], ...
python|pandas|csv|collections
0
354,430
53,214,723
Is there a limit for zip() elements in loops in python?
<p>Something weird happened to me today. I needed to create a list based on a sequence of if statements. My dataframe looks something like this:</p> <pre><code>prom_lect4b_rbd prom_lect2m_rbd prom_lect8b_rbd prom_lect6b_rbd 100 np.nan 80 200 np.nan ...
<p>You can use <code>bfill(axis=1)</code> and select the first col.</p> <pre><code>df.bfill(axis=1).iloc[:,0] 0 100.0 1 40.0 2 90.0 3 230.0 Name: prom_lect4b_rbd, dtype: float64 ## For list df.bfill(axis=1).iloc[:,0].tolist() ['100', '40', 90, '230'] </code></pre>
python|pandas|for-loop|list-comprehension
2
354,431
52,983,984
Plotting wtih seaborn - time evolution of number of my entity over years
<p>I have <code>pandas</code> dataframe representing documents which contain 3 columns - Year, Name, Type.</p> <p>I am trying to create a bar plot which will show the time evolution of my documents over years and it will also separate them by types.</p> <p>So when I have 3 years (2015, 2016, 2017) and 2 types (Good, ...
<p>Suppose you want to count each distinct record of combination of <code>Year</code> and <code>Type</code></p> <pre><code>sns.countplot(data=data1, x="Year", hue="Type") </code></pre> <p>Suppose you want to count each distinct record of combination of <code>Year</code>, <code>Type</code> and <code>Name</code></p> <...
python|pandas|seaborn
0
354,432
53,139,159
how to compare a dataset to a subset of it self? [pandas]
<p>I am trying to automate and built a cleaner code. I want my code to get a CSV, group it by X (currently variable named "Class") and then remove every 3std from mean.</p> <pre><code>import pandas as pd import numpy as np my_path = "data_291018.csv" data_loc = pd.read_csv(my_path) df = pd.DataFrame(data_loc) df = ...
<p>As much i could understood, i'm just placing my observation here so you may have a look if its relevant what you are looking for, However perfect answer still awaited from Experts:</p> <p>Simulation dataFrame from your example:</p> <pre><code>&gt;&gt;&gt; df SubjNum Class Genderm1f2 LRLevel exp1 exp2 exp3...
python|pandas|compare|pandas-groupby
0
354,433
53,313,893
Python: Cleaning the data from the csv file that is mismatched
<p>I am new in programming. I am trying to clean the data from a csv file for a further project extension. The csv file that is given as an input is really messy and I need its particular portions only.</p> <p>Input File is as follows: <a href="https://i.stack.imgur.com/VjFTx.png" rel="nofollow noreferrer"><img src="...
<p>You should try to use the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer">read_csv</a> function from pandas. There are mutliple keywords such as header, skiprows or usecols that allow you to set where you data starts in the file, skip a number of rows, ...
python|pandas|csv
0
354,434
53,328,768
Matrix multiplication with multiple numpy arrays
<p>What is the quickest way to multiply a matrix against a numpy array of vectors? I need to multiply a matrix A by every single vector in a list of 1000 vectors. Using a for loop is taking too long, so I was wondering if there's a way to multiply them all at once?</p> <p>Example:</p> <pre><code>arr = [[1,1,1], [1,1,...
<p>Seems like you want a dot product:</p> <pre><code>new_arr = np.dot(arr, A.T) </code></pre> <p>where <code>arr</code> and <code>A</code> are numpy arrays:</p> <pre><code>arr = np.array([[1,1,1], [1,1,1],[1,1,1]]) A = np.array([[2,2, 2],[2,2,2]]) </code></pre> <p>Result:</p> <pre><code>array([[6, 6], [6, 6...
python|python-3.x|numpy|scipy
2
354,435
52,939,517
How to add entries in Pandas DataFrame?
<p>Basically I have census data of US that I have read in Pandas from a csv file. Now I have to write a function that finds counties in a specific manner (not gonna explain that because that's not what the question is about) from the table I have gotten from csv file and return those counties.</p> <p><strong>MY TRY:</...
<p>There are some missing columns in the source DF posted in the OP. However, reading the loop I don't think the loop is required at all. There are 3 filters required - for <code>REGION</code>, <code>POPESTIMATE2015</code> and <code>CTYNAME</code>. If I have understood the logic in the OP, then this should be feasible ...
python|pandas|dataframe|multivalue
1
354,436
53,255,796
How to get a single value as a string from pandas data frame
<p>I am querying a single value from my data frame which seems to be 'dtype: object'. I simply want to print the value as it is with out printing the index or other information as well. How do I do this?</p> <pre><code>col_names = ['Host', 'Port'] df = pd.DataFrame(columns=col_names) df.loc[len(df)] = ['a', 'b'] t = ...
<p>If you can guarantee only one result is returned, use <code>loc</code> and call <code>item</code>:</p> <pre><code>&gt;&gt;&gt; df.loc[df['Host'] == 'a', 'Port'].item() 'b' </code></pre> <p>Or, similarly,</p> <pre><code>&gt;&gt;&gt; df.loc[df['Host'] == 'a', 'Port'].values[0] 'b' </code></pre> <p>...to get the <e...
python|pandas|numpy
58
354,437
52,918,886
Empty strings in pandas series counted as one when getting the number of words in strings
<p>I have a problem when counting the number of items in a pandas string series when there is no sting in a row.</p> <p>I´m able to count the number of words when there are one ore more items per row. But, if the row has no value (it´s an empty string when running pd.['mytext'].str.split(',')), I´m getting also one.<...
<p>Use <code>str.split</code> and count the elements with <code>str.len</code>:</p> <pre><code>df['wordcount'] = df.fruits.str.split().str.len() print(df) fruits wordcount 0 one apple 2 1 0 2 box of oranges 3 3 pile of fruit...
python|string|pandas|apply
1
354,438
53,061,807
How to ignore name that doesn't exist temporarily and randomaly from list file?
<p>I have a list of names within a file.</p> <p>Each time my program turns to one name from the list, and extracts data.</p> <p>The problem is that sometimes some of the name(s) are not available (temporarily and randomaly). </p> <p>A name that was unavailable yesterday, will be available today. but, another name th...
<p>use a <code>try</code> / <code>except</code> statement with the error you get as an exception.</p> <pre><code>with open('D:\My_Path.txt', 'r') as fp: Names = [line.rstrip('\n') for line in fp.readlines()] for Name in (Names): try: '''Do something''' except UnboundLocalError: print('%s ...
python|python-2.7|pandas
2
354,439
53,325,254
Replace Nan with 0 at where feature is missing in dataframe
<p>I am working on a dataset with missing values. The head of the dataset looks like this:</p> <pre><code>+1 1:0.2 2:0.7 3:-1.2 4:0.5 -1 1:0.9 3:0.1 4:0.8 -1 1:-0.1 2:0.1 4:1.0 +1 2:0.6 3:-1.0 </code></pre> <p>The first column is the label of the data, and the number in front of the colon is the index of the feature....
<p>The problem isn't with filling N/A values, as @BurningKarl suggested in the comments, the problem is trying to read in file with <code>read_csv</code> that isn't in any way a csv or csv-like file. You will likely need to parse this file differently. </p> <p>If it helps you get started, I have posted a snippet below...
python|pandas
1
354,440
65,720,081
Creating area chart from csv file containing multiple values in one column
<p>I have a model that produces an output in csv. The columns are as follows (just an fictive example):</p> <pre><code>| Car | Price | Year | </code></pre> <p>The car column has different car manufacturers for example, with an average car price for each year in column 'Price'.</p> <p>Example</p> <pre>...
<p>Try this I think this might work. Also, I am not a pro just a beginner</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt med_path = &quot;path for csv file&quot; med = pd.read_csv(med_path) fig, ax = plt.subplots(dpi=120) area = pd.DataFrame(prices, columns=[‘a’, ‘b’, ‘c’, ‘d’]) # in the places of a...
python|pandas|matplotlib
0
354,441
65,691,665
Currency Conversion Dataframe - skip Columns
<p>I am retrieving Yahoo stock ticker data and want to convert the given currency to euros. For this purpose I am using the Python Library Currency Converter and the pandas method multiply.</p> <p>One of the columns, trading volume, shouldn't be &quot;converted&quot; - whats the best way to skip it? This is what I curr...
<p>You can <code>loc</code> all columns except one. For example:</p> <pre><code> A B C 0 0 1 2 1 3 4 5 2 6 7 8 df.loc[:, df.columns.drop('B')] *= 10 </code></pre> <p>Result:</p> <pre><code> A B C 0 0 1 20 1 30 4 50 2 60 7 80 </code></pre>
python|pandas|dataframe
1
354,442
65,506,989
Looping panda's dataframe sometimes give different result
<p>Sometimes when I loop a panda's dataframe the variable in the foorloop refers to the column names of the dataframe, and other times it refers to the rows. Does anyone else have this problem?</p> <pre><code>for i, record in enumerate(records): print(record) </code></pre> <p>prints the colums, while other for som...
<p>You can refer to pandas <a href="https://github.com/pandas-dev/pandas/blob/v1.2.0/pandas/core/generic.py#L1787-L1796" rel="nofollow noreferrer">source code</a> .</p> <p><code>pd.DataFrame.__iter__</code>: it iterates along the info axis, which is the column names.</p> <p>hence, if you wish to loop through a datafra...
python|pandas|dataframe
1
354,443
65,622,013
Getting from a long list of strings to Pandas DataFrame
<p>I have a pricelist in pdf format which I have imported into a list. The format is such that my list looks as in the sample below.</p> <pre><code>sample = ['model description price model description price 39A Bolt 25.00 21B valve 322.40 AB3003 Engine 5000\n20B Nut 1.50 25B LockNut 3.50', 'model description...
<p>This is what I wrote that will work for the sample you have provided:</p> <pre><code>import re, pdb import pandas as pd sample = ['model description price model description price 39A Bolt 25.00 21B valve 322.40 AB3003 Engine 5000\n20B Nut 1.50 25B LockNut 3.50', 'model description price model description...
python|pandas
1
354,444
65,524,546
make two simple lines of code from python to r
<p>i'm new to R and i have difficulties translating two lines of python code into r code. the two lines are:</p> <pre><code>no = full_data[full_data.RainTomorrow == 0] yes = full_data[full_data.RainTomorrow == 1] </code></pre> <p>Can someone help me out? Thanks in advance</p>
<p>With <code>R</code>, we can use <code>$</code> instead of <code>.</code> and specify the <code>,</code> to signify the row index</p> <pre><code>no &lt;- full_data[full_data$RainTomorrow == 0,] yes &lt;- full_data[full_data$RainTomorrow == 1,] </code></pre> <p>The assignment can be also <code>=</code>, but it is a sy...
python|r|pandas|machine-learning
1
354,445
65,593,094
filter by part number
<p>let say I have ID parameter</p> <pre><code>ID=[20020,54125,45698,54220] </code></pre> <p>I want to filter only numbers that have &quot;20&quot; in ID.</p> <pre><code>20020 54220 </code></pre> <p>whats the best way to do that? `</p> <pre><code>ID=[20020,54125,45698,54220] df = pd.DataFrame(ID) </code></pre>
<p>You can also filter the list before making it a dataframe:</p> <pre><code>ID = [20020, 54125, 45698, 54220] ID = list(filter(lambda x: &quot;20&quot; in str(x), ID)) df = pd.DataFrame(ID) </code></pre> <p>Here <code>lambda x: &quot;20&quot; in str(x)</code> is like an inline funtion which accepts the element as an ...
python|pandas|dataframe|filter|pandas-loc
3
354,446
65,636,637
Keras gradient wrt something else
<p>I am working to implement the method described in the article <a href="https://drive.google.com/file/d/1s-qs-ivo_fJD9BU_tM5RY8Hv-opK4Z-H/view" rel="nofollow noreferrer">https://drive.google.com/file/d/1s-qs-ivo_fJD9BU_tM5RY8Hv-opK4Z-H/view</a> . The final algorithm to use is here (it is on page 6):</p> <p><a href="h...
<p>First, move <code>dataNoised = xBatchTrain + R</code> inside of <code>with tf.GradientTape(persistent=True) as imTape:</code> to recording the operation related to <code>R</code></p> <p>Second, instead of using:</p> <pre><code>for l,r in zip(C,R): print(imTape.gradient(l,r)) </code></pre> <p>You should using <co...
python-3.x|keras|tensorflow2.0
1
354,447
65,706,125
How to reshape an array with numpy like this:
<p>I have this:</p> <pre><code>array([[0, 0, 1, 1, 2, 2, 3, 3], [0, 0, 1, 1, 2, 2, 3, 3]]) </code></pre> <p>And I would like to reshape my array like this:</p> <pre><code>array([[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]) </code></pre> <p>How do I do it using python numpy?</p>
<p>You can just split and concatenate:</p> <pre><code>a = np.array([[0, 0, 1, 1, 2, 2, 3, 3], [0, 0, 1, 1, 2, 2, 3, 3]]) cols = a.shape[1] // 2 np.concatenate((a[:,:cols], a[:,cols:])) #[[0 0 1 1] # [0 0 1 1] # [2 2 3 3] # [2 2 3 3]] </code></pre>
python-3.x|numpy|reshape
2
354,448
65,847,051
Implementations and strategies for fast 2D interpolation from irregularly spaced points
<p>Given a large (~10 million) number of irregularly spaced points in two dimensions, where each point has some intensity (&quot;weight&quot;) associated with it, what existing python implementations are there for interpolating the value at:</p> <ul> <li>a specific point at some random position (i.e. <code>point = (0.5...
<p>Scipy is pretty good and I don't think that there are better solutions in Python, but I can add a couple things that might be helpful to you. First off, your idea of sorting the points is a really good one. The so-called &quot;incremental algorithms&quot; build the Delaunay by inserting vertices one at a time. The ...
numpy|pytorch|numba|cupy
1
354,449
65,499,989
Tensorflow Splitting metadat same way as the image_dataset_from_directory
<p>I have some images in folder respective to their classification.(i.e. under class 1 folder, there are all instances of class1 and same for other classes). Other than the images, each image also come with a few columns of metadata that could be useful for classification. This is how I've been splitting my test/valida...
<p>You can make use of <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator" rel="nofollow noreferrer">ImageDataGenerator</a> and <a href="https://keras.io/api/preprocessing/image/#flowfromdataframe-method" rel="nofollow noreferrer">flow_from_dataframe</a>.</p> <p>Below is...
tensorflow|conv-neural-network
0
354,450
65,694,410
How to make a line plot from a dataframe with multiple categorical columns in matplotlib
<p>I want to make line chart for the different categories where one is a different country, and one is a different country for weekly based line charts. Initially, I was able to draft line plots using <code>seaborn</code> but it is not quite handy like setting its label, legend, color palette and so on. I am wondering ...
<ul> <li>As requested by the OP, following is an iterative way to plot the data.</li> <li>The following example plots each year, for a given <code>'destination'</code> in a single figure</li> <li>This is similar to the <a href="https://stackoverflow.com/a/64069291/7758804">answer</a> for this <a href="https://stackover...
python|pandas|matplotlib|plot
2
354,451
65,790,794
Does pandas can search jumping point from a array
<p>When doing data visualization, it is easy to notice obvious jump points appearing on the chart. The example as follows: <a href="https://i.stack.imgur.com/BgBH3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BgBH3.png" alt="enter image description here" /></a> From the x-axis, it can be seen that...
<p>It is not 100% clear what you are after here. But an option could be to calculate a rolling average and detect when it changes the most:</p> <pre><code>df = pd.DataFrame(data) df = df.rolling(3).mean() # find the mean. See docs for rolling for more options here df.diff().abs().idxmax() # Calculate the change as abso...
python|pandas|matplotlib
2
354,452
65,713,268
how does pandas rolling std calculate?
<p>I am using a.rolling(5).std() to get a std series in a window(size=5, a is a pd.Series)</p> <p>but i found the result is not what i want.</p> <p>here is the example:</p> <pre><code>In [15]: a = [-49, -50, -50, -51, -48] In [16]: pd.Series(a).rolling(5).std() Out[16]: 0 NaN 1 NaN 2 NaN 3 ...
<p>This is probably due to Pandas normalizing by <code>N - 1</code> instead of <code>N</code>. See the first note at <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.std.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rollin...
python|pandas
2
354,453
65,530,209
ValueError: logits and labels must have the same shape ((None, 23, 23, 1) vs (None, 1))
<p>am new to ML so i don't really know what am doing i don't know what logits means in the code i haven't even written logits i just followed a YouTube tutorial to get my self familiar with the environment.. this is the entire code thanks for your help.. i am aware that there is already this kind of post on stackoverf...
<p>Your problem is that the input to the dense layer has to be a vector. To achieve that</p> <pre><code>you can replace tf.keras.layers.MaxPool2D(2,2) with tf.keras.layers.GlobalMaxPooling2D() </code></pre> <p>or just add</p> <pre><code>tf.keras.layers.GlobalMaxPooling2D() after tf.keras.layers.MaxPool2D(2,2) </code><...
python|tensorflow|valueerror|logits
1
354,454
65,586,482
Transform Set to DataFrame
<p>How to convert a set of categories into a DataFrame?</p> <p>For example:</p> <pre><code>A = [{'a', 'c'}, {'a', 'b'}, {'b', 'd'}, {'e'}] </code></pre> <p>To:</p> <pre><code> 'a', 'b', 'c', 'd', 'e' 1 1 , 0 , 1 , 0 , 0 2 1 , 1 , 0 , 0 , 0 3 0 , 1 , 0 , 1 , 0 4 0 , 0 , 0 , 0 , 1 </c...
<p>Let's try <code>explode</code> then <code>crosstab</code>:</p> <pre><code>s = pd.Series(A).explode() pd.crosstab(s.index, s) </code></pre> <p>Output:</p> <pre><code>col_0 a b c d e row_0 0 1 0 1 0 0 1 1 1 0 0 0 2 0 1 0 1 0 3 0 0 0 0 1 </code></pre> <hr /> <p><s...
python|pandas|dataframe
5
354,455
65,705,580
Issue retrieving AttributeError: 'DataFrame' object has no attribute 'Frame'
<p>I have the following data trying to plot a 3d wireframe. All the values in percentage, X Axis: CPU,Y Axis: Memory,Z Axis: Frame</p> <pre><code>Frame,10,20,30,40,50,60,70,80,90 10,40,46.66,46.67,33.33,53.33,60,40,20,46.67 20,53.33,40,53.3,46.67,53.33,53.33,46.67,40,53.33 30,46.67,46.67,46.67,33.33,66.67,33.3,60,40,40...
<p>You don't seem to be loading the headers of the csv while loading it on a DataFrame. Meaning, 'Frame' is read as a value instead of a column name.</p> <p>Print your df or its columns to ensure they are read properly.</p> <p>You should add the parameter <code>header=0</code> as follows:</p> <p><code>pd.read_csv('data...
python|numpy|matplotlib
1
354,456
65,652,577
Tensorflow Keras Gradient Tape returns None for a trainable variable of one model which is impacted by trainable variable of other model
<p>Just simple code generates None gradients. If i use other variable instead of &quot;model_tmp.trainable_variables[0]&quot; (tf.Variable b) everything would be ok and I get correct gradient</p> <pre><code>@tf.function def cat(model, model_tmp): with tf.GradientTape(persistent=True, watch_accessed_variables=False)...
<p>It's probably because you have to do the forward step on the model before TensorFlow can see the trainable variables of the model. You should run the forward step between the g.watch() and g.gradient() functions.</p>
python|tensorflow|keras
1
354,457
65,746,033
Change color in plotly bar graph
<p>How can I change in plotly express the color of a specific bar in a bar graph. For example, I want to change the color to purple , to the German Shephard (from the breed).</p> <pre><code>fig = px.bar(data_frame=df, x=&quot;quantity&quot;, y=&quot;dogs&quot;, orientation='h', color='dogs',hover_name='breed',) </code>...
<p>You can make a <code>discrete_color_map</code> dictionary like this:</p> <pre><code>color_discrete_map = {'German Shephard': 'rgb(255,0,0)'} </code></pre> <p>And pass it into your parameters when creating the bar chart like this:</p> <pre><code>fig = px.bar(data_frame=df, x=&quot;quantity&quot;, y=&quot;dogs&quot;, ...
python|pandas|plotly|plotly-express
5
354,458
65,533,269
Filter and Drop rows based on a condition for a list of list column in dataframe
<p>Sample of a much larger DataFrame I'm working on below</p> <pre><code>import pandas as pd data = {&quot;Trial&quot;: ['Trial_1', 'Trial_2', 'Trial 3', 'Trial 4'], &quot;Results&quot; : [[['a', 11.0, 1, 1.0], ['b', 12.0, 0, 6.0], ['c', 2.6, 0, 3.0]], [['d', 7.3, 1, 8.0], ['e', 13.0, 0, 5.0], ['f', 8.6, 0, 3.0]], ...
<p>You can use <code>apply</code> on <code>Results</code> using <code>query_check</code> , which you can further modify based on any changes in the filtering logic</p> <pre><code> import pandas as pd data = {&quot;Trial&quot;: ['Trial_1', 'Trial_2', 'Trial 3', 'Trial 4'], &quot;Results&quot; : [[['a', 11.0, 1, 1.0], [...
python|pandas|dataframe
1
354,459
65,678,719
Cannot compare types 'ndarray(dtype=int64)' and 'str' while trying to replace dataframe values with values from a map
<p>I have a dictionary with two different datatypes (int64 and str) and a dataframe. I am trying to replace data in the second column of my df with values from the dict if they match.</p> <p>For example-</p> <pre><code>Input: map = {'Pop': [9, 11, 13], 'HipHop': [15, 19, 22], 'Unknown': '_'} artist = {'Nam...
<p>Because <code>map</code> is function and also python code word dont use variable <code>map</code>, better is change is like <code>mapping</code>.</p> <p>Then convert <code>Reference</code> to numeric by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html" rel="nofollow noreferre...
python|pandas
1
354,460
65,794,606
Pandas: Get index number based on a condition
<p>how can I grab the index number of a dataframe only if the values of a column match the values of another column in another df?</p> <p>For instance, if I have a df_1 with a column of some words and in the other columns some values, and a df_2 with a list of words in a column and some other columns with other values...
<p>In this particular case you would need to pre-filter the df and then use <code>.index.tolist()</code> to get the index values as a list.</p> <pre><code>output = df_1[df_1['Word'].isin(df_2['Word'].values)].index.tolist() </code></pre> <p>The first part of the code is keeping only the rows in which the <code>Word</co...
python|pandas
0
354,461
65,889,052
How to convert a list with dictionaries into new pandas columns?
<p>I have a dataframe which has a list of dictionaries as a column: This column has the following format:</p> <pre><code>[{'route_id': '1', 'stop_id': '1'}, {'route_id': '2', 'stop_id': '2'}] </code></pre> <p>How can I convert this column into 4 new columns? I mean: route_id (x2), stop_id(x2) as new columns.</p> <p>Tha...
<p>You can use <a href="https://www.google.com/search?client=safari&amp;rls=en&amp;q=df.explode&amp;ie=UTF-8&amp;oe=UTF-8" rel="nofollow noreferrer"><code>df.explode</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>df.apply<...
python|pandas|list|dataframe|dictionary
1
354,462
65,841,211
I'm not able to slice and modify my array to extract desired information out of it
<p>I wanna read an excel file via pandas.read_excel but the first row is just the indication of the data in the column and I don't want it to be imported. I use this code to skip first row :</p> <pre><code>nodes=pd.read_excel(filename,skiprows=1) </code></pre> <p>but it manipulates the second row which is my interested...
<p>I solved this!</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import time import pandas as pd FilePatch='E:\\# Civil Engineering Undergraduate\\Projects\\Python\\Frame' NodesFile=FilePatch+'\\nodes4.xlsx' MemsFile=FilePatch+'\\members4.xlsx' MatsFile=FilePatch+'\\sections4.xlsx' nodes=pd.read_exc...
python|arrays|pandas|types|slice
0
354,463
65,770,109
How to merge two rows of a pandas dataframe depending on a condition in Python?
<p>I have a <code>dataframe</code> :</p> <pre><code> order_creationdate orderid productid quantity prod_name price Amount 0 2021-01-18 22:27:03.341260 1 SnyTV 3.0 Sony LED TV 412.0 1236.0 1 2021-01-18 17:28:03.343089 1 AMDR5 1.0 AMD Ryzen ...
<pre class="lang-py prettyprint-override"><code>df2.groupby(['productid', 'orderid'], as_index=False).agg( {'quantity': sum, 'Amount': sum, 'order_creationdate': min, 'prod_name': min, 'price': min} ) </code></pre> <p>The output is:</p> <pre class="lang-sh prettyprint-override"><code> productid orderid quantity ...
python|pandas|dataframe
0
354,464
65,650,983
How to apply function to pandas DataFrame, but with existing DataFrame attribute?
<pre><code>import pandas as pd import numpy as np from numpy.random import randn X = pd.DataFrame(randn(100,3)) print(X.var()) </code></pre> <p>The above code prints the variance (an attribute) of each column of a pandas DataFrame <code>X</code> (a matrix), returning a 3-element panda Series. How can apply a function ...
<p>Try using <code>ddof</code> argument:</p> <pre><code>print(X.var(ddof=2)) </code></pre> <p>You don't need <code>apply</code>.</p>
python|pandas|dataframe|statistics|apply
0
354,465
65,528,952
How to pass pandas data frame between classes
<p>There's 2 classes. The <strong>Content class</strong> contains the data frame <strong>df</strong> that needs to be passed to the <strong>Main class</strong> data function, so that the dataframe df3 in the Main Class can get the data frame df from Content class. How can it be done?</p> <pre><code>from tkinter import ...
<p>It's not super clear, what you want to do. A somewhat simpler example of what I <em>guess</em> you want to do is here:</p> <pre><code>import pandas as pd class Main: def __init__(self, df): self.df = df def work_with_data(self): return self.df.loc[self.df[&quot;name&quot;]==&quot;Anna&quot;...
python|pandas
0
354,466
65,600,306
module 'pandas' has no attribute 'Panel'
<p>I am getting an error while I am converting dictionary data frames to Panel dataframe</p> <p><code>panelda = pd.Panel()</code></p> <pre><code>--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-33-e8...
<p>Found the answer myself, I was using the latest Pandas v1.2.0, where the panel has been removed from Pandas module 0.25.0 onwards.</p> <pre><code>print(pd.__version__) print(np.__version__) 1.2.0 1.19.4 </code></pre> <p>From <a href="https://pandas.pydata.org/pandas-docs/version/0.25.3/whatsnew/v0.25.0.html" rel="no...
pandas|panel-data
8
354,467
65,591,835
How to iterate every row(every cell) and check whether the cell contains value or nan, if nan skip row
<p>I have the code like this</p> <pre><code>for r in df.iterrows(): try: if str(r[1][0]) !='nan' and str(r[1][1]) != 'nan' and str(r[1][2]) !='nan' and str(r[1][3]) !='nan' and str(r[1][4]) !='nan' and str(r[1][5]) !='nan': </code></pre> <p>what I need to do is to check if every cell contain...
<p>When you work with pandas i suggest you to not think of “iterating” because it works a little bit differently...</p> <p>You should look for a vectorized solution for most of the scenarios because looping in python is slow in comparison to the vectorization numpy and pandas provide...</p> <p><strong>SOLUTION</strong>...
python|excel|pandas|dataframe
1
354,468
65,543,305
Converting list to data frame doesn't work
<p>I'm having difficulty in converting lists into dataframe after a loop. I was getting results for the first 3 lines, however the rest of the output are NaN values. Here's my code. Any help is much appreciated. Thank you</p> <pre><code> for i in range(0,5000): data=data_phished[&quot;url&quot;][i] i...
<p>First of all, you don't really need to use pd.Series inside the <code>feat_col</code> dict.</p> <pre class="lang-py prettyprint-override"><code>feat_col = {'request_url':urlRequest, 'anchor_url':urlAnchor,'links_in_tags':linksTags,'server_from_handler':sfh,'submit_info_email':emailSubmit,'abnormal_url':urlAbnormal,'...
python|pandas|dataframe
1
354,469
65,514,944
Tensorflow embeddings InvalidArgumentError: indices[18,16] = 11905 is not in [0, 11905) [[node sequential_1/embedding_1/embedding_lookup
<p>I am using TF 2.2.0 and trying to create a Word2Vec CNN text classification model. But however I tried there has been always an issue with the model or embedding layers. I could not found clear solutions in the internet so decided to ask it.</p> <pre><code>import multiprocessing modelW2V = gensim.models.Word2Vec(fil...
<p>I solved this solution. I was adding a new dimension to vocab_size by doing it vocab_size + 1 as suggested by others. However, since sizes of layer dimensions and embedding matrix don't match I got this issue in my hands. I added a zero vector at the end of my embedding matrix which solved the issue.</p>
tensorflow|nlp|word2vec|embedding|word-embedding
1
354,470
65,682,994
ModuleNotFoundError: No module named 'keras' Can't import keras
<p>I have tried reinstalling anaconda. I also tried uninstalling and reinstalling keras. I have tensorflow 2.3.0 and keras 2.4.3 installed. But I just can't seem to be able to import keras. This is my import statement.</p> <pre><code>from keras.models import Sequential from keras.layers import Dense, LSTM from pandas ...
<p>I would first like to ask you whether only Tensorflow/Keras is broken.</p> <p>An obvious reason for a <code>ModuleNotFoundError</code> problem is that Keras is not reachable by Python library lookups. Although this is a common problem everybody has experienced, the primary solution is simple.</p> <p>You can check in...
python|tensorflow|keras|deep-learning
1
354,471
65,655,246
Python, Pandas: Compare two dataframes and return combined
<p>Good evening,</p> <p>I would like to know, which is the best way to compare two dataframes and return a combination of them? Or if there's even a build-in function inside pandas?</p> <p>For example, these are my two dataframes:</p> <p><strong>Dataframe 01:</strong></p> <pre><code>first_name | age | id | value_a | va...
<p>Since you asked <em>if there's even a built-in function inside pandas?</em>. The answer is yes, there is a built in function in pandas that allows you to compare identically labelled (with same index and columns) dataframe's.</p> <p>There is a <strong><a href="https://pandas.pydata.org/pandas-docs/stable/reference/a...
python|pandas|dataframe|compare
3
354,472
65,704,024
pd.DataFrame.from_dict() won't work for column-wise Dataframe
<p>I have a dictionary that I want to create into a Dataframe with a single row. The dictionary keys should be the columns and the dictionary values should be all the single row items. For example my dictionary looks as such:</p> <pre><code>{'gross_margin': 92.10000000000001, 'ebitda_margin': 52.8, 'net_margin': 48.199...
<p>Convert the values of your <code>dict</code> to <code>lists</code></p> <pre><code>dictionary = {'gross_margin': 92.10000000000001, 'ebitda_margin': 52.8, 'net_margin': 48.199999999999996} dictionary = {k:[v] for k,v in dictionary.items()} pd.DataFrame(dictionary) </code></pre> <pre><code> gross_margin ebitda_marg...
python|pandas|dictionary
0
354,473
65,907,096
hvplot call inside function does not display in Jupyter Notebook
<p>I am new to hvplot and trying to include a call to <code>.hvplot()</code> inside a function definition, but it's not working. The following code works and displays a figure as expected:</p> <pre><code>import pandas as pd import hvplot.pandas df = pd.DataFrame([1, 5, 3, 4, 2]) df.hvplot() </code></pre> <p>but if I t...
<p>You need to return the result of your function:</p> <pre class="lang-py prettyprint-override"><code>def plot(df): return df.hvplot() plot(df) </code></pre> <p>Or:</p> <pre class="lang-py prettyprint-override"><code>def plot(df): my_plot = df.hvplot() return my_plot plot(df) </code></pre>
python|pandas|holoviews|hvplot
2
354,474
65,863,710
normalize strings of a column with fuzzy
<p>I have a df similar to this (this is just an example, original df in spanish and is cumbersome to copy paste an excerpt here):</p> <pre><code>date city1 city2 ID company 01-10-2020 Mexico Mexico 1234 ColaCola 03-01-2020 Mexico Baja 567 Cola cola 02-09-2020 Mexico Culiacan 89...
<pre class="lang-py prettyprint-override"><code>obj = df['company'] # have a look at `company` obj.value_counts().sort_index() # use regexp and find the common part in regexp cond = obj.str.contains('cola\s*cola', flags=re.IGNORECASE) df.loc[cond, 'NAME_new'] = 'Cola Cola' ... # find the other company name's common &...
python|pandas|fuzzywuzzy
0
354,475
65,659,338
Is regex or replace method best to clean up list ? re Pandas environment
<p>From the list below I'm able to remove the non-alphabet characters but fall short all the same. I want the Draw eliminated without affecting the desired outcome.</p> <pre><code>df=pd.DataFrame({'Teams': ['Lakefield United', '101002 Castle FC pk, +½ 1.81 o 3.05 o Un 2 1.92 o', '101003 Draw 3.00 o', 'Boms', '10100...
<p>As others have suggested, this requires constructing a termination list for determining when the second team's name ends. Below is one way to do it. You may need to add more items to your termination list, but there will be a limited number of them. I have also converted the dataframe to a list for ease of manipu...
python|python-3.x|regex|pandas|dataframe
0
354,476
65,864,710
How can I locate a index of a selected row in pandas?
<p>I Have this code that returns this:</p> <p>IN:</p> <pre><code>print (df.loc[pay_date]) </code></pre> <p>OUT:</p> <pre><code>High 7.515069 Low 7.515069 Open 7.515069 Close 7.515069 Volume 1392.000000 Adj Close 7.478741 Name: 2015-02-11 00:00:00, dtype: float64 <...
<p>Use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_loc.html" rel="nofollow noreferrer"><code>get_loc</code></a> method of the index:</p> <pre><code>df.index.get_loc(paydate) </code></pre>
python|pandas
1
354,477
65,831,090
Why am I getting column headers for each index of a dataframe in Python?
<p>Hi so currently I am trying to create an empty dataframe in python using this code:</p> <pre><code>for i in range (len('bus0')): empty_df = pd.DataFrame(np.nan, index=[i], columns=['bus0', 'bus1']) print(empty_df) </code></pre> <p>But I am getting an output (below) which reprints the column headers bus0 and ...
<pre><code>import pandas as pd import numpy as np array = np.asarray([np.nan for x in range(8)]).reshape((4,2)) df = pd.DataFrame(array, columns=['bus0', 'bus1']) </code></pre>
python|pandas|dataframe
1
354,478
65,493,350
How to convert a pandas data frame to nested json
<p>Currently have a data frame contain laptop info and the aim is to transform the data to a nested json structure. As the laptop's brand, price and weight are related info, thus would like to group them together under the laptop field. Any pointer on how to convert the data frame would be appreciated.</p> <p><em><code...
<p>Consider <code>df</code>:</p> <pre><code>In [2729]: df = pd.DataFrame({'Store code':[1, 12, 132], 'Laptop brand':['Lenovo', 'Apple', 'HP'], 'Laptop price':[1000, 2000, 1200], 'Laptop weight':[1.2, 1.5, 1.4], 'star':[3, 5, 4]}) In [2730]: df Out[2730]: Store code Laptop brand Laptop price Laptop weight star 0...
python|python-3.x|pandas|dataframe
3
354,479
65,603,852
Plotly grouped bar chart from pandas df
<p>I am having trouble making a grouped bar chart with the given structure of my pandas df which looks like this:</p> <pre><code> yhat yhat_upper yhat_lower cat grp cycle_label 0 5.716087e+08 6.123105e+08 5.319125e+08 yello costs funding1 1 1.501483e+08 1.641132e+08 1.452377e+08 blue ...
<p>Split the dataframe by the columns you want to group and use plotly to create a graph based on it.</p> <pre><code>import plotly.graph_objects as go f1 = tmp_df[tmp_df['cycle_label'] == 'funding1'] f2 = tmp_df[tmp_df['cycle_label'] == 'funding2'] cats = df['cat'].unique().tolist() fig = go.Figure() fig.add_trace(g...
python|pandas|plotly|bar-chart
1
354,480
65,541,342
How to Append data in existing postgres table with incrementing primary key using python df._topostgis?
<p>I have created a table in postgresql,</p> <p>in which I am dumping the data of Geopandas GoeDataFrame.</p> <p>After dumping it, I am assigning/making the column named &quot;fid&quot; as the primary key column.</p> <p>and I have to update this table daily.</p> <p>When I am replacing the table, then it is working fine...
<p>The task basically requires you to clean up any existing duplicate values in the column that is to become the PK, and identifying the maximum value of that column. That will be necessary anyway, so NO extra work. I am unable to write the necessary code in your ORM as I don't know it. Even if I could I would not, the...
python|pandas|postgresql|postgis|geopandas
1
354,481
65,552,941
Fastest way to transpose a matrix stored in an 1D array in NumPy?
<p>Given a vector <code>v</code> of length <code>N^2</code> that holds the entries of a <code>NxN</code> matrix <code>M</code>, what is the fastest way to compute the transpose of <code>M</code> in the same vector representation using NumPy?</p> <p>I know this can be done by</p> <pre><code>v.reshape(N, N).T.flatten() <...
<p>Consider a test case:</p> <pre><code>In [207]: N=1000 In [208]: X = np.arange(N*N) </code></pre> <p>Your code:</p> <pre><code>In [209]: Y = X.reshape(N,N).T.flatten() In [210]: timeit Y = X.reshape(N,N).T.flatten() 5.45 ms ± 13 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) </code></pre> <p>A suggested alt...
python|arrays|numpy|matrix
3
354,482
65,578,339
`numpy.empty()` and `numpy.random.rand()` same or different
<p>In <code>NumPy</code> there are two functions, one is <code>numpy.random.rand()</code> and another is <code>numpy.empty()</code>. Both functions are giving me same output. Code:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.random.rand(3,2) array([[0.54372255, 0....
<p>They are different!</p> <p>Rand, based on a seed <strong>generate</strong> some numbers of a given shape.</p> <p>On the other part, <strong>empty</strong> return an <strong>unitializated</strong> array, so it means that is pointing to a random memory location, accidentally this return random values, but out of cont...
python|function|numpy|random
4
354,483
65,896,230
Seaborn's relplot gives a ValueError
<p>I am trying to do some relplots in seaborn. But I get VaueError. Here is my code:</p> <pre><code>tips = sns.load_dataset(&quot;tips&quot;) sns.relplot(x=&quot;total_bill&quot;, y=&quot;tip&quot;, data=tips, kind='scatter', hue='sex') </code></pre> <p>I get a long error message. I am pasting only the last part of the...
<p>Note that your StackTrace starts with:</p> <pre><code>sns.relplot(data=df, x=&quot;speeding&quot;, y=&quot;alcohol&quot;, hue=&quot;abbrev&quot;) </code></pre> <p>So <em>data</em> parameter is <em>df</em> not <em>tips</em>.</p> <p>Probably you are wrong as to what actually executes your program.</p> <p>Check your...
python|numpy|matplotlib|anaconda|seaborn
0
354,484
65,661,499
How to see if a dataframe column values exist in a list
<p>I have a dataframe column named 'Ace Code' (<code>df['Ace Code']</code>) and would like to check if the column value for each row exists in the list below.</p> <pre><code>codes = ['M6L', 'M8V', 'M9A', 'M9N', 'M2L', 'M4B', 'M4K', 'M4S', 'M5A',\ 'M5J', 'M5R','M6A', 'M6J', 'L4W', 'L5C', 'L5L', 'L3T', 'M2N', \ ...
<p>You can do this -</p> <pre><code>import pandas as pd codes = ['M6L', 'M8V', 'M9A', 'M9N', 'M2L', 'M4B', 'M4K', 'M4S', 'M5A', 'M5J', 'M5R','M6A', 'M6J', 'L4W', 'L5C', 'L5L', 'L3T', 'M2N', 'M3M', 'L4T', 'L6R', 'L6Y','L3P', 'M1T', 'M1C', 'M1L', 'L4H',] other_codes = ['HVH','HKJ','PYU','TRE','QWE']...
python|pandas|dataframe|data-cleaning
-1
354,485
65,825,834
pandas: calculatig average similarity across all categories
<p>I have a dataframe like the following but larger:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = {'First': ['First value','Third value','Second value','First value','Third value','Second value'], 'Second': ['the old man is here','the young girl is there', 'the old woman is h...
<p>EDIT: Based on your comments, here is what you can do.</p> <ol> <li>First calculate <code>data_similarity</code> table which combines the tokens from the different sentences for the group.</li> <li>Calculate pairwise similarity tuples between sentences</li> <li>Put them into a dataframe and then groupby the overall ...
pandas|average|similarity|across
1
354,486
65,516,926
Reshaping before as_strided for optimisation
<pre class="lang-py prettyprint-override"><code>def forward(x, f, s): B, H, W, C = x.shape # e.g. 64, 16, 16, 3 Fh, Fw, C, _ = f.shape # e.g. 4, 4, 3, 3 # C is redeclared to emphasise that the dimension is the same Sh, Sw = s # e.g. 2, 2 strided_shape = B, 1 + (H - Fh) // Sh, 1 + (W - Fw) // ...
<p>Reshaping of the strided array is a little bit costly, for the reasons you've mentioned (copy on non-contiguous array), but not as costly as you think. <code>np.einsum</code> can actually be a bottleneck in your application, depending on tensor sizes. As mentioned in <a href="https://stackoverflow.com/questions/5608...
python|numpy|conv-neural-network|tensor|numpy-einsum
1
354,487
65,888,506
ERROR: (wheel).whl is not a supported wheel on this platform
<p>I'm trying to build Tensorflow from source (if I install directly it works fine but I'm trying to get AVX2/FMA extensions support as I can't use CUDA/GPU) and I'm following <a href="https://medium.com/@thomaschou_9652/customized-tensorflow-for-macos-1fe31110d92c" rel="nofollow noreferrer">this tutorial</a> to build ...
<p>FOR MACOS - BIG SUR</p> <p>I was able to solve this problem when I found that the version of the <strong>macOS operating system does not match the version actually recognized by python</strong></p> <p>I'm using macOS 11.4, the file is with this version. But when typing a command in the terminal, I found that python ...
python|python-3.x|tensorflow|anaconda|bazel
4
354,488
65,711,587
Sagemaker not outputting Tensorboard logs to S3 during training
<p>I'm training a model with Tensorflow using Amazon Sagemaker, and I'd like to be able to monitor training progress while the job is running. During training however, no Tensorboard files are output to S3, only once the training job is completed are the files uploaded to S3. After training has completed, I can downloa...
<p>First some speculation without any facts: Sagemaker could work as some other systems that sync files between local drive and s3. They might check that the file hasn't been accessed recently before syncing it so that they don't copy it while someone is writing to it. The log files are written constantly until shutdow...
python|amazon-web-services|tensorflow|tensorboard|amazon-sagemaker
0
354,489
21,361,409
Calculating expanding mean on 2 columns simultaneously
<p>I have a table of 2 players competing each other:</p> <pre><code> date plA plB ptsA ptsB 0 01/01/2013 Jeff Tom 78 72 1 15/01/2013 Jeff Tom 52 67 2 01/02/2013 Tom Jeff 91 93 3 15/02/2013 Jeff Tom 83 87 4 01/03/2013 Tom Jeff 65 76 </code></pre> ...
<p><strong>(Please, refer to the fixed solution below)</strong></p> <p>One approach is to find out all the player's names first:</p> <pre><code>names = pd.concat((df.plA, df.plB)).unique() </code></pre> <p>Then create one new column with the expanding mean for each player:</p> <pre><code>for name in names: df['...
python|pandas|mean
1
354,490
21,258,343
Coding variables with Pandas TimeSeries
<p>As a follow up to something I was struggling with in a <a href="https://stackoverflow.com/questions/20999724/mean-of-pandas-timeseries-using-groupby">previous question</a>, I've been working for a long time on an analysis of some pretty complicated behavioural data from a mouse-tracking experiment in Pandas.</p> <p...
<p>I've been asked via email if I ever found a solution to what I wanted to do here, so I'm sharing what I've been doing to date. This might not be the canonical way of using <code>pandas</code>, but it's sufficed for me.</p> <p>In short, I've split my data into a couple of data frames. The first, <code>data</code>, i...
python|numpy|pandas|time-series
0
354,491
21,020,449
Python: How to do several float formattings with 1 lambda function
<p>I have a numpy array [2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01] and would like to format it so that it looks like this [21.53, 08.13, 03.97, 10.08]</p> <pre><code>float_formatter = lambda x: "%.2f" % x np.set_printoptions(formatter={'float_kind':float_formatter}) </code></pre> <p>How...
<p>If you want to work with two floats in your lambda, you need two input arguments like this:</p> <pre><code>float_formatter = lambda x, y: "%.2f %.2f" % (x, y) </code></pre> <p>You can define multiple inputs to lambda expressions, not just a single and the name is arbitrary. Here's the same thing with different arg...
python|numpy|lambda
1
354,492
20,979,746
DictVectorizer Recognize Feature as String
<p>The list of dictionaries that I am running through DictVectorizer (0.14) have specific categorical values that have been encoded to integers:</p> <pre><code>&gt; dictionary_list[0:2] </code></pre> <p>Out:</p> <pre><code>[{u'Life': 3377, u'SerumX': 1015, u'duration': 3, u'gene_name': 37}, {u'Life': 11655, u'Serum...
<p>I guess you can speed things a bit if you change your code to something like</p> <pre><code>for dct in dictionary_list: if 'gene_name' in dct: dct['gene_name'] = str(dct['gene_name']) </code></pre> <p>I think you can't get away from coercing values to strings, as DictVectorizer uses <code>isinstance(va...
python|dictionary|numpy|scikit-learn
2
354,493
21,237,584
Using Boolean Statements to Address a Pandas Series
<p>I have some data in a Pandas DF and would like to isolate specific portions of it based on some boolean conditions. The following two lines work as I want them to:</p> <pre><code>df['test'] = df[df.N == 30].my_variable df['test2'] = df[df.Y &gt;0.4].my_variable </code></pre> <p>Not being that familiar with Pandas ...
<p>As mentioned, you can wrap this with parenthesis to force the correct precedence:</p> <pre><code>df[(df.N == 30) &amp; (df.Y &gt; 0.4)].my_variable </code></pre> <p>It's worth mentioning that you can use <code>loc</code> (which I think is slightly cleaner):</p> <pre><code>df.loc[(df['N'] == 30) &amp; (df['Y'] &gt...
python|pandas
2
354,494
20,938,586
Get minimum x and y from 2D numpy array of points
<p>Given a numpy 2D array of points, aka 3D array with size of the 3rd dimension equals to 2, how do I get the minimum x and y coordinate over all points? </p> <p><strong>Examples:</strong></p> <p><strong>First:</strong></p> <p><em>I edited my original example, since it was wrong.</em></p> <pre><code>data = np.arra...
<p>alko's answer didn't work for me, so here's what I did:</p> <pre><code>import numpy as np array = np.arange(15).reshape(5,3) x,y = np.unravel_index(np.argmin(array),array.shape) </code></pre>
python|arrays|numpy
8
354,495
21,265,953
Why doesn't my apply function return the length of the string?
<p>I'm trying to add a Pandas DataFrame column containing the length of the string in another column.</p> <pre><code>csv = pd.read_csv('data/sentiments.csv', dtype=str) csv['length'] = csv['text'].astype(str).apply(len) csv.head() text polarity length 0 -Mi hij...
<p>To avoid possible issues with the type promotion logic of <code>astype</code> you can also try:</p> <pre><code>csv['length'] = csv['text'].apply(lambda x: len(str(x))) </code></pre> <p>and you can also use <code>map</code> instead of <code>apply</code> since you're operating along the values of a <code>Series</cod...
python|pandas|type-conversion
1
354,496
2,850,743
NumPy: how to quickly normalize many vectors?
<p>How can a list of vectors be elegantly normalized, in NumPy?</p> <p>Here is an example that does <em>not</em> work:</p> <pre><code>from numpy import * vectors = array([arange(10), arange(10)]) # All x's, then all y's norms = apply_along_axis(linalg.norm, 0, vectors) # Now, what I was expecting would work: print...
<h1>Computing the magnitude</h1> <p>I came across this question and became curious about your method for normalizing. I use a different method to compute the magnitudes. <em>Note: I also typically compute norms across the last index (rows in this case, not columns).</em></p> <pre><code>magnitudes = np.sqrt((vectors *...
python|vector|numpy|normalization
27
354,497
63,604,192
Numpy is not inserting the right array into multidimensional array
<p>I have a matrix</p> <pre><code>M = np.array([ [1, -2, -2, -2, 1, 2], [0, 3, -2, -3, 1, 3], [3, 0, 0, 1, -1, 2], [3, -3, -2, 0, 1, 1], [0, -3, 3, -3, -3, 2] ]) </code></pre> <p>and I'm trying to replace the first row by itself modulo some number <code>N = 2497969412496091</code>.</p> <p>I've been playing around with ...
<p>Your array is <code>np.int32</code>:</p> <pre><code>print(type(M[0][0])) # &lt;class 'numpy.int32'&gt; </code></pre> <p>Create the original array as <code>np.int64</code> - to avoid getting integer overflow happening:</p> <pre><code>import numpy as np M = np.array([ [1, -2, -2, -2, 1, 2], [0, 3, -2, -3, 1, 3], [3,...
python-3.x|numpy
1
354,498
63,465,187
RuntimeError: cudnn RNN backward can only be called in training mode
<p>I have seen this problem the first time, I never encountered such an error in previous Python projects. Here is my training code:</p> <pre><code>def train(net, opt, criterion,ucf_train, batchsize,i): opt.zero_grad() total_loss = 0 net=net.eval() net=net.train() for vid in range(i*batchsize,i*batc...
<p>You should remove the <code>net.eval()</code> call that comes right after the <code>def infer(net, name):</code></p> <p>It needs to be removed because you call this infer function inside your training code. Your model needs to be in train mode throughout the the whole training.</p> <p>And you never set your model ba...
deep-learning|pytorch|recurrent-neural-network|cudnn
2
354,499
63,429,520
Removing a char from a pandas dataframe column with for loop
<p>I have a DF that has a country column and some of that countries has &quot;(&quot; in it. I tried to remove all of that &quot;(&quot; s with this for loop:</p> <pre><code>for country in df_energy['Country']: if ')' in df_energy['Country']: df_energy['Country'] = df_energy['Country'].replace({'(':'', ')':...
<p>You don't need the loop:</p> <pre><code>df_energy['Country'] = df_energy['Country'].str.replace('[()]', '') </code></pre> <p>If you want to only replace matching <code>()</code> then:</p> <pre><code>df_energy['Country'] = df_energy['Country'].str.replace('\((.*)\)', r'\1') </code></pre>
python|pandas
0