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
362,300
67,154,909
Pandas DataFrame - Issue regarding column formatting
<p>I have a .txt file that has the data regarding the total number of queries with valid names. The text inside of the file came out of a SQL Server 19 query output. The database used consists of the results of an algorithm that retrieves the most similar brands related to the query inserted. The file looks something l...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_fwf.html" rel="nofollow noreferrer"><code>pd.read_fwf()</code></a> in this case, as your columns have fixed widths:</p> <pre><code>import pandas as pd df = pd.read_fwf( &quot;/content/drive/MyDrive/data/classes/100/queries100.txt&quot...
python|pandas|dataframe
1
362,301
66,785,979
Remove duplicates and add some column using python pandas
<p>Is it possible to do the followings using Python Pandas?</p> <p>I have a csv file like the table A.</p> <pre><code>TABLE A ------------------------------------------------ Name Email ------------------------------------------------ Hinckley Joel hjoel@mail.com Hinckley Joel hjoel@mail.com Hi...
<p>This is pivoting with two columns, but you need to remove duplicates:</p> <pre><code>(df.drop_duplicates() .assign(col=lambda x: x.groupby(&quot;Name&quot;).cumcount()) .pivot(index='Name', columns='col', values='Email') .add_prefix('Email_').reset_index() ) </code></pre> <p>Output:</p> <pre><code>col ...
python|pandas
4
362,302
66,768,619
Group if difference of datetime index is less than 5 minutes of a pandas series
<p>I want to perform a groupby.first() of a pandas timeseries where the datetime index is almost consecutive, where almost is less than 5 minutes of difference. I have seen a lot of material but never if the datetime is not consecutive like in my example:</p> <pre><code>ind=['2019-02-28 01:20:00', '2019-02-28 01:21:00'...
<p>Let us <code>group</code> the dataframe on blocks of consecutive rows where time difference is less than <code>5min</code>:</p> <pre><code>df = s.reset_index(name='Value') b = df['index'].diff().dt.seconds.gt(300).cumsum() df = df.groupby(b, as_index=False).first() </code></pre> <h3>Explanations</h3> <p>Reset the i...
python|pandas|group-by|time-series|pandas-resample
4
362,303
66,835,351
How to Create New Column Based on Existing Column Pandas
<p><a href="https://i.stack.imgur.com/n5RXY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n5RXY.png" alt="enter image description here" /></a></p> <p>Hi. Currently, <code>para_str</code> is a novel broken into paragraph form. I'm trying to see if each row of <code>para_str</code> contains dialogue ...
<p>Copy column:</p> <pre><code>df['Dialogue'] = df['para_str'] </code></pre> <p>Apply REGEX:</p> <pre><code>import re def getQuotes(string): return re.findall(r'&quot;([^&quot;]*)&quot;', string) df2 = df['Dialogue'].apply(lambda x: getQuotes(x)) df['Dialogue'] = df2 </code></pre>
python|pandas
0
362,304
66,917,342
Confusion matrix exercise in Python using Numpy
<p>I am trying to build a confusion matrix (2,2) with True positives, False positives, True negatives, False negatives given two lists as input. First list contains the actual values and second list contains the predicted values with only 1s and 0s.</p> <p>It looks like there is something missing in my for loop or if s...
<p>In python, split() function has default value if you don't insert any character. The default value is space(' '). So. try not &quot;1100&quot;, but &quot;1 1 0 0&quot;. Then, You can get result that you want.</p>
python|arrays|numpy|loops|matrix
0
362,305
67,125,012
How to re-structure this in python pandas? Merge, unstack or what?
<p>Trying to re-structure a data frame with a format like this:</p> <pre><code> key ref name value 0 k1 None N1 A 1 None k1 N2 B 2 None k1 N3 C 3 k2 None N4 D 4 k3 None N5 E 5 None k3 N6 F 6 None k3 N7 G # In code df = pd.DataFrame(columns=['ke...
<p>Maybe this is what you need:</p> <pre><code>import pandas as pd df = pd.DataFrame( columns=[&quot;key&quot;, &quot;ref&quot;, &quot;name&quot;, &quot;value&quot;], data=[ [&quot;k1&quot;, None, &quot;N1&quot;, &quot;A&quot;], [None, &quot;k1&quot;, &quot;N2&quot;, &quot;B&quot;], [No...
python|pandas|merge|stack|pandas-groupby
1
362,306
67,049,306
efficient web scraping Python
<p>Hi I am new to web scraping and would like to scrape a website with beautifulsoop. Now I'm wondering about how to write efficient code. This is about a bike website and they have several bikes and for each they have the features price, state, distance and duration. They all have the same class &quot;product-feat&quo...
<p>You can use list comprehension and directly construct a dataframe:</p> <pre><code>pd.DataFrame([[y.text for y in x.select('p.product-feat &gt; span')] for x in soup.select('div[class=&quot;product-smalltext&quot;]')], columns=['price', 'state', 'distance', 'duration']) </code></pre> <p>Output (I've added...
python|html|pandas|web-scraping|beautifulsoup
2
362,307
66,856,931
Python reading data from different directories and merging into one excel file
<p>I'm just a beginner in python. Now trying to use python for merging excel files from different directories.</p> <p>I have a code as seen below. However when executed only one file is being read, and the other 2 files are not merged into the final excel file. Where should I make changed in the code?</p> <p>Thanks in ...
<p>When you loop over <code>subelistesi</code>, only the last value of <code>filenames</code> is kept. A better way would be to create a list before any looping, and add all dataframes to it, then concat once finished looping.</p> <pre class="lang-py prettyprint-override"><code>import glob import pandas as pd import os...
pandas|error-handling|merge|concatenation|glob
0
362,308
66,929,798
How to do a pairwise iteration over two unequal-length tf.datasets?
<p>I work with two datasets of unequal length.</p> <p>My goal is to take for every element in datasetA an element from the other datasetB. I tried <code>.take(1)</code> (as shown <a href="https://stackoverflow.com/questions/57518079/retrieving-the-next-element-from-tf-data-dataset-in-tensorflow-2-0-beta">here</a>) to g...
<p>To get all possible pairs of samples from two datasets, one can use the following <code>generator</code>:</p> <pre><code> # assuming that dataset_A and dataset_B are defined globally def generator(): for sample_A in dataset_A: for sample_B in dataset_B: yield (sample_A, sam...
python|tensorflow|iterator
2
362,309
66,999,666
How to store realtime websocket data on a cloud service
<p>I want to store the real time websocket data of a cryptocurrency exchange. The problem occured when i was storing this data to a csv file using pandas' <code>to_csv()</code> and <code>read_csv()</code> methods. As the file grows python couldn't catchup with the real-time data and is lagging way behind.</p> <p>What c...
<p>One option is using firebase to store each new entry with a query. you can also run a mysql or mongodb to send your data to.</p> <p>If you don't want to implement a connection with db servers you can also use an sqlite database which is a database in a single file.</p>
python|pandas|amazon-web-services|firebase-realtime-database|google-cloud-platform
0
362,310
66,832,708
Pytorch embedding too big for GPU but fits in CPU
<p>I am using PyTorch lightning, so lightning control GPU/CPU assignments and in return I get easy multi GPU support for training.</p> <p>I would like to create an embedding that does not fit in the GPU memory.</p> <pre><code>fit_in_cpu = torch.nn.Embedding(too_big_for_GPU, embedding_dim) </code></pre> <p>Then when I s...
<p>Lightning will send anything that is registered as a model parameter to GPU, i.e: weights of layers (anything in torch.nn.*) and variables registered using <code>torch.nn.parameter.Parameter</code>.</p> <p>However if you want to declare something in CPU and then on runtime move it to GPU you can go 2 ways:</p> <ol> ...
pytorch-lightning
0
362,311
66,973,978
How to check if all possible combinations of columns exist in dataframe (Pandas)?
<p>I have the following dataframe</p> <pre><code> A B ... 0 1 1 1 1 2 2 1 3 0 2 1 1 2 2 2 2 3 </code></pre> <p>And I would like to check if the dataframe is a complete combination of the entries in each column. In the above dataframe this is the case. A = {1,2} B = {1,2,3} and the dat...
<pre><code>df = pd.DataFrame({'A': [1,1,1,2,2,2], 'B': [1,2,3,1,2,3]}) </code></pre> <p>Create a data frame with all combinations of unique values in all columns</p> <pre><code>uniques = [df[i].unique().tolist() for i in df.columns] df_combo = pd.DataFrame(product(*uniques), columns = df.columns) pri...
python|pandas|dataframe
2
362,312
67,096,061
Merging specific columns from multiple excel files with pandas
<p>I am trying to extract the &quot;Rep&quot;, &quot;Units&quot; &amp; &quot;Total&quot; columns from these 3 respective excel files into a new excel file</p> <p><a href="https://drive.google.com/file/d/1RbG76av_2kFXsKv_RstsC3PTmSXkcPp9/view?usp=sharing" rel="nofollow noreferrer">SampleData</a> <a href="https://drive.g...
<p>You need to pass <code>axis=1</code></p> <pre><code>join = pd.concat(dataframes, axis=1) </code></pre> <p>It will concat along the columns, default is <code>axis=0</code> which concatenates along the index i.e. row.</p> <p><strong>Sample Input</strong>:</p> <pre><code>&gt;&gt;df1 units 0 mg 1 gm 2 kg &gt...
python|excel|pandas|dataframe
2
362,313
67,104,828
How to read the tiles into the tensor if the images are tif float32?
<p>I am trying to run a CNN where the input images have three channels (rgb) and the label (target) images are grayscale images (1 channel). The input and label images are in float32 and tif format.</p> <p>I got the list of image and label tile pairs as below:</p> <pre><code>def get_train_test_lists(imdir, lbldir): ...
<p>You can read almost any image format and convert it to a numpy array with the Pillow image package:</p> <pre><code>from PIL import Image import numpy as np img = Image.open(&quot;image.tiff&quot;) img = np.array(img) print(img.shape, img.dtype) # (986, 1853, 4) uint8 </code></pre> <p>You can integrate this functio...
python|tensorflow|conv-neural-network
0
362,314
66,783,661
Replace int values in string with letters in a column using Python
<p>I currently have a csv file. The data originally is derived from PDF and doing a further analysis on the data, There are certain rows where the extracted data contains letters in place of numbers,</p> <p>I need instead of numbers the letters of the variables. So trying to replace the int values by the letters</p> <p...
<p>You might use <code>translate</code> method as follows</p> <pre><code>import pandas as pd data = pd.Series([&quot;2567i&quot;,&quot;28981&quot;,&quot;2534s&quot;,&quot;0123o&quot;]) t = str.maketrans(&quot;iso&quot;,&quot;150&quot;) data = data.str.translate(t) print(list(data)) </code></pre> <p>output</p> <pre><cod...
python|pandas
4
362,315
66,776,403
NameError: name 'IMG_H' is not defined
<p>I am a new programming Interface. I am using the PIL and Matplotlib libraries for the contract streaching.When I am using the Histogram Equalizer I am getting the error as name 'IMG_H' is not defined.I am also Converting my image to numpy array, calculate the histogram, cumulative sum, mapping and then apply the ma...
<p>You have this variable here:</p> <pre><code>mapping[i] = max(0, round((luma_levels*cumsum[i])/(IMG_H*IMG_W))-1) </code></pre> <p>But you didn't define it (or import) before, therefore you get this error.</p>
python|numpy|matplotlib|python-imaging-library|histogram
0
362,316
67,034,738
Can't open HDF5 file bigger than memory... ValueError
<p>I have many .csv of NYC taxi from <a href="https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page" rel="nofollow noreferrer">nyc.gov</a>, one .csv = year-month. There I grab cca 15 of csvs and make HDF5s from them:</p> <pre><code>import h5py import pandas as pd import os import glob import numpy as np impor...
<p>I think this is linked to how pandas is creating hdf5 files. According to vaex's <a href="https://vaex.io/docs/faq.html#Why-can%27t-I-open-a-HDF5-file-that-was-exported-from-a-pandas-DataFrame-using-.to_hdf?" rel="nofollow noreferrer">documentation</a> you can't open a HDF5 file with vaex if it has been created via ...
python-3.x|pandas|bigdata|hdf5|vaex
2
362,317
67,089,730
How to create a list of list from a dataframe
<p>I have a dataframe <strong>df</strong> and I want to convert the dataframe to a list of list</p> <pre><code> left_side right_side similarity 0114600043776001 loan payment receipt 0421209017073500 loan payment receipt 0.689008 011460004377600...
<pre><code>import pandas as pd dfold = {'left_side': ['string','string','string','string'], 'right_side': ['string','string','string','string'] } df = pd.DataFrame(dfold, columns= ['left_side', 'right_side']) print(df) df_list = df.values.tolist() print(df_list) </code></pre>
python|pandas
1
362,318
66,964,723
Get the length of every sentence before padding in torchtext bucketiterator
<p>Is it possible to get the length of every sentence before padding in torchtext bucketiterator :</p> <pre><code>train_loader = torchtext.legacy.data.BucketIterator(train_data, batch_size = 64, repeat=True, shuffle=True, sort_key = lambda x: len(x.text), sort=False, sort_within_batch=True, device = device) </code></pr...
<p>Here is a minimal example that uses <a href="https://torchtext.readthedocs.io/en/latest/data.html#field" rel="nofollow noreferrer"><code>torchtext.data.Field</code></a> and <a href="https://torchtext.readthedocs.io/en/latest/data.html#bucketiterator" rel="nofollow noreferrer"><code>torchtext.data.BucketIterator</cod...
pytorch|torchtext|pytorch-dataloader
0
362,319
66,833,434
Map values in array to their sorted index
<p>I am trying to minimize the values in an array by mapping them to their sorted index.</p> <p>For example <code>[8, 8, 15, 3, 5]</code> would become <code>[2, 2, 3, 0, 1]</code>. I was able to accomplish with the following code but it takes a long time for large arrays.</p> <pre><code>a = [8, 8, 15, 3, 5] a_mapped =...
<p>If you use <code>scipy</code>, you can use <code>rankdata</code> from <code>scipy</code>:</p> <pre><code>from scipy.stats import rankdata import numpy as np a = np.array([8, 8, 15, 3, 5]) rankdata(a, method='dense') - 1 # [2 2 3 0 1] </code></pre>
python|numpy
3
362,320
67,014,834
SyntaxError: unexpected EOF while parsing while pd.read_csv(io.StringIO(uploaded['Rawdata_2001to2018.csv']
<p>I get this message with the code. Can you help me File &quot;&quot;, line 93 &quot;state&quot;:str}) ^ SyntaxError: unexpected EOF while parsing</p> <pre><code> \\\ Codes import pandas as pd import numpy as np import io Rawdata_2001to2018_df = pd.read_csv(io.StringIO(uploaded['Rawdata_2001to201...
<ul> <li>Change your code as below <strong>\/</strong></li> </ul> <pre class="lang-py prettyprint-override"><code> import pandas as pd import numpy as np import io Rawdata_2001to2018_df = pd.read_csv(io.StringIO(uploaded['Rawdata_2001to2018.csv'].encoding('ISO-8859-1')), dtype= {&quot;gvkey&quot;:str, &quot;d...
python-3.x|pandas
0
362,321
67,057,306
Should I join features and targets dataframes for use with scikit-learn?
<p>I am trying to create a regression model to predict deliverables (dataframe 2) using design parameters (dataframe 1). Both dataframes have a id number that I used as an index.</p> <p>Is it possible to use two dataframes to create a dataset for sklearn? Or do I need to join them? If I need to join them then what woul...
<p>All estimators in scikit-learn have a signature like <code>estimator.fit(X, y)</code>, <code>X</code> being training features and <code>y</code> training targets.</p> <p>Then, prediction will be achieved by calling some kind of <code>estimator.predict(X_test)</code>, with <code>X_test</code> being the test features....
pandas|scikit-learn
0
362,322
67,066,005
tensorflow datasets found a different version of the requested dataset
<p>I loaded the imagenet2012 datasets according to the instructions on tensorflow datasets for imagenet2012, and it produced a directory storing the tfrecords under imagenet2012/5.0.0.</p> <p>But when I reload the dataset, it says</p> <p>WARNING:absl:Found a different version of the requested dataset: 5.0.0 Using /data...
<p>If you run as <code>tfds.load('imagenet2012:5.1.0')</code>, the error message should go away</p>
tensorflow-datasets
0
362,323
66,950,157
Getting predict.proba from BERT classififer
<p>I have a classifier on top of BERT, and I would like to see the predict probability for creating the ROC curve. How do I get the predict proba?. The predicted probas will be used to calculate the TPR FPR and threshold for ROC curve. <br> here is the code</p> <pre><code>class BertBinaryClassifier(nn.Module): def ...
<p>In your <code>forward</code>, you:</p> <pre><code>def forward(self, tokens, masks=None): _, pooled_output = self.bert(...) # Get output of BERT dropout_output = self.dropout(pooled_output) linear_output = self.linear(dropout_output) # Take linear combination of outputs ...
python|python-3.x|pytorch|bert-language-model|huggingface-transformers
0
362,324
67,130,101
How to calculate the average periode duration of date series with panda?
<p>I would like to calculate the mean periode duration for the occurrence of different events.</p> <p>I got data where every event has an id and is tracked in a single line identified by its id. every time an event occurs the date of occurrence is saved.</p> <pre><code>df_starting_point = pd.DataFrame( ...
<p>based on what I understood, you can do a shift on axis=1, period -1 and subtract, create a mask on the same specification :</p> <pre><code>df_end_point = df_starting_point.set_index(&quot;id&quot;) df_end_point= (df_end_point.sub(df_end_point.shift(-1,axis=1)) .dropna(how='all',axis=1).reset_index())...
python|pandas|date|timedelta
1
362,325
67,131,914
Creating new columns in Pandas dataframe reading csv file
<p>I'm reading a simple csv file and creating a pandas dataframe. The csv file can have 1 row or 2 rows or 10 rows.</p> <p>If the csv file has 1 row then I want to create few columns and if it has &lt;=2 rows, then create couple of new columns and if it has 10 rows, then I want to create 10 new columns.</p> <p>After re...
<p>for case 2 and case 3, you can do something like this -</p> <p>Case 2-</p> <pre><code># case 2 df= pd.read_csv('test.txt') lb_dict = { f'lb_{i}': value for i,value in enumerate(df['lb'].to_list(),start=1)} lb_df = pd.DataFrame.from_dict(lb_dict, orient='index').transpose() ub_dict = { f'ub_{i}': value for i,value in...
pandas|dataframe
0
362,326
67,130,643
Nested dictionary to pandas df concatenating rows
<p>Given the following dict:</p> <pre><code>j = { &quot;source&quot;: &quot;https://example.com&quot;, &quot;timestamp&quot;: &quot;2021-04-12T19:34:24Z&quot;, &quot;durationInTicks&quot;: 1082400000, &quot;duration&quot;: &quot;PT1M48.24S&quot;, &quot;combinedRecognizedPhrases&quot;: [ { &quot;chan...
<p>You can <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><strong><code>pivot()</code></strong></a> into the expected output:</p> <pre class="lang-py prettyprint-override"><code>index = ['source', 'durationInTicks', 'duration'] columns = ['recognizedPhrases....
python|pandas|json-normalize|glom
0
362,327
66,830,798
Pytorch Model Summary
<p>I am trying to load a pytorch model using:</p> <pre><code>model = torch.load('/content/gdrive/model.pth.tar', map_location='cpu') </code></pre> <p>I want to check the model summary. When I try:</p> <pre><code>print(model) </code></pre> <p>I get the following output:</p> <pre><code>{'state_dict': {'model.conv1.weight...
<p>You loaded the &quot;*.pt&quot; and didn't feed it to a model (which is just a dictionary of the weights depending on what you saved) this is why you get the following output:</p> <pre><code>{'state_dict': {'model.conv1.weight': tensor([[[[ 2.0076e-02, 1.5264e-02, -1.2309e-02, ..., -4.0222e-02, -4.0527e...
python|pytorch
2
362,328
66,900,665
How to properly access individual tensor after concatenate?
<p>I need to concatenate two tensors, but I am a bit confused about accessing the element afterward. For an example:</p> <pre><code>import numpy as np import tensorflow as tf x = np.random.randint(100,size=(100,120,14)) y = np.random.randint(50,size=(100,120,14)) z = tf.concat([x,y],axis=0) </code></pre> <p>Now how ca...
<p>Here is the complete answer reference by @Lescurel, use <code>tf.stack</code></p> <pre><code>import tensorflow as tf from tensorflow.keras.backend import eval # let's say x, y, z x = tf.constant([1, 4]) y = tf.constant([2, 5]) z = tf.constant([3, 6]) eval(x), eval(y), eval(z) (array([1, 4], dtype=int32), array(...
python|tensorflow|concatenation
1
362,329
67,089,373
Merge or join two datasets using between two numbers in python
<p>I have got two data sets;</p> <p>Trying to merge df2 (content data) on df1 (viewed data). Have to use merge. However, the key is not standard but should be a between key.</p> <pre><code>df1 = pd.DataFrame({&quot;ID&quot;: [1, 2],&quot;start&quot;:[7200, 1000],&quot;end&quot;:[7400, 1100],&quot;duration&quot;:[200, 1...
<p>You can take cartesian product of <code>df1</code> and <code>df2</code>, then filter only the overlapping intervals, and calculate durations:</p> <pre><code># cartesian product and interval filtering z = (df1 .assign(k=1).merge(df2.assign(k=1), on='k') .query('(Prog_start &lt; end) &amp; (Prog_end ...
python|pandas|merge
2
362,330
67,140,812
How can I define f(x) = some integral in python
<p>I'm trying to define the following function:</p> <p><img src="https://latex.codecogs.com/png.latex?%5Cbg_white%20%5Chuge%20f%28x%29%20%3D%20%5Cint_%7Bx%7D%5E%7B0%7D%5Cfrac%7B1%7D%7B2%5Cpi%7De%5E%7B%5Cfrac%7B-r%5E%7B2%7D%7D%7B2%7D%7Ddt-0.45" alt="" /></p> <p>And this is the code I'm using:</p> <pre class="lang-py pre...
<p>Reading documentation to understand how to call a function is critical! Looking at the doc for <code>scipy.integrate.quad</code>: <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.qu...
python|numpy|symbolic-math
4
362,331
67,133,480
Evenly sampled 3D meshgrid
<p>I have a 3-dimensional meshgrid generated using the following code:</p> <pre><code>x = np.linspace(-1,1,100) xx, yy, zz = np.meshgrid(x, x, x) </code></pre> <p>This generates a 100 x 100 x 100 point 3-d grid of points. I would like to plot an evenly-space sub-sampling of this same grid, without having to generate ...
<pre><code>In [117]: x = np.linspace(-1,1,100) ...: xx, yy, zz = np.meshgrid(x, x, x) In [118]: xx.shape Out[118]: (100, 100, 100) </code></pre> <p>1000 equally spaced points in <code>xx</code>, similarly for all other grids:</p> <pre><code>In [119]: xx[::10,::10,::10].shape Out[119]: (10, 10, 10) </code></pre> <p...
python|arrays|numpy|multidimensional-array
1
362,332
67,165,211
There's some way to create a line from a string split
<p>I need your help on something like this:</p> <p>My input (when I read .csv file):</p> <p><a href="https://i.stack.imgur.com/Bhj2j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bhj2j.png" alt="enter image description here" /></a></p> <pre><code>data = {'A':['000','001','002'], 'B':['Name0','Na...
<p>It seems a physical work rather than a technical work:)</p> <pre class="lang-py prettyprint-override"><code>entry_list = df.loc[2, 'B'].split(' ') df.loc[2, 'B'] = entry_list[0] entry_list = entry_list[3:] lines = [] for i in range(0, len(entry_list), 4): raw_line = entry_list[i:i+4] line = [item.replace('@'...
python|pandas
1
362,333
66,898,529
Dataframe.max() giving all NaNs
<p>I have a pandas DataFrame with data that looks like this:</p> <p><a href="https://i.stack.imgur.com/Rkyy2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rkyy2.png" alt="enter image description here" /></a></p> <p>With the data extending beyond what you can see here. I can't tell if the blue cells...
<p>First convert all values to numeric by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html" rel="nofollow noreferrer"><code>DataFrame.astype</code></a>:</p> <pre><code>df = df.astype(float) </code></pre> <p>If not working, use <a href="http://pandas.pydata.org/pandas-docs/...
python|pandas|dataframe|max|nan
3
362,334
66,998,478
Conversion of nested list to np.array for tensor model prediction is incorrect
<p>I have an input array created from :</p> <pre><code>initial window = 'I have a bad feeling about this' seq_tokens = t.texts_to_sequences(initial_window) # seq_tokens = [[4], [], [], [5], [590], [], [], [5], [], [998], [5], [], [], [], [], [], [], [4], [], [], [], [5], [998], [591], [], [], [], [], [], [4], []] </cod...
<p>According to the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/text/Tokenizer#texts_to_sequences" rel="nofollow noreferrer">documentation</a>, <code>Tokenizer.texts_to_sequences()</code> takes a list of strings as argument. If you provide a string only, it probably tries to create a lis...
python|arrays|numpy|keras|tensor
0
362,335
67,063,643
Is there a way to force pandas dataframe query to use 'python' as default engine?
<p>According to doc, you can do this:</p> <pre><code>df.query(myQuery, engine='python') </code></pre> <p>It happens that 99% of what I did (in a single file or ipython notebook), i will need engine='python', and it gets really tiresome to be reminded of, and typing that extra arg. Is there a global config I can use to...
<p>It does not seem like that is an <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html#available-options" rel="nofollow noreferrer">available option</a> provided by pandas.</p> <p>You can make a workaround though by using the <a href="https://docs.python.org/3/library/functools.html#functools...
python|pandas|dataframe
1
362,336
66,860,762
numpy generate random elements within triangle
<p>I'd like to generate random points within a triangle based on the points <code>(0, 0) (0, 1), (1, 0.5)</code>. I figure the easiest way to do this is to generate the points within the <code>(0, 0), (0, 1), (1, 1), (1, 0)</code> square using numpy and then filter it to that triangle.</p> <p>Here is the code that will...
<p>If you want to go for a filtering approach, you have to find a condition to check which points are inside the triangle. Then you can use numpys argwhere function to find the indices of all points that fullfill your condition:</p> <pre><code>pts = np.random.rand(1000, 2) x_coord = pts[:, 0] y_coord = pts[:, 1] def ...
python|numpy
2
362,337
67,109,987
List all points within distance to line
<p>I have a list of coordinates <code>a</code>. I want to specify a radius <code>r</code> and then list all points on a 2D grid within the specified radius of any point in <code>a</code>, together with the minimum distance of each of those grid-points to any point in <code>a</code>. Since <code>a</code> is substantial ...
<p>You can adapt <a href="https://stackoverflow.com/a/67108327">the answer</a> I gave to your other linked question in a very straightforward way. The outcome is also very fast (~425 ms for 10K points in <code>a</code>).</p> <p><strong>Edit</strong>: For sparse cases (where the number of points actually filtered is a s...
python|arrays|numpy|scipy
3
362,338
47,266,569
replace values in pandas based on other two column
<p>I have problem with replacement values in a column conditional other two columns.</p> <p>For example we have three columns. A, B, and C Columns A and B are both booleans, containing True and False, and column C contains three values: "Payroll", "Social", and "Other".</p> <p>When in columns A and B are True in colu...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.all.html" rel="nofollow noreferrer"><code>all</code></a> for check if all <code>True</code>s per rows and then assign output by filtered <code>DataFrame</code> by boolean mask:</p> <pre><code>data1 = pd.DataFrame({ ...
python-3.x|pandas|dataframe|replace
1
362,339
47,483,733
Print exact value of PyTorch tensor (floating point precision)
<p>I'm trying to print <code>torch.FloatTensor</code> like:</p> <pre><code>a = torch.FloatTensor(3,3) print(a) </code></pre> <p>This way I can get a value like:</p> <pre><code>0.0000e+00 0.0000e+00 3.2286e-41 1.2412e-40 1.2313e+00 1.6751e-37 2.6801e-36 3.5873e-41 9.4463e+21 </code></pre> <p>But I want to get more...
<p>You can set the precision options:</p> <pre><code>torch.set_printoptions(precision=10) </code></pre> <p>There are more formatting options on the <a href="http://pytorch.org/docs/master/torch.html#creation-ops" rel="noreferrer">documentation page</a>, it is very similar to numpy's.</p>
python|pytorch
41
362,340
47,310,975
How to speed up importing dataframes into pandas
<p>I understand that one of the reasons why pandas can be relatively slow importing csv files is that it needs to scan the entire content of a column before guessing the type (see the discussions around the mostly deprecated <code>low_memory</code> option for <code>pandas.read_csv</code>). Is my understanding correct?<...
<p>One option is to use <a href="https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.genfromtxt.html" rel="nofollow noreferrer"><code>numpy.genfromtxt</code></a> with <code>delimiter=',', names=True</code>, then to initialize the pandas dataframe with the numpy array. The numpy array will be structured an...
python|pandas|dataframe
2
362,341
47,146,800
Python: 2D Numpy Array (Matrix) - Finding Sum of Negative Numbers (Rows)
<p>I have a matrix (using <code>numpy</code>), user enters number of rows and columns. After going through some FOR loops, user enters elements, of course depending on what number of rows and columns did he/she has chosen.</p> <p>Now I need to find a sum of negative elements for every row below row 7 and output this e...
<pre><code>a = np.random.random_integers(-1, 1, (10,3)) &gt;&gt;&gt; a array([[ 0, 0, -1], [ 1, -1, -1], [ 0, 1, 1], [-1, 0, 0], [ 1, -1, 0], [-1, 1, 1], [ 0, 1, 0], [ 1, -1, 0], [-1, 0, 1], [ 1, -1, 1]]) &gt;&gt;&gt; </code></pre> <p>You can...
python|arrays|numpy|matrix
1
362,342
47,500,913
Tensorflow lite example with custom model - "input_product_scale < output_scale was not true"
<p><strong>How to reproduce:</strong><br> retrain a mobilenet with command: </p> <pre><code>python tensorflow/tensorflow/examples/image_retraining/retrain.py —image_dir (data-pwd) —learning_rate=0.001 —testing_percentage=20 —validation_percentage=20 —train_batch_size=32 —validation_batch_size=-1 —flip_left_right ...
<p>Does the following not work for you?</p> <p><strike>bazel-bin/tensorflow/contrib/lite/toco/toco --input_file=(path)/output_graph.pb --input_format=TENSORFLOW_GRAPHDEF --output_format=TFLITE --output_file=./mobilenet_quantized_224.tflite --inference_type=QUANTIZED_UINT8 --input_type=QUANTIZED_UINT8 --input_array=Pla...
tensorflow|tensorflow-lite
1
362,343
47,210,958
Fastest way to find exchange times in Python
<p>I have two lists of times. Starting from each point in list1, I want to find the closest subsequent (greater) time in list2. </p> <p>For example:</p> <p>list1 = [280, 290]</p> <p>list2 = [282, 295]</p> <p>exchange(list1, list2) = [2, 5]</p> <p>I'm having trouble doing this quickly. The only way I can think to d...
<p>I propose a solution with <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.searchsorted.html" rel="nofollow noreferrer"><code>np.searchsorted</code></a> (numpy is the pandas skeleton) wich find insertion points of a list in an other. it's a <code>O(N ln (N))</code> solution, when yours ...
python|pandas
1
362,344
47,201,417
How to configure Python in a GPU cluster?
<p>I have a GPU cluster with one storage-node and several computing nodes each has 8 GPU. I am configuring the cluster. </p> <p>One of the task is to configure the python, what we need is several versions of Python and some python packages, and for some packages we may require several versions of it, such as different...
<p>You can install <a href="http://modules.sourceforge.net/" rel="nofollow noreferrer">Modules software environment</a> in a shared directory accessible on every node. Then it will be easy to load a specific version of python or TensorFlow:</p> <pre><code>module load lang/Python/3.6.0 module load lib/Tensorflow/1.1.0 ...
python|tensorflow|pip|hpc
1
362,345
47,444,362
Tensorflow batching without extra None dimension?
<p>Is it possible to do batching in tensorflow without expanding the placeholder size by an extra dimension of None? Specifically I'd just like to feed multiple samples via the placeholders through feed_dict. The code base I'm working on would require a large amount of change to the code to account for adding an extra ...
<p>The shape information including the number of dimensions is available to Python code to do arbitrary things with, and does affect the ops added to the graph (like which matmul kernel is used), so there's no general safe way to automatically add a batch dimension. Something like <a href="https://github.com/tensorflow...
tensorflow|batching
0
362,346
47,296,752
Plot Pandas groupby dataframe
<p>I am having some problems with plotting a Pandas dataframe that was created from a groupby() and now has a RangeIndex.</p> <p>For example, here is my input data with four columns:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame(np.random.randint(0,100,size=(...
<p>By using <code>left</code> to get the leftbreak.</p> <pre><code>gb_df['New_A']=gb_df.A.apply(lambda x : x.left).astype('float') gb_df.plot.scatter(x = 'New_A', y='B') </code></pre> <p><a href="https://i.stack.imgur.com/5Mcil.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Mcil.png" alt="enter i...
python|pandas|matplotlib
1
362,347
47,359,439
cx_Freeze - opencv compatibility
<p>I get a <code>numpy.core.multiarray failed to import</code> error whenever I try to build an exe file using cx_Freeze.</p> <p>My system uses the following versions:</p> <blockquote> <p>python 3.6.0</p> <p>opencv 3.3.0</p> <p>numpy 1.13.1</p> <p>cx_Freeze 5.0</p> </blockquote> <p>The code is:</p> <pre><code>impor...
<p>I managed to make this work only after I uninstalled cx_Freeze and installed <a href="http://www.pyinstaller.org/" rel="nofollow noreferrer">Pyinstaller</a> instead. It works like a charm.</p>
python|numpy|opencv|cx-freeze
2
362,348
47,161,550
Pandas Loc select by index as well as boolean condition in single expression
<p>I have a simplified Dataframe which can be set up as follows:</p> <pre><code>indexes =['01/10/2017', '28/10/2018', '27/10/2019', '30/10/2019'] cols = ['Period', 'A', 'B', 'C'] df= pd.DataFrame(index = indexes, columns= cols) df.Period = 1 df = pd.concat([df, 2*df.copy(), 3*df.copy()]) df.sort_index() </code></pre> ...
<p>Combine the two conditions, use <code>isin</code> for the first.</p> <pre><code>df[df.index.isin(['28/10/2018', '27/10/2019']) &amp; (df.Period &gt; 2)] Period A B C 28/10/2018 3 NaN NaN NaN 27/10/2019 3 NaN NaN NaN </code></pre>
python|pandas
6
362,349
47,133,863
Inserting multiple elements in a numpy array
<p>Is there a function in python that allows me to insert number 100's or consecutive non zeros in the array [1,2,3,4,5]?</p> <p>Output should be [1, 100, 100, 100, 2, 100, 100, 100, 3 .....] or [ 1, 100, 101, 102, 2 , 100, 101, 102, 3...] </p> <p>I have tried numpy.insert()</p> <p>ar2=np.insert(ar1, slice(1,None),...
<p>You can use <code>numpy.kron</code></p> <pre><code>np.kron([1,2,3,4,5],[1,0,0,0]) + 100*np.kron(np.ones(5),[0,1,1,1]) </code></pre> <p>for the second one</p> <pre><code>np.kron([1,2,3,4,5],[1,0,0,0]) + np.kron(np.ones(5),[0,101,102,103]) </code></pre>
python-3.x|numpy
0
362,350
47,110,528
Return coordinates for bounding boxes Google's Object Detection API
<p>How can i get the coordinates of the produced bounding boxes using the inference script of Google's Object Detection API? I know that printing boxes[0][i] returns the predictions of the ith detection in an image but what exactly is the meaning of these returned numbers? Is there a way that i can get xmin,ymin,xmax,y...
<p>Google Object Detection API returns bounding boxes in the format [ymin, xmin, ymax, xmax] and in normalised form (full explanation <a href="https://www.tensorflow.org/api_guides/python/image#Working_with_Bounding_Boxes/" rel="noreferrer">here</a>). To find the (x,y) pixel coordinates we need to multiply the results ...
tensorflow|object-detection|object-detection-api
15
362,351
47,179,246
Using vtk library in python to extract vtk data as array
<p>I would like to use the <code>vtk</code> library in python 2.7 to extract data from vtk unstructured grid files and convert this data to <code>numpy</code> or python <code>list</code> format. The vtk file is structured as follows:</p> <pre><code>ASCII DATASET UNSTRUCTURED_GRID POINTS 96 float CELLS 9...
<p>The names of VTK functions in Python are analogous to the C++ ones. So you can use the functions given in the <a href="https://www.vtk.org/doc/nightly/html/classvtkUnstructuredGridReader.html" rel="nofollow noreferrer">C++ Documentation for vtkUnstructuredGridReader</a></p> <pre><code>import vtk Filename = 'test.vt...
python|arrays|numpy|vtk
1
362,352
47,240,348
What is the meaning of the "None" in model.summary of KERAS?
<p><a href="https://i.stack.imgur.com/be1s4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/be1s4.png" alt="enter image description here"></a></p> <p>What is the meaning of the (None, 100) in Output Shape? Is this("None") the Sample number or the hidden dimension?</p>
<p><code>None</code> means this dimension is variable. </p> <p>The first dimension in a keras model is always the batch size. You don't need fixed batch sizes, unless in very specific cases (for instance, when working with <code>stateful=True</code> LSTM layers). </p> <p>That's why this dimension is often ignored ...
tensorflow|machine-learning|keras
59
362,353
47,477,789
Pandas concat and OHLC issue
<p>I have an old script and it used to work perfectly, it was designed to take tick (bid and ask) data and turn it into OHLC data using pandas <code>.resample</code> and <code>.agg</code>, like the following:</p> <pre><code>df = pd.DataFrame(list(MDB.CHART.find())) DF = df[['dt','bid','ask']] DF = DF.set_index('dt') ...
<p>So from now on we'll have to use the following when using bid and ask data, as renaming with a dict is to be depreciated soon:</p> <pre><code> db = DF.bid.resample('2T').ohlc().add_suffix('bid') da = DF.ask.resample('2T').ohlc().add_suffix('ask') df = pd.concat([db, da], axis = 1) df.head(3) ...
python|pandas|aggregate|resampling
0
362,354
47,386,523
Dataframe to json in layers
<p>I have a dataframe:</p> <pre><code>school_id city id name batch roll_no age xx ax 1 abc a1 100 13 xx ax 1 dsf a2 200 45 xx ax 2 fas a1 400 23 </code></pre> <p>i have to convert it into multi layered json format: such th...
<p>First add new column <code>message</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with custom function for <code>dict</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataF...
python|json|pandas
1
362,355
47,515,454
Mapping RGB values in an image to a corresponding ID using a dictionary
<p>I am working on a segmentation problem where given an image, each RGB value corresponds to a class label. The problem I have is to efficiently map RGB values from an image (numpy array) to a corresponding class label image.</p> <p>Let's provide the following simplified example:</p> <pre><code>color2IdMap {(100,0,...
<p>Assume the RGB value map is like this(store in a Python dict):</p> <pre class="lang-py prettyprint-override"><code>color_dict = {(128,128,128):(255,255,255), (128,256,128):(255,128,255), } </code></pre> <p>The RGB value remap operation can be done using np.where() and np.all():</p> <pre class="lang-py ...
python|arrays|image|numpy
0
362,356
47,110,193
New Matrix with new rows formed in 2nd dataframe wrt 1st dataframe
<pre><code>data1 = { 'node1': [1,1,1,2], 'node2': [2,3,5,4], 'weight': [1,1,1,1], } df1 = pd.DataFrame(data1, columns = ['node1','node2','weight']) data2 = { 'node1': [1,1,2,3], 'node2': [4,5,4,5], 'weight': [1,1,1,1], } df2= pd.DataFrame(data2, columns = ['node1','node2','weight']) Expected Outp...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow noreferrer"><code>merge</code></a> for <code>1</code> values with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> for al...
python|numpy|dataframe
1
362,357
47,205,160
Tensorflow v1.4: Layer.input not supported in Eager mode
<p>I understand that Eager mode is a new alpha feature on the nightly builds and that it is not perfect yet, but I do not know if there are any tf.keras workarounds for this problem.</p> <p>The error <code>Layer.input not supported in Eager mode.</code> triggers on the block</p> <pre><code>model = tf.keras.models.Seq...
<p>Keras <code>Model</code>s are not yet supported with eager execution, but Keras layers are. Which means that while you can't use <code>tf.keras.models.Sequential</code> yet, you could combine layers yourself. See <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/g3doc/guid...
python|tensorflow|keras|eager
1
362,358
47,224,567
Creating a Running Total column in a matrix?
<p>Related to <a href="https://stackoverflow.com/questions/47221759/returning-a-numpy-matrix/47222030?noredirect=1#comment81396707_47222030">this question I recently posted &amp; resolved</a>.</p> <p>If the 3rd column of a matrix is to be changed to be the running total of the sums, how would I adjust my code to do so...
<p>For your purposes, an easy way to keep track of z would be to initialise it outside of the loop, then keep adding the value of <code>sum_2_dice</code>.</p> <pre><code>def dice(n): z = 0 rolls = np.empty(shape=(n, 3),dtype=int) for i in range(n): x = random.randint(1,6) y = random.randint...
python|python-2.7|numpy
0
362,359
47,319,424
Digging down json file
<p>I have been trying in many ways (and by many questions in stackoverflow) to normalize a deep json file. I have tried with <code>.apply(pd.Series)</code>, not great with many levels of dictionary.</p> <p>I am currently trying with <code>json_normalize</code> and it has given some results. I think I know how the func...
<p>Can you try this : </p> <pre><code>json_normalize(raw['hits'],'hits','_source','authors','affiliations') </code></pre>
json|python-3.x|pandas
0
362,360
47,246,384
pandas monthly resample 15th day
<p>I am trying to resample to monthly values but with respect to 15th day</p> <p>I checked the timeseries <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases" rel="nofollow noreferrer">offsets</a> documentation but there is only</p> <p>M month end frequency SM semi-month end frequen...
<p>Aggregate by starts of months <code>MS</code> and then adjust the resampled time labels by <code>loffset</code> parameter:</p> <pre><code>df1 = df.resample('MS', loffset=pd.Timedelta(14, 'd')).sum() </code></pre> <p>Sample:</p> <pre><code>rng = pd.date_range('2017-04-03', periods=15, freq='5D') df = pd.DataFrame(...
python|pandas|resampling
7
362,361
47,393,001
How to save a huge pandas dataframe to hdfs?
<p>Im working with pandas and with spark dataframes. The dataframes are always very big (> 20 GB) and the standard spark functions are not sufficient for those sizes. Currently im converting my pandas dataframe to a spark dataframe like this:</p> <pre><code>dataframe = spark.createDataFrame(pandas_dataframe) </code>...
<blockquote> <p>Meaning having a pandas dataframe which I transform to spark with the help of pyarrow. </p> </blockquote> <p><a href="https://github.com/apache/arrow/blob/42fc57be9c768add32b278adbee2f6f30b10005d/python/pyarrow/table.pxi#L679-L705" rel="noreferrer"><code>pyarrow.Table.fromPandas</code></a> is the fun...
python|pandas|apache-spark|pyarrow|apache-arrow
21
362,362
11,362,376
Append extras informations to Series in Pandas
<p>Is it possible to customize Serie (in a simple way, and DataFrame by the way :p) from pandas to append extras informations on the display and in the plots? A great thing will be to have the possibility to append informations like "unit", "origin" or anything relevant for the user that will not be lost during computa...
<p>Right now there is not an easy way to maintain metadata on pandas objects across computations.</p> <p>Maintaining metadata has been an open discussion on github for some time now but we haven't had to time code it up.</p> <p>We'd welcome any additional feedback you have (see pandas on github) and would love to acc...
python|pandas
1
362,363
10,989,438
How to cleanly index numpy arrays with arrays (or anything else that supports addition so that it can be offset)
<p>The easiest way to explain my question may be with an example, so let me define some arrays:</p> <pre><code>&gt;&gt;&gt; test = arange(25).reshape((5,5)) &gt;&gt;&gt; test array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]) &g...
<p>I'm not entirely sure what you want, but maybe <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ix_.html"><code>ix_</code></a> would help? I think I've seen people who know more about numpy than I do use it in similar contexts.</p> <pre><code>&gt;&gt;&gt; from numpy import array, arange, ix_ &gt;...
python|numpy|indexing|offset
13
362,364
11,376,080
Plot numpy datetime64 with matplotlib
<p>I have two numpy arrays 1D, one is time of measurement in datetime64 format, for example:<br></p> <pre><code>array([2011-11-15 01:08:11, 2011-11-16 02:08:04, ..., 2012-07-07 11:08:00], dtype=datetime64[us]) </code></pre> <p>and other array of same length and dimension with integer data.<br> I'd like to make a plot...
<pre><code>from datetime import datetime a=np.datetime64('2002-06-28').astype(datetime) plot_date(a,2) </code></pre>
python|datetime|numpy|matplotlib
22
362,365
68,397,254
Python scipy.io write a mat file of n by 1
<p>I need to save a .mat file from python. The mat file should be a cell array of n by 1. The code below does what I need except the output mat file is 1 by n.</p> <pre><code>import scipy.io as sio import numpy as np Label = ['A','Bob','C'] mat_file = {'label_mat':np.array(Label, dtype=object)} sio.savemat(r'./test.ma...
<p>Just do a list of lists.</p> <pre><code>import scipy.io as sio import numpy as np Label = [['A'],['Bob'],['C']] mat_file = {'label_mat':np.array(Label, dtype=object)} sio.savemat(r'./test.mat', mat_file) </code></pre>
python|numpy|scipy
0
362,366
68,030,077
How can I get indices of the first column from a 2-D array that satisfies the condition without Iterations?
<p>Assuming X like this:</p> <pre><code>[[6 3 4] [3 0 9] [7 7 8] [8 5 1] [8 3 8]] </code></pre> <p>the condition <code>x &lt; 5</code></p> <p>and then get array like this, they are the indices of the first column in the array that satisfies the condition.</p> <pre><code>[1,0,None,2,1] </code></pre> <p>can I get ...
<p>This is almost <code>np.argmax</code> with a mask but since <code>argmax</code> will return 0 when all elements of a row are <code>False</code> in a mask, we can resort to <code>any</code>. Also, to incorporate <code>None</code>, integer type isn't enough:</p> <pre><code># get a boolean array over the condition mask...
python|numpy|multidimensional-array
1
362,367
68,261,070
create list of specific dates by variabels
<p>i am looking for a solution to create, based on a existing dataframe with a datetimeindex, a list of specific dates. these dates are based on the variables &quot;month&quot; and &quot;date_d&quot; and the start and end of the existing dataframe.</p> <pre><code>import pandas as pd df_date = pd.date_range(start=&quot;...
<p>Seems like <code>df_date</code> could be filtered to match only where <code>% month</code> is 0 and the <code>day</code> matches <code>date_d</code>:</p> <pre><code>import pandas as pd df_date = pd.date_range(start=&quot;2018-07-01&quot;, end=&quot;2020-02-02&quot;) month = 6 date_d = 15 out = ( df_date[(df_d...
pandas|datetime
2
362,368
68,298,794
Calculate keras metric in numpy rather than tensorflow
<p>I'm trying to calculate a Keras metric in NumPy rather than in TensorFlow.</p> <p>As you usually don't need the gradient flow through a pure metric, it would be fine to calculate the metric in NumPy.</p> <p>I extended <code>tf.keras.metrics.Metrics</code> and have overwritten the <code>update_state()</code> method. ...
<p>wrap your function within <code>tf.py_function</code></p> <p><a href="https://www.tensorflow.org/api_docs/python/tf/py_function" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/py_function</a></p> <p>Keras wants to build a graph beforehand, but NumPy requires the computation to be eager. <cod...
python|numpy|tensorflow|keras|metrics
0
362,369
68,218,567
How can I create a new column that could tell me if specific columns have NaN values
<p><a href="https://i.stack.imgur.com/lX96o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lX96o.png" alt="DataFrame" /></a></p> <p>Saying that I have a DataFrame with 6 Columns and I want to add a new colum that could give me a 1 when column 3 to 6 is NaN and a 0 when not all of them are <code>NaN<...
<p>IIUC, here's one way:</p> <pre><code>df['&lt;New Col Name&gt;'] = df.set_index(['Date', 'Name']).isna().all(1).astype(int) </code></pre>
python|pandas
0
362,370
68,431,800
Merging dataframes on two columns alternative solution
<p>I have been trying to find an alternative (possibly more elegant) solution for the following code but without any luck. Here is my code:</p> <pre class="lang-py prettyprint-override"><code>import os import pandas as pd os.chdir(os.getcwd()) df1 = pd.DataFrame({'Month': [1]*6 + [13]*6, 'Temp': [0...
<p>It seems you don't need <code>Place</code> column from <code>df1</code>, you can just drop it before merging:</p> <pre><code>(df1.drop('Place', axis=1) .merge(df2, how='left', on=['Temp', 'Month']) .fillna({'Place': 0})) # Month Temp Place2 Place3 Place #0 1 0 1 2 0.0 #1 ...
python|pandas|dataframe
0
362,371
68,231,104
Extract part of a 3 D dataframe
<p>I have a 3d dataframe. looks like this:</p> <pre><code> d1 d2 d3 A B C D... A B C D... A B C D.. 0 1 2 </code></pre> <p>How could I extract only column A &amp; B from every d1,d2.....? I desire to take the dataframe like this:</p> <pre><code> d1 d2 d3 A B A B A B 0 1...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.isin.html#pandas-index-isin" rel="nofollow noreferrer"><code>Index.isin</code></a> on the level 1 values of columns then select with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel=...
python|pandas|dataframe
2
362,372
68,263,670
Training dataset repeatedly - Keras
<p>I am doing an image classification task using Keras.</p> <p>I used the vgg16 architecture, I thought it is easier to do, the task is to classify the image having tumor or not in MRI images.</p> <p>As usual, I read and make all the images in same shape (224×224×3) and normalised by dividing all the images by 255. The...
<p>When using <code>train_test_split</code> and validating in different sessions, always set your random seed. Otherwise, you will be using different splits, and leaking data like you stated. The model is not &quot;learning&quot; more, rather is being validated on data that it has already trained on. You will likely ge...
tensorflow|keras|deep-learning
0
362,373
68,270,092
How to remove an excel file with same name as pdf counterpart?
<p>Imagine you want to remove a file in a directory which is Excel, but only if it is the same name as a PDF in the same directory.</p> <p>Have tried the following:</p> <pre><code>import os #if both excel and pdf, remove excel directory = r&quot;C:\Users\Max12\Desktop\xml\git\yourubl\attachments\75090058\Statu...
<p>You can use <code>pathlib</code> to accomplish that straightforward:</p> <pre><code>import pathlib directory = pathlib.Path(r&quot;C:\Users\Max12\Desktop\xml\git\yourubl\attachments\75090058\Status\Verwerking&quot;) for f in directory.glob('*.xlsx'): if f.with_suffix('.pdf').exists(): f.unlink() </code...
python|excel|pandas
1
362,374
68,355,473
Python Pandas: How do I sumproduct by rows with an if condition?
<p>I know there are some questions on Stack Overflow on Sumproduct but the solution are not working for me. I am also new to Python Pandas.</p> <p>For each row, I want to do a sumproduct of certain columns only if column['2020'] !=0. I used the below code, but get error:</p> <p><strong>IndexError: ('index 2018 is out o...
<p>Your column names are most likely <strong>strings</strong>, not integers.</p> <p>To confirm it, run <code>df_copy.columns</code> and you should receive something like:</p> <pre><code>Index(['2020', '2018', '2019'], dtype='object') </code></pre> <p>(note apostrophes surrounding column names).</p> <p>So change your co...
python|pandas|sumproduct
2
362,375
68,176,859
How to get the "center" of grayscale numpy image
<p>I have a 2D numpy array <code>arr</code> of shape <code>(m,n)</code> with nonnegative values. I would like to find a pair <code>(k,l)</code> such that</p> <ul> <li>the difference between <code>sum(arr[:k, :])</code> and <code>sum(arr[k:, :])</code> is minimal</li> <li>similarly, the difference between <code>sum(arr[...
<p>This works:</p> <pre><code>sum_to_k = np.pad(np.cumsum(np.sum(a, axis=1)), (1, 0)) sum_to_l = np.pad(np.cumsum(np.sum(a, axis=0)), (1, 0)) k = np.argmin(np.abs(sum_to_k - (sum_to_k[-1] - sum_to_k))) l = np.argmin(np.abs(sum_to_l - (sum_to_l[-1] - sum_to_l))) </code></pre>
python|numpy
1
362,376
68,148,400
Concat following row to the right of a df - python
<p>I'm aiming to subset a pandas df using a condition and append those rows to the right of a df. For example, where <code>Num2</code> is equal to <code>1</code>, I want to take the following row and append it to the right of the <code>df</code>. The following appends <em>every</em> row, where as I just want to append ...
<p>You can try:</p> <pre><code>df=df.join(df.shift(-1).mask(df['Num2'].ne(1)).drop('Value',1).add_suffix('2')) </code></pre> <p><strong>OR</strong></p> <pre><code>ones.index=ones.index-1 df=df.join(ones.drop('Value',1).add_suffix('2')) #OR(use any 1 since both method doing the same thing) df=pd.concat([df,ones.drop('V...
python|pandas
1
362,377
68,311,105
How to labeling with Pandas (.map)?
<p>label with pandas (.map) in the following table</p> <pre><code>m2m_similarity.columns = ['MoviId 1','MoviId 2','similarity_score'] m2m_similarity.head(3) </code></pre> <p>I have tried to get the label slightly-similar, similar, and exacly</p> <pre><code>m2m_similarity['analysis'] = m2m_similarity['similarity_score']...
<p>A better way would be:</p> <pre><code>m2m_similarity['analysis'] = m2m_similarity['similarity_score'].map(lambda s: 'Exacly' if round(s, 2) == 1 else ('similar' if round(s, 2) &gt;= 0.5 else 'slightly-similar')) </code></pre> <p>As it would cover all the options in between. And anyway make sure that in <code>similar...
python|pandas|jupyter-notebook|data-science
1
362,378
68,122,685
pandas- kernel restarting: the kernel for .ipynb appears to have died. it will restart automatically
<h1>Update</h1> <p>I ran a <code>docker-container</code> for a <code>jupyter-notebook</code>, however when running a <code>pandas</code>-based block, after a few seconds the system returns:</p> <blockquote> <p>kernel restarting: the kernel for .ipynb appears to have died. it will restart automatically.</p> </blockquote...
<p>The issue was related to the number of iterations, it was necessary to decrease iterations.</p> <p>First, renamed the function to <code>convert_to_percentage()</code>, then iterate over each key and value to replace characters:</p> <pre><code> ############# convert_to_percentage(string) ################# # string :...
python|pandas|linux|docker|jupyter-notebook
0
362,379
68,299,454
What is smart way to get batched gather?
<p>I have two matrices, <code>A</code> and <code>B</code>, with shapes <code>(n, m, k)</code> and <code>(n, m)</code> respectively. <code>n</code> is the batch size, <code>m</code> is the amount of data in a batch, and <code>k</code> is the feature size.</p> <p>Each element of <code>B</code> is an index less than <code...
<p>You can use</p> <pre><code>a[torch.arange(n)[:, None], b] </code></pre> <p>An example:</p> <pre><code>&gt;&gt;&gt; n, m, k = 3, 2, 5 &gt;&gt;&gt; a = torch.arange(30).view(n, m, k) &gt;&gt;&gt; b = torch.randint(high=m, size=(n,m)) # first indexer (of shape (n, 1)) &gt;&gt;&gt; torch.arange(n)[:, None] tensor([[0]...
python|pytorch
2
362,380
68,339,744
Difference in logistic regression result when using StandardScaler
<p>I have a dataframe: <code>df = pd.read_excel</code> I did <code>classifier.predict(df)</code><br> And another thing I tried is doing <code>df = sc.transform(df)</code> and then doing <br><code>classifier.predict(df)</code> The result was different. What could be the reason for this<br> Which one is accurate? <br> I ...
<p>You can test out which model is more accurate by using cross_val_score from sckit-learn(See documentation: <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_score.html" rel="nofollow noreferrer">https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross...
python|pandas|logistic-regression
1
362,381
68,359,360
Reading Excel files in a subfolder and how to use subfolder name as a new column value?
<p>I've got a main folder and then I've got folders inside of that for different countries with Excel files.</p> <p>I was wondering if someone knew how I can read all these Excel files and use the subfolder/country name as a column value.</p> <p>Then I am planning to concatenate all these files as they are all the same...
<p>You can try something like that:</p> <pre><code>import pandas as pd import pathlib main_folder = './data' data = [] for xlsxfile in pathlib.Path(main_folder).glob('**/*.xlsx'): df = pd.read_excel(xlsxfile) df['dirpath'] = xlsxfile.parent data.append(df) df = pd.concat(data) </code></pre>
python-3.x|pandas|dataframe
0
362,382
68,416,974
Convert string to colum
<p>I have a simple data frame, and I am developing a sentiment analysis.</p> <p>This is the code and the reproducible example</p> <pre><code>import transformers from pysentimiento import SentimentAnalyzer from pysentimiento import EmotionAnalyzer analyzer = SentimentAnalyzer(lang=&quot;en&quot;) emotion_analyzer = Emo...
<p>The results must be converted into a <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.html" rel="nofollow noreferrer"><code>pd.Series</code></a> then <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>join</code></a> back to the DataFr...
pandas|dataframe
0
362,383
68,430,210
How to limit the size of the features vector in Wav2Vec?
<p>I'm attempting to receive a features vector of short wav (audio) files using wav2vec by using <a href="https://huggingface.co/transformers/model_doc/wav2vec2.html" rel="nofollow noreferrer">Hugging Face Transformers</a>.</p> <p>However, for unknown reasons, no matter which approach I use to control the output size, ...
<p>At the moment <code>truncation</code> is not supported by the feature extractor in Hugging Face, so if you want to &quot;pad&quot; to a &quot;max_length&quot; that is shorter than the sample length, it simply won't change anything since no padding is needed.</p> <p>However, we should definitely add a <code>truncatio...
python|numpy|huggingface-transformers|transformer-model
2
362,384
68,156,273
Losing values not only zeroes during read csv in Python Pandas?
<p>I have huge problem to read numbers by pandas. When I want to read csv where are rows like below:</p> <pre><code>001234 1245600 123140 </code></pre> <p>And so one... sometimes zeroes are reading, sometimes not... Moreover, sometimes also other values like 1,2,3 are also not reatten, What can I do? I tried many solut...
<p>You need to specify the column as a string when reading in the data. Otherwise leading zeros are dropped:</p> <p>Correct:</p> <pre><code>df = pd.read_csv(r'Desktop\test\test.csv', header=None, dtype={0:'str'}) df Out[1]: 0 0 001234 1 1245600 2 123140 </code></pre> <p>If there are multiple columns and ...
python|pandas|dataframe|csv
0
362,385
68,271,586
Conv2D padding in TensorFlow and PyTorch
<p>I am trying to convert <code>TensorFlow</code> model to <code>PyTorch</code> but having trouble with <code>padding</code>. My code for for relevant platforms are as follow:</p> <p><strong>TensorFlow</strong></p> <pre><code>conv1 = tf.layers.conv2d( inputs=input_layer, filters=32, ...
<p>To answer your questions:</p> <p>The reason why Pytorch doesn't have padding = 'same' to quite simply put it is due to its dynamic computation graph in comparison to Tensorflow static graph.</p> <ol> <li><p>Both the codes are not equivalent as different padding is used.</p> </li> <li><p>'Same' padding tries to pad e...
tensorflow|pytorch|conv-neural-network
2
362,386
68,274,569
Can't update StatsModels SARIMAX with new observation (ValueError)
<p>I'm trying to run out-of-sample validations on a time-series dataset using SciKitLearn's <code>TimeSeriesSplit()</code> to create train/test folds.</p> <p>The idea is to train Statsmodel's SARIMAX on the train folds and then validate on the test folds without refitting the model. To do that we must iteratively appen...
<p>Got it! It was silly.</p> <p>The <code>.append()</code> method of the SARIMAX model <em>returns</em> the model itself rather than changing the data stored in the model.</p> <p>So the correct code is simmply: <code>model_fitted = model_fitted.append(next_row, refit=False)</code></p>
python|pandas|time-series|statsmodels|arima
3
362,387
68,128,686
Python Pandas concatenate every 2nd row to previous row
<p>I have a Pandas dataframe similar to this one:</p> <pre><code> age name sex 0 30 jon male 1 blue php null 2 18 jane female 3 orange c++ null </code></pre> <p>and I am trying to concatenate every second row to the previous one adding extra columns:</p> <pre><code> age ...
<p>You can create a new dataframe by slicing the dataframe using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a> with a step of 2:</p> <pre><code>cols = ['age', 'name', 'sex'] new_cols = ['colour', 'language', 'other'] d = ...
python|pandas|dataframe|concatenation|row
2
362,388
68,378,256
Pandas: what is truth value condition when dealing with missing data
<p>I have a function that creates a ratio. It is defined as</p> <pre><code>def create_ratio(data,num,den): if data[num].isnull(): ratio = -9997 if data[den].isnull(): ratio = -9998 if data[num].isnull() &amp; data[den].isnull(): ratio = -9999 else: ratio = data[num]/data[...
<ul> <li>you are mixing between scalars and series, where your function needs to return a series or array given its calling context</li> <li>as simple way as any to implement this conditional logic is <code>np.select()</code></li> <li>have simulated data, including missing values to meet your use cases</li> </ul> <pre...
pandas|missing-data
0
362,389
68,363,794
Lookup a single value using a multi-column key from Pandas DataFrame
<p>This thread doesn't seem to cover a situation I am routinely in.</p> <p><a href="https://stackoverflow.com/questions/33027643/return-single-cell-value-from-pandas-dataframe">Return single cell value from Pandas DataFrame</a></p> <p>How does one return a single value, not a series or dataframe using a set of column c...
<p>If the combination of columns <code>A</code> and <code>B</code> is unique then we can set the index in advance to efficiently retrieve a single value</p> <pre><code>df.set_index(['A', 'B']).loc[(1, 3), 'C'] </code></pre> <p>Alternative approach with <code>item</code></p> <pre><code>df.loc[df['A'].eq(1) &amp; df['B']...
python|pandas|dataframe
1
362,390
68,261,409
Getting labels for legend after graphing pivot of dataframe in pandas
<p>I am trying to have my plot show a legend where the column each value came from would have a label. I did not separate the plt.plot() from the pivot step but want to know if it is still possible to have a legend. One does not show up at all and if I add</p> <pre><code>plt.plot(df_EPErrorPercentByWeekAndDC.pivot(inde...
<p>Either save the pivoted frame then specify the legend as the columns:</p> <pre><code>df['Error Percent'] = df['Error Percent'].str[:-1].astype(float) plt.xticks(rotation=90) pivoted_df = df.pivot(index='hellofresh delivery week', columns='DC', values='Error Percent') plt.plot(pivoted_df) plt.le...
python|pandas|matplotlib
0
362,391
68,050,302
Check missing row in specific column and then add it to the dataframe
<p>I want the code to check if the dataframe has all elements of period_list. If not I want to add that element to the dataframe, the values associated with the element will be zero. I wrote this and it didn't work Dataframe: test_1</p> <pre><code> Period A B C 0 2018 - Q2 1 0 1 1 2018 - Q...
<p>Try with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.set_index.html#pandas-dataframe-set-index" rel="nofollow noreferrer"><code>set_index</code></a> + <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.reindex.html#pandas-dataframe-reindex" rel="nofollow noreferrer"><co...
python|pandas
1
362,392
68,206,512
How to convert epoch time to GMT + 7 time in pandas dataframe?
<p>I have a pandas dataframe that has a column created_date which is in epoch format. I wanted to use a filter condition as shown below.</p> <p>Dataframe sample</p> <pre><code> created_time updated_time sys_time last_action_time account_id \ 0 1624473000000 1624459148023 1624459148023 0...
<p>First : Strip last 3 digits from column &quot;created_time&quot;, it seems that epoch lengh is only 9-10 and you have 13 :</p> <pre><code>df['created_time'] = df['created_time'].astype(str).apply(lambda x: x[:-3]) </code></pre> <p>Second : Convert from Unix epoch to datetime :</p> <pre><code>df['created_time'] = pd....
python|pandas|dataframe|data-conversion
0
362,393
68,409,829
Delete rows above headers in a CSV using Python Pandas
<p>I need to clean up a files using Pandas. But the raw files we are using have a couple of rows above the column headers that I need to erase before getting to work. I do not find how to get rid of them.</p> <p>I suppose this has to be done before generating the frame.</p> <p>Can someone help?</p> <p>Thanks in advan...
<p>You can try using the <code>skiprows</code> parameter in <code>read_csv()</code> :</p> <pre class="lang-py prettyprint-override"><code>pd.read_csv('filename.csv', skiprows=5) </code></pre>
python|pandas|dataframe|rows
1
362,394
68,446,951
Is there a way to replace True/False with string values in Pandas?
<p>The pandas data frame looks like this:</p> <pre><code> job_url 0 https://neuvoo.ca/view/?id=34134414434 1 https://zip.com/view/?id=35453453454 2 https://neuvoo.com/view/?id=2452444252 </code></pre> <p>I want to turn all the strings beginning with 'https://neuvoo.ca' into 'Canada'.</p> <p>My solution to...
<p>Let's try with <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a> instead:</p> <pre><code>import numpy as np import pandas as pd csv_file = pd.DataFrame({ 'job_url': ['https://neuvoo.ca/view/?id=34134414434', 'https://z...
python|python-3.x|pandas|dataframe|replace
2
362,395
68,185,164
NaN output when multiplying row and column of dataframe in pandas
<p>I have two data frames the first one looks like this: <img src="https://i.stack.imgur.com/fGDOa.png" alt="first data frame" /></p> <p>and the second one like so: <img src="https://i.stack.imgur.com/J60yW.png" alt="second data frame" /></p> <p>I am trying to multiply the values in number of donors column of the secon...
<p>Your second dataframe has dtype <code>object</code>, you must convert it to <code>float</code></p> <pre><code>df_sls.iloc[0,3:-1].astype(float) </code></pre>
pandas|dataframe|nan|multiplication
1
362,396
68,323,680
Counting sequences of numbers in an array?
<p>I have the following dataframe for a year of data:</p> <pre><code> lat lon date month ssta 90th 10th threshold year dayofyear 21680 30.375 273.875 1982-01-01 1 0.995117 1.566498 -1.620501 0 1982 1 21681 30.375 273.875 1982-01-02 1 ...
<p>If I understand you correctly you're just looking for neighboring values that are more than 5 apart by value?! If so you can just shift the array by 1 and compare like so</p> <pre><code>arr[np.argwhere(np.abs(arr-np.roll(arr,-1)) &gt;= 5)] </code></pre> <p>This almost gives your desired output just as a 3,1 array. I...
python|pandas|numpy
0
362,397
68,419,707
Prediction limit or intervals in neural networks
<p>I have a simple graph neural network in TensorFlow/python which I use in regression.</p> <p>My dataset y-values are always in the interval of [0,1] as a float number.</p> <p>But a lot of predictions are smaller than 0 or larger than 1. This issue greatly reduces performance.</p> <p>Is there any way I can set a limit...
<p>I am not sure of the architecture of your neural network. However, a sigmoid activation function should restrict the output values between [0, 1].</p> <p>You can find more information here - <a href="https://www.tensorflow.org/api_docs/python/tf/keras/activations/sigmoid" rel="nofollow noreferrer">https://www.tensor...
python|tensorflow|neural-network
0
362,398
68,326,773
Keras multi-label classification: Failed to convert a NumPy array to a Tensor (Unsupported object type int)
<p>I am trying to do multi-label classification using Keras. I got my dataset from kaggle.</p> <p>Link to dataset: <a href="https://www.kaggle.com/dadajonjurakuziev/movieposter" rel="nofollow noreferrer">https://www.kaggle.com/dadajonjurakuziev/movieposter</a></p> <p>I am getting an error when I am trying to fit the mo...
<p>The error is the same of the question <a href="https://stackoverflow.com/q/68320743/16401339">Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray) on ImageDataGenerator in Keras</a>.</p> <p>The function <code>model.fit</code> expects <code>X_train</code> and <code>y_train</code> to be ...
python|numpy|tensorflow|keras
0
362,399
68,117,561
Pyvis network keeps on moving
<p>I have a text corpus for which I want to visualize the co-occurence of words as a network. To do so, I have created a pd Dataframe <code>cooc_pd</code> with the columns <code>Source</code>,<code>Target</code> and <code>Weight</code>. The first two are nodes and <code>Weight</code> indicates how often the two nodes (...
<p>I was having the same problem with my graph, it kept moving in a noisy way.</p> <p>Reading the <a href="https://pyvis.readthedocs.io/en/latest/documentation.html" rel="nofollow noreferrer">documentation</a>, I've found a method called <strong>repulsion</strong>, which &quot;Set the physics attribute of the entire ne...
python-3.x|pandas|graph|networkx|pyvis
4