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
11,500
67,066,214
Groupby column value and keep row based on another column value
<p>I have a DataFrame, <code>df</code>, that has a range of values such as:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">ID</th> <th style="text-align: center;">Code</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">01</td> <td style="text-align...
<p>You can sort your dataframe by <code>ID</code> and boolean value (<code>False</code> when Code starts with <code>&quot;BC&quot;</code>), then <code>.groupby()</code> and take first item:</p> <pre><code>df[&quot;tmp&quot;] = ~df.Code.str.startswith(&quot;BC&quot;) df = df.sort_values(by=[&quot;ID&quot;, &quot;tmp&quo...
python-3.x|pandas|pandas-groupby
1
11,501
66,938,978
Split a numpy array into 8-elements arrays and invert each of them
<p>Well, I have a numpy array like that:</p> <pre><code>a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24] </code></pre> <p>My desired output is:</p> <pre><code>b=['87654321','161514131211109','2423222120191817'] </code></pre> <hr /> <p>For it, I need first to split &quot;a&quot; into arrays of 8 elemen...
<p>No need for <code>numpy</code>, though it will work for an array as well. One way:</p> <pre><code>&gt;&gt;&gt; [''.join(str(c) for c in a[x:x+8][::-1]) for x in range(0, len(a), 8)] ['87654321', '161514131211109', '2423222120191817'] </code></pre>
python|arrays|numpy|split
3
11,502
66,874,561
Interpolate smaller histogram bins (Pandas / Plotly)
<p>I have a histogram of probability data, where the probabilities are bucketed in bins of size 10. When I display the histogram as a heatmap in plotly using buckets that are the same size as the data, I get this:</p> <p><a href="https://i.stack.imgur.com/u4QXl.png" rel="nofollow noreferrer"><img src="https://i.stack.i...
<p>I just found <a href="https://plotly.com/python/distplot/" rel="nofollow noreferrer">distplot</a>. I can probably use that to get a good idea of the fine-grained distribution. I'll post back with the results when I have them.</p>
python|pandas|plotly
0
11,503
68,248,798
Cannot interpret feed_dict key as Tensor: Tensor is not an element of this graph
<p>Tried to predict type of gen, but got some error, could you suggest what's wrong? any help will be appreciate. In other case to predict type of clothes in ZOLANDO dataset it's works. But in other case I was stuck :(</p> <pre><code>#some code of gen1, gen2 and merged dataFrames X_train, X_test, y_train, y_te...
<pre><code>graph = tf.Graph() with graph.as_default(): (your code of tf) </code></pre>
tensorflow
0
11,504
68,237,537
Most viewed product
<p>I am trying to find most viewed product as per user ID. If two products have been viewed for the same number of times then the most recent viewed product is to be selected.</p> <p>I have the following coding:</p> <pre><code>#tabulating most viewed product by an user in the last 15 days df_most_viewed_product= new_df...
<p>Systematically build it up as you describe</p> <ul> <li>get hits and last hit per <strong>UserID</strong> and <strong>ProductID</strong></li> <li>select rows from this aggregated data frame that match max <strong>hits</strong> and max <strong>last_hit</strong></li> </ul> <pre><code>import io import pandas as pd df =...
pandas|dataframe|time|group-by
0
11,505
68,092,709
Numpy restrict array to given indices
<p>Let's say I have an array J and another array O of indices that I would like to restrict J to. If J was [1, 0, 9, 1] and O was [0, 3], something would happen to give me [1, 1]. Is there any numpy function for this?</p>
<p>You can slice numpy array by selected indexes:</p> <pre><code>import numpy as np arr = np.array([1, 0, 9, 1]) arr = arr[[0, 3]] # &gt;&gt; array([1, 1]) </code></pre>
python|numpy
1
11,506
59,235,222
AttributeError: module 'tensorflow' has no attribute 'get_default_graph' in jupyter notebooks
<p>I am trying to run a cnn model for some classification but I am getting the following error:</p> <p><code>AttributeError: module 'tensorflow' has no attribute 'get_default_graph'</code></p> <p>These are the packages that I installed:</p> <pre><code>import numpy as np from keras.models import load_model import tim...
<p>There are multiple issues here:</p> <ol> <li>You are mixing imports between <code>tf.keras</code> and <code>keras</code>, this is not supported, pick one package and stick with it</li> <li>Keras 2.2.4 does not support TensorFlow 2.0, for this you need to either upgrade Keras to version 2.3.x, or downgrade TensorFlo...
python|tensorflow|keras
0
11,507
59,157,803
pandas dataframe group by a column and based on count update another column rows individually
<p>Input dataframe</p> <pre><code>data = { 'org_id' :[79,80,21,36,40,7,10,9,12,24], 'r_id' : [79,80,20,20,20,7,7,9,12,12], 'Type_id' : ['P','P','C','C','C','P','C','P','P','C'], 'grp_id': ['g54','g55','g13','g13','g13','g6','g6','g7','g8','g8'] } df2 = pd.DataFrame.from_dict(data) df2 Out[271]: org_id r...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.where.html" rel="nofollow noreferrer"><code>Series.where</code></a> with mask by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.duplicated.html" rel="nofollow noreferrer"><code>Series.duplicated</co...
pandas|dataframe|pandas-groupby
1
11,508
59,119,069
Recommened Image Size & Aspect Ratio
<p>What's the recommended image size (px) and aspect ratio when using tensorflow's object recognition API ? Also, does it make sense to convert images to grayscale beforehand ?</p>
<p>You need not convert the images to greyscale for tf object detection and the image size depends on the selected model, most of the SSD models have image size as 224 * 224. </p>
tensorflow|computer-vision|object-detection-api
0
11,509
45,921,995
How can I append features column wise and start a row for each sample
<p>I am trying to create a training data file which is structured as follows:</p> <p>[Rows = Samples, Columns = features]</p> <p>So if I have 100 samples and 2 features the shape of my np.array would be (100,2).</p> <p>The list bellow contains path-strings to the .nrrd 3D sample patch-data files.</p> <pre><code>['/...
<h1>Very simple solution</h1> <p>Instead of </p> <pre><code>f_median = np.median(data) training_file.append(f_median) f_sum = np.sum(data) training_file.append(f_sum) </code></pre> <p>you could do do</p> <pre><code>training_file.append((np.median(data), np.sum(data))) </code></pre> <h1>slightly longer solution</h...
python|numpy|scikit-learn
0
11,510
66,641,888
Python Sharepoint API Authentication Successful But Can't Read Excel File
<p>So basically the authentication to my sharepoint is successful, but then Pandas can't read the xlsx file (which is stored as a byte object).</p> <p>I get the error: &quot;ValueError: File is not a recognized excel file&quot;</p> <p>Code:</p> <pre><code>from office365.runtime.auth.authentication_context import Authen...
<p>Osugi's method above worked for me! For added clarity: I had to open the Excel file in the actual Excel application, not OneDrive. I did this by clicking File -&gt; info -&gt; Open in Desktop App.</p> <p>Once in the Excel application, I went File -&gt; info -&gt; Copy path. I pasted that path as my URL and it worked...
python|excel|pandas|sharepoint|sharepoint-api
0
11,511
66,416,394
Setting With Copy but I'm using .iloc and have no chain commands, why?
<p>So I am doing this super simple program and it's returning a set with copy warning. I'm using iloc.</p> <p>My goal is to check if the values in check if the value is a null and replace it with a tuple with 3 None values. It does work, but I'd like to avoid the copy warning.</p> <pre><code>df = pd.DataFrame({'a':[Non...
<p>You can use <code>at</code> instead of <code>iloc</code>, but note that <code>at</code> can only work on one cell at a time (<a href="https://stackoverflow.com/questions/37216485/pandas-at-versus-loc">see this question</a>).</p> <pre><code>if pd.isna(df['b'][0]): df.at[0,'b'] = (None, None, None) print(df) </cod...
pandas
1
11,512
66,652,196
How to print the data of the Tensors' formed in the data pipeline process ? (tf.data.Dataset.map -<class 'tensorflow.python.framework.ops.Tensor'> )
<p>I try to see the process of data pipeline with tensorflow2</p> <p>My code is working but I can't print some value in this pipeline steps. (especially inside of <code>.map(read_image)</code> )</p> <p>How can I print values inside read_image functions? (called with .map() method)</p> <pre><code>def read_image(image_pa...
<p><a href="https://www.tensorflow.org/api_docs/python/tf/print" rel="nofollow noreferrer">tf.print</a> prints both using this code.</p> <pre><code>import tensorflow as tf def read_image(image_paths,label_paths): tf.print(image_paths) img_raw = tf.io.read_file(image_paths) image = tf.image.decode_jpeg(img...
python-3.x|tensorflow|tensorflow2.0|tensorflow-datasets
0
11,513
57,667,392
How to count the number of variable in a column in dataframe
<p>dataframe <code>test_df</code> containing series <code>a b c d e</code> I need to count the number of each unique variable in a that has abc in e then divide that number by the sum of <code>b</code> and <code>c</code> and output new dataframe containing a d and g=sum of b and c</p> <p>`</p> <pre><code>test_df a b...
<pre><code>df['g'] = df['b']+df['c'] df.drop(['b','c', 'e'], axis=1,inplace = True) </code></pre>
python-3.x|pandas|dataframe|data-visualization
1
11,514
57,533,966
How to feed data properly in tensorflow
<p>I have been learning Tensorflow and understanding feed_dict has been a challenge. Take for example the following piece of code i am working on</p> <pre><code> p=0 self.sequence_length=25 with tf.Session() as sess: init.run() ...
<p>Usually the reason for that error is because your input array(x) isn’t the same size as your labels array(y). As the error states it looks like your labels array is empty. Before doing anything tensorflowy make sure both x and y arrays have values in them and that they are of the same size.</p> <p>To answer your qu...
dictionary|tensorflow|feed
0
11,515
70,655,431
Conditionally set data frame values based on logic
<p>I have a data frame that has price of an asset, a bunch of trigger prices and some price target parameters.</p> <pre><code>target_A = +2 target_B = -1 price trigger 2017-08-17 04:00:00 1 True 2017-08-17 04:01:00 2 None 2017-08-17 04:02:00 3 Non...
<p>I converted the sample data into a csv and was able to come up with this code for counting target_A and target_B hits.</p> <pre><code>df = pd.read_csv('price.csv', names=['date', 'price', 'trigger']) # cast &quot;None&quot; to NoneType df['trigger'].replace({'None': None}, inplace=True) # create columns with None a...
python|pandas|time-series|multiple-columns|back-testing
1
11,516
70,524,183
Python pandas dataseries slice with label vs index discrepancy
<pre><code>s2 = pd.Series([10,20,30,40,50,60], index=['a', 'b', 'c', 'd', 'e', 'f']) </code></pre> <p>When I select slice using the labels as below</p> <pre><code>print(s2['b':'e']) </code></pre> <p>output is</p> <pre><code>b 23 c 33 d 43 e 54 dtype: int64 </code></pre> <p>but when I select slice using inde...
<pre><code>s2['b':'e'] </code></pre> <p>this works similar to <code>df.loc[]</code></p> <p>here a slice object with labels 'a':'f' (Note that contrary to usual Python slices, both the start and the stop are included, when present in the index! See Slicing with labels and Endpoints are inclusive.)</p> <p>where as <code>...
python|pandas|indexing|slice
1
11,517
70,654,193
Panda datafram from excel
<p>Hi I'm working on a script, and I can't figure out how to accomplish -I have an excel file with student INFO -I wanna add that data to a PANDAS data frame -but I can't(or IDK how, yet) since I gotta make a code dynamic so it does it by itself regardless of how many student I have at that moment IDK if I explained my...
<p>Did you try using <code>pd.read_excel</code>?</p> <pre><code>import pandas as pd path = &quot;database.xlsx&quot; #location df = pd.read_excel(path) </code></pre>
python|excel|pandas|dataframe
1
11,518
71,011,179
dataframe not reading float values
<p>I have a dataframe that contains times in float format for example 12.0, 12.25, 12.75 with 27 columns. I have an if which checks if a user-given time is in the dataframe, but it only recognizes the 12.0 formatted time out of the dataframe. I am checking from the dataframe df4 in a specific column &quot;Timestamp&quo...
<p>You don't need to get the <code>values</code> of index that you want to select using <code>.loc[...]</code>. Just use <code>idx=df4[df4[&quot;Timestamp&quot;]==return_time].index</code></p>
pandas|dataframe
0
11,519
70,939,896
Matrix size-incompatible: In[0]: [47,1000], In[1]: [4096,256]
<p>I'm new to TensorFlow and am following a tutorial. I'm trying to do image captioning using VGG. I am getting an error that says:</p> <p><a href="https://i.stack.imgur.com/hTvDx.png" rel="nofollow noreferrer">enter image description here</a></p> <p>This is my code:</p> <pre class="lang-py prettyprint-override"><code>...
<ol> <li>solved after apply the below modification inputs1 --&gt; 1000 instead of 4096 se1 --&gt; 47 instead of 256 decoder2 --&gt; 47 instead of 256 fe2 --&gt; 47 instead of 256 se3 --&gt; 47 instead of 256</li> <li>or just update inputs1 to 1000 i think it will solve the issue</li> </ol>
python|tensorflow|keras|conv-neural-network|vgg-net
0
11,520
51,807,348
How to insert a data in mysql as previous and next record
<p>How to write SQL in Mysql or Python? I was trying to load on the basis of row_number and how do i bring next value into current row Can you throw some lights on this? Input</p> <pre><code>symbol,timestamp,close,open,status,row_number ABCLTD,2015-01-16,43.25,33.81,Bullish,1 ABCLTD,2015-02-28,29.891,34.22,Bearish,2 ...
<p>The row number depends on how the data is retrieved. Row 1 ordered by date ascending is different to row 1 ordered by descending. </p> <p>You need to forget row number. If you want a new record between row 1 and 2 just make sure the value you insert is between the values in the column you order by.</p>
python|mysql|pandas
0
11,521
51,688,576
How do I subtract two pandas datetime series DataFrames from each other when the index is a datetime?
<p>I am trying to subtract the values of two pandas datetime series DataFrames from each other in which the index for both DataFrames is a datetime value.</p> <p>The two DataFrames in question have the same amount of columns. I want to subtract the value in the column in the second DataFrame from the value in the of t...
<p>Using <code>sub</code> between two dataframes will work if columns have the same name so here for example, create the dataframe <code>test</code> by:</p> <pre><code>test = pd.DataFrame(est.predict(X),columns=['price']) </code></pre>
python|pandas|datetime|dataframe|machine-learning
2
11,522
36,076,241
Why when I try to execute 2 conditions in 1 function it give me just black raster?
<p>Why when I try exercise 1 condition in 1 function it works, but when I try to add next - it give just black raster?</p> <p>instead of average > 0.05*99 - I try to make: (average > 0.05*99)&amp;(average &lt; 0.20*99) (It is condition: more than 5% but less than 20% ).</p> <p>May be something wrong with Python ru...
<p>In Python <code>&amp;</code> is the bitwise <code>and</code> operator while logical <code>and</code> is simply <code>and</code>. Change your line from</p> <pre><code>if (average &gt; 0.05*99)&amp;(average &lt; 0.20*99): </code></pre> <p>to:</p> <pre><code>if average &gt; 0.05 * 99 and average &lt; 0.20 * 99: </c...
python|numpy|raster
3
11,523
36,021,385
Connecting from Python to SQL Server
<p>I'd like to connect from IPython notebook to a SQL-Server database via integrated security. </p> <p>Is this possible? I'm guessing yes it is.</p> <p>How do I format the connection string in the following?</p> <pre><code>import pandas as pd import pandas.io.sql as psql sql = "SELECT * FROM WHdb.dbo.vw_smallTable" ...
<p>You need to install the package, pypyodbc</p> <pre><code>!pip install pypyodbc </code></pre> <p>Then, you can import it as follows:</p> <pre><code>import pypyodbc as podbc </code></pre> <p>You can now create the connection:</p> <pre><code>conn = podbc.connect("Driver={SQL Server};Server=&lt;YourServer&gt;;Datab...
sql-server|python-3.x|pandas|ipython|jupyter-notebook
10
11,524
36,041,410
python, pandas, csv import and more
<p>I have seen many questions in regards to importing multiple csv files into a pandas dataframe. My question is how can you import multiple csv files but ignore the last csv file in your directory? I have had a hard time finding the answer to this.</p> <p>Also, lets assume that the csv file names are all different w...
<p>Try this:</p> <pre><code>import os import glob import pandas as pd def get_merged_csv(flist, **kwargs): return pd.concat([pd.read_csv(f, **kwargs) for f in flist], ignore_index=True) path =r'C:\DRO\DCL_rawdata_files' # use your path fmask = os.path.join(path, '*.csv') allFiles = sorted(glob.glob(fmask), key=o...
python|csv|pandas|import
1
11,525
42,023,438
Python Pandas - Can Dataframe have multiple indexes?
<p>I have a dataset in CSV which I read with:</p> <pre><code>df = pd.read_csv(requestfile, header=[0,1], parse_dates= [0]) </code></pre> <p>The following Dataframe is in following format [0..8759]:</p> <pre><code> time output direct diffuse temperature UTC kW kW/m2 kW/m2 ...
<p>Ok, I found the error and the original question was bad:</p> <p>Solution:</p> <pre><code>df = pd.read_csv(requestfile, index_col=[0], parse_dates=[0], skiprows=[1]) </code></pre> <p>Headers were left out, and I added the read_csv to skip the row containing units in 'str'. So the problem was one of the functions u...
python|csv|pandas|indexing|dataframe
0
11,526
42,093,632
Semantic Segmentation with Encoder-Decoder CNNs
<p>Appologizes for misuse of technical terms. I am working on a project of semantic segmentation via CNNs ; trying to implement an architecture of type Encoder-Decoder, therefore output is the same size as the input.</p> <p>How do you design the labels ? What loss function should one apply ? Especially in the situati...
<p>I suggest starting with a base architecture used in practice like this one in nerve-segmentation: <a href="https://github.com/EdwardTyantov/ultrasound-nerve-segmentation" rel="nofollow noreferrer">https://github.com/EdwardTyantov/ultrasound-nerve-segmentation</a>. Here a dice_loss is used as a loss function. This wo...
tensorflow|deep-learning|keras
1
11,527
41,833,568
place the mydata_array into the random location of Big_array of zeros
<p>mydata is an numpy array of shape(10,100,100) of the form(z,y,x). And i have created the empty array of shape(10,800,800). Now i need to place the mydata_array into some random locations of empty_array such that if I would plot the output, it should look like mydata is placed randomly in the ouput plot of array(10,8...
<p>Here's a demonstration of placing several copies of one array inside another, using slice indexing:</p> <pre><code>In [802]: out = np.zeros((10,10),int) In [803]: src = np.arange(6).reshape(2,3) In [804]: out Out[804]: array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ... ...
python|numpy|scipy
1
11,528
37,890,394
Tensorflow GradientDescentOptimizer - how does it connect to tf.Variables?
<p><a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/train.html#GradientDescentOptimizer" rel="nofollow">Documentation</a></p> <p>I'm just curious how you tell it to minimize which variables. For example in this linear regression code, TF does fine optimizing weights/bias without being told the names o...
<p>It takes them from <code>tf.trainable_variables()</code> which includes all variables created with <code>trainable=True</code> flag (the default)</p>
python|tensorflow
7
11,529
31,547,461
Is there a way to automate the presentation of pandas Dataframes in an attractive manner
<p>An important component of my job is presenting data tables in an attractive manner. I do a lot of work in Pandas and usually have to export to Excel and work on the presentation in there. Does anyone know of any way to present Pandas Data frames in attractive looking tables? </p>
<p>I like the approach that @<a href="https://stackoverflow.com/users/85360/brandon-rhodes">Brandon Rhodes</a> takes in his excellent <a href="https://github.com/brandon-rhodes/pycon-pandas-tutorial" rel="nofollow noreferrer">pandas tutorial</a>. He uses the IPython Notebook, and at the beginning of his notebooks, he a...
python|pandas|dataframe|data-visualization
2
11,530
64,533,664
Speed up list comprehension, alternative?
<p>In my class i'm using a list comprehension which takes way too much time.</p> <pre><code>class Crack: def __init__(self, filename): self._mesh = pyfrd.Mesh(filename) self._filename = filename self._node_sets = self._mesh.node_sets[1:] # list of front names self._calc...
<p>A list comprehension is likely to allocate and re-allocate multiple times, as the list is built up. Since you know the length of the final list beforehand (<code>len(self._node_sets)</code>), this could be one area of improvement. So, you could try having a <code>numpy</code> array of <code>numpy</code> arrays in th...
python|performance|numpy|for-loop|list-comprehension
0
11,531
64,212,319
Issue with numpy all() and any()
<p>I like to check if an array contains any negative or zero element.</p> <p>To do this, I tried using <code>numpy.any</code> or <code>numpy.all</code>, but when I ran the following code:</p> <pre><code>import numpy as np arr = np.array([0,1,-1,-2,3,5]) print(arr) if np.any(arr) &lt;= 0: print('negative or zero ele...
<pre><code>if np.any(test_array) &lt;= 0: </code></pre> <p>You are currently comparing if the return value of <code>any()</code> is less than or equal to zero. Instead, you need to compare with each element of the array:</p> <pre><code>if np.any(test_array &lt;= 0): </code></pre>
python|numpy
1
11,532
64,313,526
ModuleNotFoundError: No module named 'tensorflow' on flask run
<p>I already installed tensorflow,</p> <pre><code>Python 3.7.7 (default, Apr 15 2020, 05:09:04) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32 Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; import tensorflow 2020-10-12 14:37:43.718059:...
<p>So basically, in my current environment it's not installed flask yet, but I do can serve a server using flask too without tensorflow it worked. maybe anaconda just bugged and using base environment installed flask to run that server.</p> <p>after I installed flask on my current environment it worked good. so basical...
python|tensorflow|flask
0
11,533
47,909,081
TensorFlow Object detection API. How can I get precision and recall after I trained the model
<p>I have trained Faster_rcnn_Inception model and other models using my own dataset locally. But I can only get images with bounding boxes. I want to get precision and recall to compare models. I see 'compute_precision_recall' in metrics.py but i don't know how to use it. My dataset has only one class.</p>
<p>These are the following things I did to do calculate the Precision and Recall metrics </p> <ol> <li>Run the <code>inference_detections.py</code> script(usage is mentioned in the file) in the <code>object_detection/inference</code> directory. A detection record file will be generated using this command in the outp...
tensorflow|object-detection-api
-1
11,534
47,722,292
Python Keras Tensorflow Embedding Layer Indices[i,j] = k is not in [0,max_features]
<p>I am trying to do Author Identification, my <code>train_vecs_w2v.shape = (15663, 400)</code>. <code>y_train.shape = (15663,3)</code> which has 3 label one hot encoded. Now the problem is I am having an error in the Embedding layer. Indices[0,X] = -1 is not in [0, 15663). How to solve this? Is it my code or Keras/Ten...
<p>I think the problem here is with the word vectors count.<br> It should be</p> <pre><code>len(train_vecs_w2v) + 1 </code></pre>
python|tensorflow|keras|convolution|multiclass-classification
1
11,535
47,858,996
Properly convert png to npy numpy array (Image to Array)
<p>When I generate an image and then generate a numpy array from it, the original <code>.npy</code> file differs from the new one. I thought <code>new-array.npy</code> would be exactly the same as <code>original-array.npy</code> since they are coming from the same image.</p> <p>For an example, I used this little image ...
<p>The files are different because the arrays have different data types.</p> <p>The first time you save the data is when you save the array CXY. This array has a type of <code>np.float64</code>, since that is the default data type returned by <code>np.zeros</code>.</p> <p>The second array is created by loading the or...
python|arrays|python-2.7|numpy|image-processing
1
11,536
48,974,747
numpy function cythonization
<p>I have the following function in pure python:</p> <pre><code>import numpy as np def subtractPython(a, b): xAxisCount = a.shape[0] yAxisCount = a.shape[1] shape = (xAxisCount, yAxisCount, xAxisCount) results = np.zeros(shape) for index in range(len(b)): subtracted = (a - b[index]) ...
<p>When trying to optimize a function, one always should know what is the bottle-neck of this function - without you will spend a lot of time running in the wrong direction.</p> <p>Let's use your python-function as baseline (actually I use <code>result=np.zeros(shape,dtype=a.dtype)</code> otherwise your method returns...
python|numpy|cython
4
11,537
58,960,019
removing spaces from integer column in python
<p>I am using a number column in my dataframe for a simple lookup, however one of the record has spaces and it botched the lookup. Below is just a sample column from the actual file.</p> <pre class="lang-none prettyprint-override"><code>Column 90043 216977   98207 </code></pre> <p>record two <code>216977</code> is t...
<p>If one of the fields has a space, chances are it's a number stored as a string. You can try to cast the type as int. </p> <pre><code>df = pd.DataFrame([[1],['2 '],[3]], columns=['Messy Data']) df Messy Data 0 1 1 2 2 3 </code></pre> <p>Now use apply &amp; lambda to cast everything to...
python|pandas|dataframe
1
11,538
70,024,227
Convert list of nested dictionary into Pandas Dataframe
<p>I need to convert a list of nested dictionary into Pandas Dataframe. My list is the following:</p> <pre><code>data = [{&quot;2016-09-24&quot;:{&quot;totalRevenue&quot;:123, &quot;netIncome&quot;:456, &quot;ebit&quot;:789}}, {&quot;2015-09-24&quot;:{&quot;totalRevenue&quot;:789, &quot;netIncome&quot;:456, &quot;ebit&...
<p>Thanks for the notice on how to write questions @HarryPlotter and thanks for the suggested solution @Geoffrey.<br /> I found an answer to my problem:</p> <pre><code>pd.concat([pd.DataFrame(l) for l in my_list],axis=1) </code></pre>
python|pandas|dataframe
0
11,539
56,226,667
Execute update with dictionary/dataframe values in SQLAlchemy
<p>I'm trying to update <code>user_id</code> and <code>date_synced</code> in my user_table. I'm using MySQL. My table is as follows: <code>User(user_id, mail, active, activity_level, date_synced)</code>.These values come from my DataFrameUsers:</p> <pre><code>user_id date_synced 1 2019-05-20 20:48:04 8 2019-05-20 ...
<p>You have a wrong format of parameters. <code>sqlalchemy</code> doesn't now how to search row and what update. Correct format:</p> <pre><code>[ {'user_id': 1, 'date_synced': '2019-05-20 20:48:04'}, {'user_id': 8, 'date_synced': '2019-05-20 20:48:04'} ] </code></pre> <p>So you need just to convert <code>dict...
python|pandas|sqlalchemy
2
11,540
56,267,110
Categorical variables usage in pandas for ANOVA and regression?
<p>To prepare a little toy example:</p> <pre><code>import pandas as pd import numpy as np high, size = 100, 20 df = pd.DataFrame({'perception': np.random.randint(0, high, size), 'age': np.random.randint(0, high, size), 'outlook': pd.Categorical(np.tile(['positive', 'neutral', 'ne...
<p>Finding out likelihood of <code>outcome</code> given columns and Feature importance (1 and 2)</p> <p><strong>Categorical data</strong></p> <p>As the dataset contains categorical values, we can use the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html" rel="nofollow ...
pandas|numpy|scipy|anova|hypothesis-test
5
11,541
64,877,001
Quantile Regression with Tensorflow Probability
<p>I am trying to give tensorflow probability a try. I have a simple quantile regression in R. I would like to get the same results from tensorflow probability.</p> <h3>R Quantile Regression</h3> <pre class="lang-r prettyprint-override"><code>library(&quot;quantreg&quot;) mtcars_url &lt;- &quot;https://gist.githubuserc...
<p>Try to adjust the learning rate and see if the model converges correctly. Also, with the reshape function in your code, you probably intended to do a transpose. With a learning rate of 1.0 and some code fixes, this is what I got:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; n = 1000 &gt;&gt;&gt; ...
python|r|tensorflow2.0|tensorflow-probability|quantile-regression
2
11,542
64,865,527
Pandas PivotTable
<p>I have a Pandas dataframe with the following columns:</p> <pre><code>SecId Date Sector Country 184149 2019-12-31 Utility USA 184150 2019-12-31 Banking USA 187194 2019-12-31 Aerospace FRA ............... 128502 2020-02-12 CommSvcs UK ............... </code></pre> <p>SecId ...
<p>You can use <code>get_dummies</code>. You can cast as a categorical dtype beforehand to define what columns will be created.</p> <p>code:</p> <pre><code>SECTORS = df.Sector.unique() df[&quot;Sector&quot;] = df.Sector.astype(pd.Categorical(SECTORS)) COUNTRIES = df.Country.unique() df[&quot;Country&quot;] = df.Count...
python|pandas|pivot-table|multi-index
2
11,543
65,004,162
Break consecutive for loops after n iterations
<p>I have the following code, it works so far, but after it reaches the 6th iteration it jumps from loop <code>for i in range(1,6):</code> to the loop <code>for filename in files:</code> and enter the loop <code>for i in range(1,6):</code> again. So it's doing a calculation again. This repeats in general 3 times and af...
<pre class="lang-py prettyprint-override"><code>for root, dirs, files in os.walk('/Users/path....'): for i, filename in enumerate(files, 1): # Calculation print(results) if i == 6: break </code></pre> <p>But I’m not really sure what you try to accomplish.</p> <p>Could you be more...
python|pandas|for-loop
2
11,544
64,849,974
Initialize high dimensional sparse matrix
<p>I want to initialize <code>300,000 x 300,0000</code> sparse matrix using <code>sklearn</code>, but it requires memory as if it was not sparse:</p> <pre><code>&gt;&gt;&gt; from scipy import sparse &gt;&gt;&gt; sparse.rand(300000,300000,.1) </code></pre> <p>it gives the error:</p> <pre><code>MemoryError: Unable to ...
<p>Try passing a reasonable <code>density</code> argument as seen in the docs... if you have like 10 trillion cells maybe like 0.00000001 or something...</p> <p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.rand.html#scipy.sparse.rand" rel="nofollow noreferrer">https://docs.scipy.org/doc/sc...
python|numpy|scipy|sparse-matrix
1
11,545
39,900,208
How to get unique rows and their occurrences for 2D array?
<p>I have a 2D array, and it has some duplicate columns. I would like to be able to see which unique columns there are, and where the duplicates are.</p> <p>My own array is too large to put here, but here is an example:</p> <pre><code>a = np.array([[ 1., 0., 0., 0., 0.],[ 2., 0., 4., 3., 0.],]) </code></pre> ...
<p>Here's a vectorized approach to give us a list of arrays as output -</p> <pre><code>ids = np.ravel_multi_index(a.astype(int),a.max(1).astype(int)+1) sidx = ids.argsort() sorted_ids = ids[sidx] out = np.split(sidx,np.nonzero(sorted_ids[1:] &gt; sorted_ids[:-1])[0]+1) </code></pre> <p>Sample run -</p> <pre><code>In...
python|arrays|numpy|unique
0
11,546
40,132,352
python filter 2d array by a chunk of data
<pre><code>import numpy as np data = np.array([ [20, 0, 5, 1], [20, 0, 5, 1], [20, 0, 5, 0], [20, 1, 5, 0], [20, 1, 5, 0], [20, 2, 5, 1], [20, 3, 5, 0], [20, 3, 5, 0], [20, 3, 5, 1], [20, 4, 5, 0], [20, 4, 5, 0], [20, 4, 5, 0] ]) </cod...
<p><strong>Generic approach :</strong> Here's an approach using <a href="https://numeric.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow"><code>np.unique</code></a> and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow"><code>np.bincount</code></a>...
python|arrays|numpy
3
11,547
39,480,314
tensorflow InvalidArgumentError: You must feed a value for placeholder tensor with dtype float
<p>I am new to tensorflow and want to train a logistic model for classification.</p> <pre><code># Set model weights W = tf.Variable(tf.zeros([30, 16])) b = tf.Variable(tf.zeros([16])) train_X, train_Y, X, Y = input('train.csv') #construct model pred = model(X, W, b) # Minimize error using cross entropy cost = tf.redu...
<p>From your error message, the name of the missing placeholder&mdash;<code>'Placeholder_54'</code>&mdash;is suspicious, because that suggests that at least 54 placeholders have been created in the current interpreter session. </p> <p>There aren't enough details to say for sure, but I have some suspicions. Are you ru...
python|types|tensorflow
3
11,548
39,857,949
Applying a function to a DataFrame column returns NoneType
<p>I have a DataFrame with source IP addresses and I want to check if they belong to a documented CIDR range. </p> <pre><code>netflow_df2["sip"].head(10) timestamp 2016-10-04 16:24:58 40.101.X.X 2016-10-04 16:24:58 40.101.X.X 2016-10-04 16:24:58 40.101.X.X 2016-10-04 16:24:58 67.X.X.X 2016-10-04 16:24:5...
<p>The problem is that I use the <code>defaultdict</code> in the <code>netmap</code> function wrong. This yields the corrects results:</p> <pre><code>def netmap(ip, network_lookup_dict): for key, value in network_lookup_dict.iteritems(): try: if ipaddress.ip_address(unicode(ip)) in ipaddress.i...
python|pandas|networking
0
11,549
44,300,396
how to calculate the ratio from series in pandas after groupby?
<p>I have a series like this: the first column is user_id and the second column is a flag to represent how many times in reordered=0/1. Some users have no reordered, for example , the user 21. I want to get a new columns ratio, which is from times(0)/times(1&amp;0). for example, for user 1, the ratio is 1 / (1+10). How...
<pre><code>(dff.xs(0, level='reordered') / dff.groupby(level='user_id').sum()).rename('ratio') user_id 1 0.090909 15 0.200000 19 0.333333 21 1.000000 31 0.500000 43 0.500000 52 0.071429 67 0.050000 81 0.500000 82 0.111111 98 0.142857 109 1.000000 120 0.500000 185 1...
pandas
4
11,550
44,056,833
matplotlib.scatter color argument not accepting numpy array
<p>I have written the following python plotting script using matplotlib:</p> <pre><code>import pynbody as pyn import numpy as np import matplotlib.pyplot as plt import glob s = pyn.load('./ballsV2.00001') sl = s.g[np.where((s.g['z'] &lt; 0.005) &amp; (s.g['z']&gt;-0.005))] sx = s.s['x'][0] sy = s.s['y'][0] sz = s.s[...
<p><code>Flux</code> and <code>np.log10(sl['radFlux'])</code> ended up being different lengths. <code>sl</code> (a slice of <code>s</code>) was not used to compute <code>r2</code>, so <code>Flux</code> ended up being to big. It would be nice if matplotlib checked that the color array was the same length as the scatter...
python|arrays|numpy|matplotlib|scatter-plot
4
11,551
69,597,350
Pytorch summary : number of parameters
<p>I am experimenting with various deep networks and I always want to know how may parameters are involved. I was using pytorch summary however I noticed that if I use many times the same module in the forward pass, its associated parameters are counted multiple times.</p> <p>An example is this:</p> <pre><code>class Ne...
<p>From the <a href="https://discuss.pytorch.org/t/repeated-model-layers-real-or-torchsummary-bug/26489/2" rel="nofollow noreferrer">discussion here</a>, it seems that <a href="https://github.com/sksq96/pytorch-summary" rel="nofollow noreferrer">torchsummary</a> (in its current form) is not created with all possible mo...
deep-learning|pytorch
0
11,552
69,438,131
pandas conditionally include values in aggregation operation
<p>for a dataframe of:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'trigger':[0,0,0, 1,1,1, 2,2,2, 3,3,3,], 'score' :[1,0,0, 0,1,0 ,0,0,1 ,1,1,1], 'label' :[1,0,0, 0,1,0 ,0,0,1 ,1,1,1] }) # in reality ranked using some other column df['rank'] = df.groupby(['trigger']).cumcount() display(df) ...
<p>One option is <code>merge</code>:</p> <pre><code>d_eval = (df[df['rank'] &lt;=2].groupby(['trigger']) .agg({'score':'max', 'label':'max'}) ) df.merge(d_eval, on='trigger', suffixes=['','_max']) </code></pre> <p>Output:</p> <pre><code> trigger score label rank score_max label_max 0 ...
python|pandas|conditional-statements
1
11,553
69,331,929
Is this a safe way to set values in a DataFrame? Why does this work?
<p>I'm using <code>.loc</code> to filter my DataFrame and set values from another column. Here's a short example, first setting up a simple DataFrame:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({ 'name': ['Steve', 'Julie', 'Dan', 'Mary'], 'nickname': ['Steve-o', 'Jules', '', ''] }) #...
<p>It's because Pandas sets the values by the corresponding index. The index of the <code>name</code> is <code>0</code> <code>1</code> <code>2</code> <code>3</code>, but the located rows (<code>loc</code>) indexes are <code>2</code> and <code>3</code>, so it would reindex the original <code>name</code> column to only t...
python|pandas|dataframe|numpy
2
11,554
69,391,197
How to solve the dimension error and effectively use Conv2dTranspose?
<p>i have created a discriminator and generator file to implement GAN, however, i am facing this error.</p> <p>The initial error i was facing was in the main.py file where i am calling the criterion library and passing the output and label. I solved that error using squeeze function, so that the issue of shape was reso...
<p>You have a &quot;gap&quot; between layer <code>t6</code> and <code>t7</code> of your <code>generatorG</code>:</p> <pre class="lang-py prettyprint-override"><code> # ... self.t6 = nn.Sequential( nn.Conv2d(in_channels=512, out_channels=4000, kernel_size=(4, 4)), nn.BatchNorm2d(40...
machine-learning|neural-network|pytorch|conv-neural-network|generative-adversarial-network
0
11,555
53,811,351
Cleaning data frames with rogue elements using split()
<p>Given the following data in an excel sheet (taken in as a dataframe) :</p> <pre><code> Name Number Date AA '9988779911' '01-JAN-18' 'BB' '8779912044' '01-FEB-18' </code></pre> <p>I have used the following code to clean the dataframe and remove the unnecessary apostrophes;</p> <pre><code>for ...
<p>try this,</p> <pre><code>for name in list(df): df[name] = df[name].str.replace("\'","") </code></pre> <p>Replace <code>'</code> with <code>empty</code> character.</p>
python|pandas|split|data-analysis|attributeerror
0
11,556
38,310,204
Data Transformation in Python
<p>I have the following DataFrame:</p> <pre><code>ID MONTHLY_QTY H1 M1 H1 M2 H1 M3 H1 M4 H2 M1 H2 M4 </code></pre> <p>I need to transform it to something like this:</p> <pre><code>ID col1 col2 col3 col4 H1 M1 M2 M3 M4 H2 M1 M2 </code></pre> <p>The number of distinct valu...
<p>Starting with this <code>df</code>:</p> <pre><code> ID MONTHLY_QTY 0 H1 M1 1 H1 M2 2 H1 M3 3 H1 M4 4 H2 M1 5 H2 M4 dummies = pd.get_dummies(df["MONTHLY_QTY"]) df2 = df.join(dummies) df2.groupby(['ID' ] )['M1','M2', "M3", "M4" ].sum() M1 M2 ...
python|pandas
1
11,557
38,221,584
Pandas: Select balanced sample
<p>I have a data frame with 3000 companies covering five years.</p> <pre><code>Id Company Year Value 0 1111111 2016 NaN 1 1111111 2015 3871.0 2 3333333 2016 3989.0 3 3333333 2015 3648.0 4 4444444 2016 5...
<p>groupby.count() returns the number of non-null values so if you groupby companies, the count should be equal to the number of years. Assuming no duplicates, you can do this:</p> <pre><code>df.ix[df.groupby('Company')['Value'].transform('count') &gt; 1, :] Out[259]: Id Company Year Value 2 2 3333333 2016...
python|python-2.7|pandas
1
11,558
38,394,265
Buying ram to avoid chunking for 30-50Gb plus files
<p>I use pandas to read very large csv files, which also are gzipped. I unzip into csv files which are approx 30-50GB. I chunk the files and process/manipulate them. Finally add the relevant data to HDF5 files which I compress </p> <p>It works fine but is slow since I have to deal with one file per day and have severa...
<p>I think you have quite a few things which can be optimized:</p> <ul> <li><p>first of all read only those columns that you really need instead of reading and then dropping them - use <code>usecols=list_of_needed_columns</code> parameter</p></li> <li><p>increase your chunksize - try it with different values - i would...
python|csv|pandas|ram|chunking
1
11,559
65,942,903
TextFileReader arguments in Pandas
<p>In pandas IO functions, like read_csv, read_fwf, the documentation says that the optional keyword arguments are passed to TextFileReader.</p> <pre><code>**kwds : optional Optional keyword arguments can be passed to TextFileReader. </code></pre> <p>And then, nothing in the documentation says what the valid argum...
<blockquote> <p>the documentation says that the optional keyword arguments are passed to TextFileReader.</p> </blockquote> <p>Well technically when you call <a href="https://github.com/pandas-dev/pandas/blob/5d65e0a3092f3c30169d0c0a3d0227e985104a56/pandas/io/parsers/readers.py#L438" rel="nofollow noreferrer">pandas.io....
python|pandas
1
11,560
66,163,453
Pandas: groupby and shift not doing quite what I need
<p>Here is a small dataset:</p> <pre><code>df = pd.DataFrame({'KEY' : [100, 100, 100, 100, 100, 100, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 102, 102], 'RPTDATE' : ['2002-10-23', '2002-10-23', '2002-10-30', '2002-10-30', '2002-11-6', '2002-11-6', \ ...
<p>Start with your original <code>df</code> as provided and doing the same first step. Then create a dataframe of unique &quot;KEY, RPTDATE, STDEPTH, ENDDEPTH&quot; values where STDEPTH is not 0 and use that to fill values where STDEPTH is 0:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np # nee...
python|pandas
1
11,561
66,000,735
< SyntaxError: invalid syntax
<p>I am playing around with the below code and do not know why it is giving me this syntax error:</p> <p><a href="https://i.stack.imgur.com/uRf2K.png" rel="nofollow noreferrer">enter image description here</a></p> <pre><code>def isSupport(df,i): support = df['Low'][i] &lt; df['Low'][i-1] and df['Low'][i] &lt; ...
<p>You can use parentheses to also align multiline statements:</p> <pre class="lang-py prettyprint-override"><code>support = (df['Low'][i] &lt; df['Low'][i - 1] and df['Low'][i] &lt; df['Low'][i + 1] and df['Low'][i + 1] &lt; df['Low'][i + 2] and df['Low'][i - 1] &lt; df['Low'][i - 2]) ...
python|pandas|matplotlib
3
11,562
52,727,247
1 Milllion Integers GroupBy - Occurrence
<p>I created 1million random integers between 1 and 100 &amp; wrote the results to a text file. </p> <pre><code>Results_File = open('RandomResults.txt','w') for i in range(1000000): x = random.randint(1,100) Results_File.write(str(x) + "," + '\n') </code></pre> <p>Okay that works. But I wanted to find the ...
<p>Hope it helps. The <code>value_counts()</code> function of pandas does that.</p> <pre><code>df['A'].value_counts() </code></pre>
python|pandas|random|pandas-groupby
1
11,563
58,311,112
Python code breaks when attemting to download larger zipped csv file, works fine on smaller file
<p>while working with small zipfiles(about 8MB) containg 25MB of CSV files the below code works exactly as it should. As soon as I attempt to download larger files (45MB zip file containing a 180MB csv) the code breaks and I get the following error message:</p> <pre><code>(venv) ufulu@ufulu awr % python get_awr_rankin...
<p>The problem seems to be the split call on a float and not necessarily the download. Try changing line 79</p> <p>from</p> <pre class="lang-py prettyprint-override"><code>domain.append(row.split("//")[-1].split("/")[0].split('?')[0]) </code></pre> <p>to </p> <pre class="lang-py prettyprint-override"><code>domain.a...
python|pandas|csv|python-requests|unzip
0
11,564
58,343,208
python pandas, transform data set, move rows into columns
<p>There is a csv data frame which contains attributes and their values in an hourly interval. Not all attributes are listed each hour. It looks like this:</p> <pre><code>time attribute value 2019.10.11. 10:00:00 A 10 2019.10.11. 10:00:00 B 20 2019.10.11. 10:00:00 C ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer">DataFrame.pivot_table</a>:</p> <pre><code>df=df.pivot_table(columns='attribute',index='time' ,values ='value',fill_value=0) print(df) </code></pre> <hr> <pre><code>attribute ...
python|pandas|join|merge|concatenation
2
11,565
58,507,886
Convert list into dataframe
<p>I've this list, </p> <pre><code>grid = [['r', 0.01529051987767584, 0.001, -1], ['r', 0.9357798165137615, 0.03162277660168379, 39], ['r', 0.9480122324159022, 1.0, 79], ['r', 0.8899082568807339, 1000.0, 9], ['c', 0.9327217125382263, 0.001, 49], ['c', 0.9724770642201835, 0.03162277660168379, 89], ['c', 0.9724770...
<p>You can make a dataframe using a list of lists directly by calling <code>pd.DataFrame(data=a_list)</code>. You can give column names with the <code>columns</code> keyword, provided that the column names are equal to the number of elements in the sublist.</p> <p>Just use:</p> <pre><code>df = pd.DataFrame(grid, colu...
python|pandas|numpy
1
11,566
69,120,086
Pandas removing parts from string
<p>I've got a Dataframe containing strings like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A header</th> <th>Another header</th> </tr> </thead> <tbody> <tr> <td>First</td> <td>row</td> </tr> <tr> <td>Second</td> <td>row</td> </tr> <tr> <td>[First] nenen</td> <td>row</td> </tr> <tr...
<pre><code>&gt;&gt;&gt; df a header another header 0 first row 1 [First] second row &gt;&gt;&gt; df[&quot;a header&quot;]=df[&quot;a header&quot;].str.replace(r'\[.*?\]\ *','') &gt;&gt;&gt; df a header another header 0 first row 1 second row </code>...
python|pandas|string
0
11,567
69,188,573
How to handle missing data in pandas dataframe?
<p>I have a pandas dataframe containing the following information:</p> <ul> <li>For each Timestamp, there are a number of Trays (between 1-4) out of 8 available Trays. (So there is a maximum number of 4 Trays per Timestamp.)</li> <li>Each Tray consists of 4 positions.</li> </ul> <p>A dataframe could look like this:</p>...
<p><a href="https://pyjanitor-devs.github.io/pyjanitor/" rel="nofollow noreferrer">pyjanitor</a> has a <a href="https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.complete.html#janitor.complete" rel="nofollow noreferrer">complete</a> function that exposes explicitly missing values (<a href="...
python|pandas|dataframe
1
11,568
68,961,417
ValueError while iterating over dataframe: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
<p>I have a dataframe in which I am trying to convert the values in &quot;LoginTime&quot; to a 24HR format based on whether the &quot;Timing&quot; contains &quot;am&quot; or &quot;pm&quot;.</p> <pre><code>data = &quot;&quot;&quot; LoginDate LoginTime Timing StudentId 2021-03-23 12 am 3574 2021-03-23 12...
<p>You could try this :</p> <pre><code>df[&quot;LoginTime&quot;] = np.where(df[&quot;Timing&quot;] == &quot;pm&quot;, df[&quot;LoginTime&quot;] + 12, df[&quot;LoginTime&quot;]) </code></pre>
python|pandas|dataframe|jupyter-notebook
0
11,569
44,642,862
Merge two lists in to one list and discard the duplicates. Pandas Python
<p>Want to merge two lists and discard the intersecting elements</p> <pre><code>A = ['a', 'b', 'c', 'd'] B = ['a', 'b', 'd', 'e', 'f'] </code></pre> <p>Expected result: </p> <pre><code>['c', 'e', 'f'] </code></pre> <p>I can get this by: </p> <pre><code>[i for i in A if i not in B] + [i for i in B if i not in A] <...
<p>Use sets:</p> <pre><code>set(A).symmetric_difference(B) </code></pre> <p>or equivalent:</p> <pre><code>set(A)^set(B) </code></pre> <p>(You can convert back to <code>list</code> if needs to be...)</p>
python|pandas|merge|unique|concat
1
11,570
61,021,287
Tf 2: Could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR
<p>I am getting the above error (Could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR) when I execute the code below. I have cheked if my gpu is woking using tf.test.is_gpu_available</p> <pre><code># coding: utf-8 import tensorflow as tf import numpy as np import keras from models import * import os import gc ...
<p>There is an <a href="https://stackoverflow.com/a/58684421/1295595">answer on a question about TF1.0</a> which addresses how to do this for TF2. The suggestion from that answer worked for me, so I'll copy it in here. TF2 seems to be moving away from <code>tf.Session</code>, so I tend to prefer this suggestion to the ...
tensorflow|keras|tensorflow2.0
1
11,571
61,093,438
Model is not been training when tf.Session() is used
<p>I am new to TensorFlow and Keras. I am trying to understand GANs using TF 1.x (using this repo <a href="https://github.com/hse-aml" rel="nofollow noreferrer">https://github.com/hse-aml</a>) and I have trouble with the below function which has been used to create a session. My problem is what exactly this function is...
<p>Documentation <a href="https://www.tensorflow.org/api_docs/python/tf/compat/v1/InteractiveSession" rel="nofollow noreferrer">here</a> </p> <p>The only difference between <code>Session</code> and an <code>InteractiveSession</code> is that <code>InteractiveSession</code> makes itself the default session so that you c...
tensorflow|keras|tf.keras|generative-adversarial-network
0
11,572
60,880,636
Pandas: str extract text every thing except the last part of the string
<p>I have a dataframe with a column known as "msg".</p> <p>In the "msg" column, all rows goes somesthing like below. User xxxx is of length 6 or 7 characters. xx.xx.xx.xx and yy.yy.yy.yy are ip addresses thus every octet could be 1 digit or 3 digits.</p> <pre><code>User xxxxxx is attempting to restart primary host xx...
<p>You could use a positive lookahead regex here:</p> <pre><code>Test = df['msg'].str.extract(pat='^.*(?=\s+at [A-Za-z]{3} \d{2}, \d{4}, [\d:]+ (?:AM|PM)$)') </code></pre> <p>Here is a regex demo showing that the above pattern is working:</p> <p><a href="https://regex101.com/r/AILSVU/1" rel="nofollow noreferrer"><h2...
python|regex|pandas|dataframe|extract
2
11,573
61,178,934
merge csv files in a directory with delimeter ";" with the same headers and remove duplicates
<p>I would like to merge several csv files (delimeter ";") in a directory and output them into a single csv file with either another ";" delimeter or with a ",". All csv files have the same amount of headers (the headers must stay) and they're called the same throughout all csv files. But their content might have dupli...
<p>this is me shooting in the dark; have a go at this and lemme know if it works</p> <pre><code>from glob import glob import pandas stock_files = sorted(glob(r'C:\Users\urale\Desktop\logs\pc_dblatmonstat_*_*.log')) final_headers = [ 'Start Time', 'epoch', 'Host Name', 'Db Alias', ...
python|pandas|csv|merge
1
11,574
71,636,001
How to highlight kdeplot in average points?
<p>I have a problem statement to draw graphs on <strong>5 CSV files</strong> of algorithm and compare the <strong>better algorithm among them</strong></p> <p>The csv file contains only floating point numbers of <strong>100 rows * 4 columns</strong> I have plotted the kdeplot comparing the <strong>1st column of 5 csv fi...
<p>You could apply the approach of <a href="https://stackoverflow.com/questions/63307440/how-to-plot-a-mean-line-on-a-distplot-between-0-and-the-y-value-of-the-mean">How to plot a mean line on a distplot between 0 and the y value of the mean?</a> for each of the 5 curves:</p> <pre class="lang-py prettyprint-override"><...
python|pandas|csv|matplotlib|seaborn
2
11,575
69,965,519
cross_entropy_loss(): argument 'target' (position 2) must be Tensor, not numpy.ndarray
<p>Data preparation, and building the model:</p> <pre><code>dataset = datasets.load_iris() data = dataset.data target = dataset.target data_tensor=torch.from_numpy(data).float() target_tensor=torch.from_numpy(target).long() model = nn.Sequential( bnn.BayesLinear(prior_mu=0, prior_sigma=0.1, in_features=4, out_feat...
<p>You used the wrong variable for target.</p> <pre><code>cross_entropy_loss(models, target) </code></pre> <p>would be</p> <pre><code>cross_entropy_loss(models, target_tensor) </code></pre>
python|pytorch
2
11,576
72,297,922
Why is my output predicting the same label using pretrained Alexnet in pytorch?
<p>I'm attempting to use a pretrained alexnet model for CIFAR10 dataset however it always predicts everything as the same class. I use the exact same code except using alexnet untrained and it works as intended. Why is it doing this?</p> <p>Here is my code:</p> <pre><code>device = torch.device('cuda') if torch.cuda.is_...
<p>Pytorch AlexNet was trained on ImageNet so the classifier is with 1000 classes.</p> <p>CIFAR10 is a 10 classes dataset.</p> <p>You should create a new classifier before training with CIFAR10.</p> <p>I found this <a href="https://analyticsindiamag.com/implementing-alexnet-using-pytorch-as-a-transfer-learning-model-in...
python|machine-learning|pytorch|conv-neural-network
0
11,577
72,387,169
How to drop rows from a dataframe based on condition in python?
<p>So I have a CSV file that has data in the following manner:</p> <pre><code>|Variable |Time |Value| |A1 |Jan | 33 | | |Feb | 21 | | |Mar | 08 | | |Apr | 17 | | |May | 04 | | |Jun | 43 | | |Jul | 40 | | |Aug | 37 | ...
<p>Assuming your data is arranged as you described, with some extrapolation as below <a href="https://i.stack.imgur.com/tbLl6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tbLl6.png" alt="enter image description here" /></a></p> <p>Use pandas' <code>ffill()</code> to impute the variable column to f...
python|pandas|csv
0
11,578
72,400,165
How to print row number inside apply function after a criteria
<p>I have a dataframe like as below</p> <pre><code>Company,year T123 Inc Ltd,1990 T124 PVT ltd,1991 T345 Ltd,1990 T789 Pvt.LTd,2001 ABC Limited,1992 ABCDE Ltd,1994 ABC Ltd,1997 ABFE,1987 Tesla ltd,1995 AMAZON Inc,2001 Apple ltd,2003 compare = pd.MultiIndex.from_product([tf['Company']...
<p>Let us try enumerating over the unique values in <code>level 0</code> index:</p> <pre><code>groups = [] grouper = compare.groupby(level=0, sort=False) for i, (k, g) in enumerate(grouper, 1): # Execute statements here groups.append(g.apply(metrics)) print(f'comparison of {i} input key: {k} with {len(g)} ...
python|pandas|dataframe|series|multi-index
2
11,579
72,275,023
How to speed up calculating geometry area of 2D boundary arrays?
<h2>Background</h2> <p>I have four 2D arrays: lon_centers, lat_centers, lon_bnds, and lat_bnds. <code>bnds</code> means the boundary of each pixel and <code>centers</code> stands for the center of pixels.</p> <h2>Data overview</h2> <pre><code>import numpy as np import matplotlib.pyplot as plt lon_bnds = np.array([[-77...
<p>It's very convenient that you have the points arranged in a grid so you know how they match up. The general formula for the area of a planar quadrilateral given a list of points arranged in a counter-clockwise direction is:</p> <pre><code>A = 0.5 * ((x1 * y2 + x2 * y3 + x3 * y4 + x4 * y1) - (x2 * y1 + x3 ...
python|numpy|gis|shapely|pyproj
1
11,580
50,402,400
sum every element of first array with all the elements of second array
<p>I have two arrays:</p> <pre><code>array1 = [1,2,3] array2 = [10,20,30] </code></pre> <p>I want the next sum:</p> <pre><code>array3 = [10+1,10+2,10+3,20+1,20+2,20+3,30+1,30+2,30+3] </code></pre> <p>How can I do that? (I know that it can be done with two <code>for</code> loops but I want something more efficient i...
<p>I do not think pandas is necessary here </p> <pre><code>[x+y for x in array2 for y in array1] Out[293]: [11, 12, 13, 21, 22, 23, 31, 32, 33] </code></pre> <p>If they are in the dataframe </p> <pre><code>df=pd.DataFrame({'a':array1,'b':array2}) df Out[296]: a b 0 1 10 1 2 20 2 3 30 df.a.values+df.b.val...
python|performance|pandas|sum
6
11,581
45,348,033
TensorFlow installation on CentOs7 - libcupti-dev equivalent?
<p>I'm trying to install TensorFlow from sources (<a href="https://www.tensorflow.org/install/install_sources" rel="nofollow noreferrer">https://www.tensorflow.org/install/install_sources</a>) on CentOS7 with GPU support. Is there any equivalent for libcupti-dev library? Is it libcupti.so, or something else?</p>
<p>Building Tensorflow on Centos is painful. I'm working through the issues myself.</p> <p>I had to reach out to an Nvidia engineer for the answer to this one. Installing the Nvidia toolkit creates the directory /usr/local/cuda-8.0/extras/CUPTI/lib64. The library libcupti.so is in there.</p>
tensorflow|centos7
9
11,582
45,704,587
fastest way to do fuzzy matching two strings in pandas data frame
<p>I have two data frames with name list</p> <pre><code>df1[name] -&gt; number of rows 3000 df2[name] -&gt; number of rows 64000 </code></pre> <p>I am using fuzzy wuzzy to get the best match for df1 entries from df2 using the following code:</p> <pre><code>from fuzzywuzzy import fuzz from fuzzywuzzy import proc...
<p>One improvement i can see in your code is to use generator, so instead of square brackets, you can use round brackets. it will increase the speed by multiple time.</p> <pre><code>matches = (process.extract(x, df1, limit=1) for x in df2) </code></pre> <p>Edit: One more suggestion, we can parallelize the operation wit...
python|pandas|jupyter-notebook|fuzzywuzzy|entityresolver
5
11,583
62,584,861
Is there a way to uniquely group by a set of column values in Pandas?
<p>I have a data frame that contains five columns for ID values, and some arbitrary metric. The ID values relate to 5 employees for a specific project, but there is no standard for the order that each ID is entered into the dataset. I want to perform a groupby on the set of 5 ID's to evaluate at a group level.</p> <pre...
<p>To group on a unique combination of items in multiple columns regardless of order, with no missing values, <code>sort</code> the values and assign the sorted values back to the columns. Then you can group plainly. In this case we use <code>numpy</code> because it's one of the faster ways to sort</p> <pre><code>impor...
python|pandas|dataframe|pandas-groupby
0
11,584
62,651,415
Change interval length in pandas
<p>I am trying to change the precision of my data so that it is in 100 length intervals.</p> <p>I was able to do this with plain python, but I was wondering if there was a more elegant solution using pandas (I am still trying to learn).</p> <p><strong>Example:</strong></p> <p>This is the starting data</p> <pre><code>st...
<p>Start from <code>import itertools</code>, it will be needed soon.</p> <p>The part of my solution requiring the most part of coding is to &quot;translate&quot; each source row into a sequence of &quot;intervals&quot; for each hundred range.</p> <p>To do it, define the following generator function:</p> <pre><code>def ...
python|pandas
0
11,585
54,473,018
Where is pandas.tools?
<p>After installing <code>pandas</code>:</p> <pre><code>idf:~/Documents/python/plot$ pip3 install pandas --user Collecting pandas Using cached https://files.pythonhosted.org/packages/f9/e1/4a63ed31e1b1362d40ce845a5735c717a959bda992669468dae3420af2cd/pandas-0.24.0-cp36-cp36m-manylinux1_x86_64.whl Requirement already ...
<p>Package <code>pandas.tools.plotting</code> was moved to <code>pandas.plotting</code> in <a href="https://github.com/pandas-dev/pandas/commit/7993fc81098936a893ec0dc0d84d41cfe4eb4218" rel="noreferrer">this commit</a>, as part of <a href="https://github.com/pandas-dev/pandas/pull/16005" rel="noreferrer">#16005</a> and...
python|python-3.x|pandas
69
11,586
54,505,260
Merge with duplicate indices - Number rows greater than expected
<p>I have two dataframes with some duplicate indices</p> <pre><code>df1 = pd.DataFrame(np.random.randn(5, 3), columns=['A', 'B', 'C'], index=['I1', 'I1' ,'I1', 'I2', 'I2']) df2 = pd.DataFrame(np.random.randn(4, 3), columns=['D', 'E', 'F'], index=['I1', 'I1', 'I1', 'I2']) pd.merge(df1, df2, how='left', left_index=True...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.concat.html" rel="nofollow noreferrer"><code>pd.concat()</code></a> to join on same index:</p> <pre><code>pd.concat([df2,df1],axis=1) A B C D E F I1 0.112906 -1.080809 0.857712 -0...
python|pandas
1
11,587
54,343,216
TypeError: only length-1 arrays can be converted to Python scalars - complex numbers
<p>I have tried to plot a graph with complex values using Python 2.7. But the code did not return the complex values for the y values.</p> <pre><code>import numpy as np import math import cmath import matplotlib.pyplot as plt def f(x): return ((x)*cmath.sqrt((x)+0.5)*((x)+1)) x=np.linspace(-4,-2,10) y=f(x) plt...
<p>try it with numpy:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def f(x): return ((x) * np.sqrt((x) + 0.5) * ((x) + 1)) x = np.linspace(-4, -2, 10).astype(np.complex) y = f(x) plt.plot(y.real, y.imag,'*') for i in range(x.shape[0]): plt.text(y.real[i], y.imag[i],"x="+str(x.real[i])...
python|python-2.7|numpy|matplotlib|math
0
11,588
73,526,741
Faster way to get all elements/indices from 2 arrays with condition depending on each other
<p>I got two binary images of the same size, both contain black blobs.</p> <p><strong>Essentially</strong>, I need to find the positions of all black pixels from both images that are within a specific distance from all black pixels from the other image. This is slow in the most obvious approach. Best case would be some...
<p><a href="https://scipy.org/" rel="nofollow noreferrer">Scipy</a> provides useful functions which make the solution easy.</p> <ol> <li><p>You can use one of the answers to <a href="https://stackoverflow.com/q/56735991/14627505">this question</a> to construct a <code>proximity_mask</code>. I have chosen <a href="https...
python|arrays|numpy
0
11,589
71,436,799
Geopandas plot makes label for every datapoint instead of a colorbar
<p>This is my simple code:</p> <pre><code>gdf_MA_outage.plot(column = 'total_customers_affected_by_city' , cmap = 'OrRd' , figsize = (16,16) , legend = True) </code></pre> <p>'total_customers_affected_by_city' ranges from 1 to 200000. Instead of making a colorbar, it makes a label for every row in that column. Any help...
<p><em>total_customers_affected_by_city</em> must be a string so it is treated as a categorical. Change it to a numeric column and you will get a color bar. Code below shows what you describe where I have deliberately set column to be a string rather than numeric.</p> <pre><code>import geopandas as gpd import numpy a...
python|matplotlib|geopandas|colorbar
1
11,590
71,145,811
Panda get all data from a column A where they have the same value in the column B
<p>I have a dataset (df) like that :</p> <pre><code> Card Number Amount 0 102******38 22.0 1 102******56 76.0 2 102******38 25.6 </code></pre> <p>and it's load using</p> <pre><code>import panda as pd df = pd.read_csv(&quot;file.csv&quot;) </code></pre> <p>And I would like to calcu...
<p>First, you need to calculate the mean value per card number. Let's calculate that by grouping same card numbers, getting the average amount, and call that 'card_mean':</p> <pre><code>mean_values = df.groupby('Card Number')\ .mean()['Amount']\ .reset_index()\ .rename(columns={'Amount':'card_mean'}) </code></...
python|pandas
1
11,591
71,382,852
One large numpy array (3mil rows on 5 columns) - how to pick rows that meet several conditions at the same time? Python 3.8.8
<pre><code> def func(data): A = np.zeros([len(data), 5], np.int16) for i in range(len(data)): if(data[i, 1] &gt;= -10 and data[i, 1] &lt;= -13 and data[i, 3] &gt;= -20 and data[i, 3] &lt;= -22): A[i] = data[i] ...
<p>My solution is very close to AJH one but I believe it is a bit simpler and you don't need to keep in memory a full size <code>A</code> frame. Not sure it changes much but it is a bit less memory intensive.</p> <pre class="lang-py prettyprint-override"><code>def func(data): condition_1 = ((data[:, 1] &lt;= -10) &...
python|numpy|optimization
2
11,592
71,367,219
How to write pandas date column to Databricks SQL database
<p>I have <code>pandas</code> dataframe column that has string values in the format <code>YYYY-MM-DD HH:MM:SS:mmmmmmm</code>, for example <code>2021-12-26 21:10:18.6766667</code>. I have verified that all values are in this format where milliseconds are in 7 digits. But the following code throws conversion error (shown...
<p>Keep the dates as plain strings <strong>without</strong> converting <code>to_datetime</code>.</p> <p>This is because <a href="https://docs.microsoft.com/en-us/azure/databricks/sql/user/queries/query-results-external-data-source" rel="nofollow noreferrer">DataBricks SQL</a> is based on SQLite, and <a href="https://do...
python|pandas|dataframe|sqlalchemy|azure-databricks
1
11,593
52,345,998
Python not finding None in a numpy array
<p>Today python stopped finding None in a numpy array. My code breaks because of the following. Any clue appreciated.</p> <pre><code>In [36]: abc = np.array([3,2,None]) In [37]: None is abc[-1] Out[37]: True In [38]: None in abc /Users/py/htrans.py:1: FutureWarning: comparison to `None` will result in an elementw...
<p>Link: <a href="https://github.com/numpy/numpy/issues/1608" rel="nofollow noreferrer">https://github.com/numpy/numpy/issues/1608</a></p> <p>According to the link, this bug was reported and fixed in the 1.13.0 release of Numpy.</p> <p>A quick workaround you can use is: </p> <p><code>any(elem is None for elem in abc...
python|numpy
2
11,594
60,583,644
Find similar rows and subtract a particular column value in Pandas Dataframe
<p>I know there are similar problems and solutions in here, but I dont seem to find the exact solution.</p> <p>Wanted to find rows with "all but one" column similar.</p> <p>So,</p> <pre><code> ColumnA ColumnB ColumnC ColumnD ColumnE 1 John Texas USA 115 5 2 Mike ...
<p>So I'm not sure exactly what format you want your result in so I made a dictionary where the key is the index of a given row and the value is a list of indices for rows that differ by exactly 1 entry...</p> <pre><code>def ndif(a,b): d = 0 for x,y in zip(a,b): if x!=y: d+=1 ...
python|pandas|dataframe|data-wrangling
0
11,595
60,524,622
Worker killed running Tensorflow on Google App Engine flexible
<p>I am attempting to use Tensorflow to predict from a model on Google App Engine. Session seems to start up and run for a couple of seconds before the worker is killed / booted.</p> <blockquote> <p>tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not com...
<p>It is hard to know the specifics of the reason without knowing your app.yaml or were the app is located, nevertheless, it seems that you are trying to run it in an instance with incompatible CPU. I would recommend you to change the instance CPU in your <a href="https://cloud.google.com/appengine/docs/flexible/go/ref...
tensorflow|google-app-engine|flask
0
11,596
60,490,101
How to sort a dataframe by values from a list
<p>I have a list with numbers:</p> <pre><code>[18, 22, 20] </code></pre> <p>and a dataframe:</p> <pre><code>Id | node_id UC5E9-r42JlymhLPnDv2wHuA | 20 UCFqcNI0NaAA21NS9W3ExCRg | 18 UCrb6U1FuOP5EZ7n7LfOJMMQ | 22 </code></pre> <p>list numbers map to node_id numbers. The order of the node_id numb...
<p>Use sorted <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Categorical.html" rel="nofollow noreferrer"><code>Categorical</code></a>, so you can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>DataFrame...
pandas|list|dataframe|sorting
5
11,597
60,699,779
Round the time up to the nearest hour pandas Series
<p>Trying to round the observed time to the nearest hour</p> <pre><code>Example Data: observed_time = ['2020-02-20T17:54:00Z', '2020-02-20T18:54:00Z'] slice_begin_time=['2020-02-20T17:50:00Z', '2020-02-20T18:50:00Z', '2020-02-20T19:50:00Z', '2020-02-20T20:50:00Z', '2020-02-20T21:50:00Z'] slice_end_time=['2020-02-20T...
<p>Hope this helps:</p> <pre><code>observed_time = ['2020-02-20T17:54:00Z', '2020-02-20T18:54:00Z'] slice_begin_time=['2020-02-20T17:50:00Z', '2020-02-20T18:50:00Z', '2020-02-20T19:50:00Z', '2020-02-20T20:50:00Z', '2020-02-20T21:50:00Z'] slice_end_time=['2020-02-20T18:05:00Z', '2020-02-20T19:05:00Z', '2020-02-20T20:0...
python|pandas|time
1
11,598
60,397,141
'NA' handling in python pandas
<p>i have a dataframe with name,age fieldname,name column has <strong>missing value</strong> and <strong>NA</strong> when i read the value using pd.read_excel,<strong>missing value</strong> and <strong>NA</strong> become NaN,how can i avoid this issue. this is my code</p> <pre><code>import pandas as pd data = {'Nam...
<p>To avoid this, just set the <code>keep_default_na</code> to False:</p> <pre><code>df = pd.read_excel('test1.xlsx', keep_default_na=False) </code></pre>
python-3.x|pandas
2
11,599
60,637,769
Given two matrices and a function that takes two vectors, how to vectorize mean of function for every pair of vectors from the matrices?
<p>I am working on evaluating recommendation algorithms (on their ranking performance). Here, a row in the <code>true_scores</code> (binary) matrix is ground values for all items of a user while a row in the <code>predicted_scores</code> (continuous) matrix is predicted scores for all items from some algorithm. <code>s...
<p><strong>Edit:</strong> I've listed three implementations for the problem. </p> <p>Firstly, it's possible to completely eliminate loops, but the resulting function <code>avg_prec_noloop()</code> is quite memory hungry as it tries to do <em>every</em> operation in one go. As long as the number of items is within 100,...
python|python-3.x|numpy|scikit-learn|vectorization
2